name = input("Hello there!\n I will be your financial advisor for today.\n I will ask a few questions to get to know you.\n My name in Greg, what's your?\n")
print ("Nice to meet you", name,". You have such a beautiful name!\n Alright, let's get down to business.\n")

hours_per_week = input("How many hours do you work per week? \n")
hours_per_week = float (hours_per_week)
hours_per_year = hours_per_week*4*12
print("You work", hours_per_year, "hours per year!\n")

wage_per_hour = input("What's your hourly wage? \n")
wage_per_hour = float(wage_per_hour)
wage_per_year= wage_per_hour*hours_per_year
print("You make", wage_per_year, "dollars per year! \n")

taxes = input("How much percentage % of taxes do you pay? \n Please type your answer as numbers only, Thanks! \n")
taxes = float(taxes)
taxes = taxes/100

taxes_paid = taxes*wage_per_year
print("You pay the government", taxes_paid, "dollars a year!\n Thank you for being a good citizen!\n")

gross_pay = wage_per_year
print ("Your gross pay is", gross_pay, "dollars a year!\n")

net_pay = gross_pay - taxes_paid
print("After paying your taxes, like the good citizen you are, your net pay is", net_pay,"dollars a year!\n Glad to be of service to you,", name,"!\n")


from nipype.interfaces.utility import Function
from nipype.pipeline import Node

def tsv2subjectinfo(in_file, exclude=None):

    import pandas as pd
    from nipype.interfaces.base import Bunch
    import numpy as np

    events = pd.read_csv(in_file, sep=str('\t'))

    if exclude is not None:  # not tested
        events.drop(exclude, axis=1, inplace=True)

    conditions = sorted(events['trial_type'].unique())
    onsets = [events['onset'][events['trial_type'] == tt].tolist() for tt in conditions]
    durations = [events['duration'][events['trial_type'] == tt].tolist() for tt in conditions]

    if 'weight' in events.columns:
        amplitudes = [events['weight'][events['trial_type'] == tt].tolist() for tt in conditions]
    else:
        amplitudes = [np.ones(len(d)) for d in durations]

    bunch = Bunch(conditions=conditions,
                  onsets=onsets,
                  durations=durations,
                  amplitudes=amplitudes)

    return bunch

Tsv2subjectinfo = Function(function=tsv2subjectinfo, input_names=['in_file', 'exclude'],
                           output_names=['subject_info'])

def getpercentthresh(value, percentage):
    return percentage * value

Getpercentthresh = Function(function=getpercentthresh, input_names=['value', 'percentage'],
                            output_names=['out_val'])

def getinormscale(medianval):
    return 10000. / medianval

Getinormscale = Function(function=getinormscale, input_names=['medianval'],
                         output_names=['value'])

def getusan(in_file, brightness_thresh):
    return [(in_file, brightness_thresh)]

Getusan = Function(function=getusan, input_names=['in_file', 'brightness_thresh'],
                   output_names=['usan'])

def find_fsl_mni_files():

    import os
    if 'FSLDIR' in os.environ:
        fsldir = os.environ['FSLDIR']
    else:
        raise ValueError("You don't have FSL installed! "
                         "Cannot run this pipeline")

    mni_head = os.path.join(fsldir, 'data', 'standard', 'MNI152_T1_2mm.nii.gz')
    mni_brain = os.path.join(fsldir, 'data', 'standard', 'MNI152_T1_2mm_brain.nii.gz')
    mni_mask = os.path.join(fsldir, 'data', 'standard', 'MNI152_T1_2mm_brain_mask_dil.nii.gz')
    return mni_head, mni_brain, mni_mask

Find_fsl_mni_files = Function(function=find_fsl_mni_files, input_names=None,
                              output_names=['MNI_head', 'MNI_brain', 'MNI_mask'])


#!/usr/bin/env python

"""
test06.py -- producer adds to fixed-sized list; scanner uses them

OPTIONS:
-v  verbose multiprocessing output
"""

import logging
import logging.handlers
import multiprocessing
import sys
import time

LOG_FILENAME = 'test06.log'

def producer(obj_list):
    """
    add an item to list every 2 sec; ensure fixed size list
    """
    logger = multiprocessing.get_logger()
    logger.info('start')
    while True:
        try:
            time.sleep(0.5)
        except KeyboardInterrupt:
            return
        msg = 'ding: {:04d}'.format(int(time.time()) % 10000)
        logger.info('put: %s', msg)
        del obj_list[0]
        obj_list.append(msg)

def scanner(obj_list):
    """
    every now and then, run calculation on obj_list
    """
    logger = multiprocessing.get_logger()
    logger.info('start')
    while True:
        try:
            time.sleep(5)
        except KeyboardInterrupt:
            return
        logger.info('items: %s', list(obj_list))

def main():
    opt_verbose = '-v' in sys.argv[1:]
    logger = multiprocessing.log_to_stderr(
        level=logging.DEBUG if opt_verbose else logging.INFO,
    )
    handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=1024,
                                                   backupCount=5)
    logger.addHandler(handler)

    logger.info('setup')

    # create fixed-length list, shared between producer & consumer
    manager = multiprocessing.Manager()
    my_obj_list = manager.list([None] * 10)

    multiprocessing.Process(target=producer, args=(my_obj_list,),
                            name='producer',).start()

    multiprocessing.Process(target=scanner, args=(my_obj_list,),
                            name='scanner',).start()

    logger.info('running forever')
    try:
        manager.join()  # wait until both workers die
    except KeyboardInterrupt:
        pass
    logger.info('done')

if __name__ == '__main__':
    main()


#!/usr/bin/env python
import pika

def send(data):
    connection = pika.BlockingConnection(
        pika.URLParameters('amqp://admin:admin@rabbitmq:5672'))
    channel = connection.channel()

    channel.queue_declare(queue='model')

    channel.basic_publish(exchange='', routing_key='model', body=data)
    print(" [x] Sent 'Hello World!'")
    connection.close()


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('admin', '0030_giftbalancechangelog'),
    ]

    operations = [
        migrations.CreateModel(
            name='GiftOrder',
            fields=[
                ('id', models.AutoField(auto_created=True, serialize=False, primary_key=True, verbose_name='ID')),
                ('order_id', models.CharField(max_length=32, verbose_name='订单号')),
                ('page_id', models.CharField(max_length=64, verbose_name='货架号')),
                ('trans_id', models.CharField(max_length=32, verbose_name='微信支付交易订单号')),
                ('create_time', models.IntegerField(verbose_name='订单创建时间')),
                ('pay_finish_time', models.IntegerField(verbose_name='订单支付时间')),
                ('total_price', models.IntegerField(verbose_name='全部金额')),
                ('open_id', models.CharField(max_length=32, verbose_name='购买者')),
                ('accepter_openid', models.CharField(max_length=32, verbose_name='接收者')),
            ],
            options={
                'db_table': 'gift_order',
            },
        ),
        migrations.CreateModel(
            name='GiftOrderInfo',
            fields=[
                ('id', models.AutoField(auto_created=True, serialize=False, primary_key=True, verbose_name='ID')),
                ('order_id', models.IntegerField(verbose_name='对应gift_order的自增长id')),
                ('card_id', models.CharField(max_length=32, verbose_name='卡类型ID')),
                ('price', models.IntegerField(verbose_name='卡面值')),
                ('code', models.CharField(max_length=32, verbose_name='code')),
            ],
            options={
                'db_table': 'gift_order_info',
            },
        ),
        migrations.AddField(
            model_name='giftbalancechangelog',
            name='status',
            field=models.CharField(default='0', max_length=1, verbose_name='code状态u(0:未销售;1:已销售)'),
        ),
    ]


# Copyright 2014-present, Apstra, Inc. All rights reserved.
#
# This source code is licensed under End User License Agreement found in the
# LICENSE file at http://www.apstra.com/community/eula

import retrying

from apstra.aosom.exc import SessionRqstError
from apstra.aosom.collection import Collection, CollectionItem

__all__ = ['DeviceManager']

class DeviceServices(object):
    def __init__(self, device):
        self.device = device

    @property
    def names(self):
        if 'services' not in self.device.value:
            self.device.read()
        return self.device.value['services']

    def __getitem__(self, service):
        got = self.device.api.requests.get(self.device.url + "/%s" % service)
        if not got.ok:
            raise SessionRqstError(message="unable to retrieve service=%s" % service,
                                   resp=got)
        return got.json()['items']

    def __str__(self):
        return str(self.names)

    __repr__ = __str__

class DeviceItem(CollectionItem):
    @property
    def services(self):
        return DeviceServices(self)

    @property
    def state(self):
        """
        Returns
        -------
        str
            current AOS management state value, e.g. "IS-ACTIVE", meaning "In service, Active".
        """
        return self.value['status']['state']

    @property
    def is_approved(self):
        """
        Returns
        -------
        True if this device is approved
        False otherwise
        """
        return bool(self.id in self.collection.approved.ids)

    @property
    def user_config(self):
        """
        As a **getter** returns the current `user_config` dictionary of values.
        As a **setter** provides the ability to set the `user_config` values.

        Returns
        -------
        dict
            The 'user_config' dictionary of values

        Raises
        ------
        SessionRqstError
            when error occurs in setting the `user_config` value
        """
        self.read()
        return self.value.get('user_config')

    @user_config.setter
    def user_config(self, value):
        got = self.api.requests.put(
            self.url,
            json=dict(user_config=value))

        if not got.ok:
            raise SessionRqstError(
                message='unable to set user_config',
                resp=got)

    def approve(self, location=None):
        """
        Approves this device for use by the AOS system.  If the device is already approved, then this
        method will return False.

        Parameters
        ----------
        location : str
            optional User value that can be used to identify where this device is located in the network.

        Returns
        -------
        True if the device is approved
        False if the device does not need to be approved

        Raises
        ------
        SessionRqstError
            An error has occurred attempting to make the approve request with the AOS Server API
        """
        if self.state != 'OOS-QUARANTINED':
            return False

        self.user_config = dict(
            admin_state='normal',
            aos_hcl_model=self.value['facts']['aos_hcl_model'],
            location=location or '')

        self.collection.approved.update([self.id])

        return True

class Approved(object):
    def __init__(self, api):
        self.api = api
        self.url = '%s/resources/device-pools/default_pool' % self.api.url

    @property
    def ids(self):
        return [item['id'] for item in self.get_devices()]

    def get(self):
        got = self.api.requests.get(self.url)
        if not got.ok:
            raise SessionRqstError(got)

        return got.json()

    def get_devices(self):
        return self.get()['devices']

    def update(self, device_keys):
        has_devices = self.get_devices()

        has_ids = set([dev['id'] for dev in has_devices])
        should_ids = has_ids | set(device_keys)
        diff_ids = has_ids ^ should_ids

        if not diff_ids:
            return   # nothing to add

        # need to append to what's already in the pool,
        # since this is a PUT action

        for new_id in diff_ids:
            has_devices.append(dict(id=new_id))

        timeout = 3000

        @retrying.retry(wait_fixed=1000, stop_max_delay=timeout)
        def put_updated():
            got = self.api.requests.put(
                self.url, json=dict(display_name='Default Pool',
                                    devices=has_devices))

            if not got.ok:
                raise SessionRqstError(
                    message='unable to update approved list: %s' % got.text,
                    resp=got)

        put_updated()

class DeviceManager(Collection):
    URI = 'systems'
    LABEL = 'device_key'
    Item = DeviceItem

    def __init__(self, owner):
        super(DeviceManager, self).__init__(owner)
        self.approved = Approved(owner.api)


#!/usr/bin/python
# -*- coding: Utf-8 -*

"""Module notes_amas"""

#----------------------------------------------------------
# Importation des librairies

import numpy as np
from matplotlib import pylab as plt
import matplotlib.pyplot as plt2
from math import *

#----------------------------------------------------------
# Variables globales empiriques

#Nombre maximal de croches sur une même note
nbr_croches = 2

#----------------------------------------------------------
# Fonctions

#on retire les portées de l'image
def enleve_portees(img,soluce):
	for x in range(img.shape[0]):
		for y in range(img.shape[1]):
			if round(y*soluce[0]+soluce[1]) == round(x):
				img[x][y] = 1
				img[x-1][y] = 1
				img[x+1][y] = 1 #peu précis mais imprécision des droites détectées oblige
	return img

def enleve_portees_liste(img,liste):
	img1 = np.zeros(img.shape,np.int)
	img2 = np.zeros(img.shape,np.int)
	for elt in liste:
		img1 = enleve_portees(img,elt)
		img2 = union(img2,img1)
	return img2

#Dessine un structurant adapté pour l'ouverture en tout ou rien
def cree_structurant(rayon):
	h = int(3 + 4*rayon)
	l = int(7 + 2*rayon)
	a = np.zeros((h,l),int)
	#2 : indifférent, blanc ou noir
	for x in range(h):
		for y in range(l):
			a[x][y] = 2

	#1: points blancs
	"""for y in range(1+rayon):
		a[0][y] = 1
		a[a.shape[0]-1][a.shape[1]-1-y] = 1"""
	"""for x in range(rayon):
		a[x][0] = 1
		a[a.shape[0]-1-x][a.shape[1]-1] = 1"""
	for x in range(h):
		a[x][0] = 1
		a[x][l-1] = 1

	#0: points noirs
	for x in range(1+rayon,a.shape[0]-(1+rayon)):
		for y in range(a.shape[1]):
			a[x][a.shape[1]/2] = 0
	for x in range(1+rayon,a.shape[0]/2+1):
		for y in range(a.shape[1]/2-(x-(1+rayon)),1+a.shape[1]/2+(x-(1+rayon))):
			a[x][y] = 0
			a[a.shape[0]-x-1][y] = 0
	return a

#détermine s'il y a une note à proximité de /collées à la barre verticale
def existe_note(img,ecart,i,j,seuil,coul):
	somme = 0
	rep = False
	ecart = int(round(ecart))
	for x in range(i-ecart,i):
		for y in range(j-ecart,j):
			if x < img.shape[0] and y < img.shape[1]:
				if img[x][y] == 0:
					somme = 1 + somme
				#plt.plot([j-ecart,j,j,j-ecart,j-ecart],[i-ecart-1,i-ecart-1,i-1,i-1,i-ecart-1])
	#si on remplit plus de 20% du carré "en bas"
	if somme*100 >= seuil*ecart*ecart:
		c1 = plt2.Circle(((2*j-ecart)/2,i),3*e/2,color=coul)
		plt2.gcf().gca().add_artist(c1)
		rep = True
	else:
		somme = 0
		for x in range(i-ecart,i):
			for y in range(j,j+ecart):
				if x < img.shape[0] and y < img.shape[1]:
					if img[x][y] == 0:
						somme = 1 + somme
					#plt.plot([j,j+ecart,j+ecart,j,j],[i-ecart+1,i-ecart+1,i+1,i+1,i-ecart+1])
		#si on remplit plus de 20% du carré "en haut"
		if somme*100 >= seuil*ecart*ecart:
			c1 = plt2.Circle(((2*j+ecart)/2,i),3*e/2,color=coul)
			plt2.gcf().gca().add_artist(c1)
			rep = True
	return rep

#pour chaque barre verticale identifiée, on regarde si c'est une note de musique
def existe_noire_img(img,liste,ecart,pc_note):
	for elt in liste:
		elt.append(existe_note(img,ecart,elt[1],elt[2],pc_note,'g'))
		elt.append(existe_note(img,ecart,elt[0],elt[2],pc_note,'g'))
	return liste

#identifie une éventuelle croche en haut d'une barre verticale
def existe_croche_haut(img,ecart,i,j,pc_cro):
	somme = 0
	rep = 0
	ecart = int(round(ecart))
	e2 = int(round(ecart/2))
	for x in range(i,i+e2):
		for y in range(j-e2,j):
			if x < img.shape[0] and y < img.shape[1]:
				if img[x][y] == 0:
					somme = 1 + somme
	if somme*100 >= pc_cro*e2*e2:
		p = plt2.Rectangle((j,i),e2,e2,color='b')
		plt2.gcf().gca().add_artist(p)
		rep = 1
	else:
		somme = 0
		for x in range(i,i+e2):
			for y in range(j,j+e2):
				if x < img.shape[0] and y < img.shape[1]:
					if img[x][y] == 0:
						somme = 1 + somme
		if somme*100 >= pc_cro*e2*e2:
			p = plt2.Rectangle((j,i),e2,e2,color='b')
			plt2.gcf().gca().add_artist(p)
			rep = 1
	return rep

#identifie une éventuelle croche en bas d'une barre verticale
def existe_croche_bas(img,ecart,i,j,pc_cro):
	somme = 0
	rep = 0
	ecart = int(round(ecart))
	e2 = int(round(ecart/2))
	for x in range(i-e2,i):
		for y in range(j-e2,j):
			if x < img.shape[0] and y < img.shape[1]:
				if img[x][y] == 0:
					somme = 1 + somme
	if somme*100 >= pc_cro*e2*e2:
		p = plt2.Rectangle((j-e2,i-e2),e2,e2,color='b')
		plt2.gcf().gca().add_artist(p)
		rep = 1
	else:
		somme = 0
		for x in range(i-e2,i):
			for y in range(j,j+e2):
				if x < img.shape[0] and y < img.shape[1]:
					if img[x][y] == 0:
						somme = 1 + somme
		if somme*100 >= pc_cro*e2*e2:
			p = plt2.Rectangle((j-e2,i-e2),e2,e2,color='b')
			plt2.gcf().gca().add_artist(p)
			rep = 1
	return rep

#jusqu'à nbr_croches croches
def existe_autre_croche(img,liste,ecart,pc_cro):
	ecart = int(round(ecart))
	for elt in liste:
		if len(elt) > 5:
			if elt[5] != 0:
				for i in range(1,nbr_croches):
					elt[5] = (existe_croche_haut(img,ecart,elt[0]+i*ecart,elt[2],pc_cro) or existe_croche_bas(img,ecart,elt[1]-i*ecart,elt[2],pc_cro)) + elt[5]
	return liste

#détermine suivant les résultats de l'existence de notes, l'existence de croches, de blanches ou de barres de mesure
def existe_croche_blanche_mesure(img,img2,liste,ecart,pc_cro,pc_blan):
	for elt in liste:
		#Si on a une noire en haut ou (exclusif) en bas
		if (not(elt[3]) and elt[4]) or (elt[3] and not(elt[4])):
			if elt[3]:
				elt.append(existe_croche_haut(img,ecart,elt[0],elt[2],pc_cro))
			else:
				elt.append(existe_croche_bas(img,ecart,elt[1],elt[2],pc_cro))
			#on regarde s'il y a d'autres croches
			liste = existe_autre_croche(img,liste,ecart,pc_cro)
			elt.extend([False,False])

		#s'il n'y a pas de noire
		elif (not(elt[3]) and not(elt[4])):
			#on met le nombre de croches à zéro
			elt.append(0)
			elt.append(existe_note(img2,ecart,elt[1],elt[2],pc_blan,'magenta'))
			elt.append(existe_note(img2,ecart,elt[0],elt[2],pc_blan,'magenta'))

			#c'est une barre de mesure (ni noire, ni blanche)
			if (not(elt[6]) and not(elt[7])):
				#elt.extend('m')
				x = [elt[2],elt[2]]
				y = [elt[0],elt[1]]
				plt.plot(x,y,'b')
	return liste

def max_matrice(img):
	m=0
	for i in range(img.shape[0]):
		for j in range(img.shape[1]):
			if img[i][j] > m:
				m = img[i][j]
	return m


import os
import json
import urllib
import logging
import threading
from contextlib import contextmanager
import requests

logger = logging.getLogger(__name__)

class Lock(object):
    def __init__(self, appName, server, releaseTimeout=60, token=None):
        self.appName = appName
        self.releaseTimeout = releaseTimeout
        self.server = server
        self.acquire_url = urllib.parse.urljoin(server, "./acquire")
        self.release_url = urllib.parse.urljoin(server, "./release")
        self.token = token

    def acquire(self, lockName, releaseTimeout=None):
        releaseTimeout = releaseTimeout or self.releaseTimeout
        params = {
            "appName": self.appName,
            "lockName": lockName,
            "releaseTimeout": releaseTimeout,
        }
        if self.token:
            params["token"] = self.token
        url = urllib.parse.urljoin(self.acquire_url, "?" + urllib.parse.urlencode((params)))
        respone = requests.get(url)
        result = json.loads(respone.content.decode("utf-8"))
        return result["success"]

    def safe_acquire(self, lockName, releaseTimeout=None):
        try:
            success = self.acquire(lockName, releaseTimeout)
        except Exception as e:
            logger.info("acquire lock failed: {0}".format(str(e)))
            success = False
        return success

    def release(self, lockName):
        params = {
            "appName": self.appName,
            "lockName": lockName,
        }
        if self.token:
            params["token"] = self.token
        url = urllib.parse.urljoin(self.release_url, "?" + urllib.parse.urlencode((params)))
        respone = requests.get(url)
        result = json.loads(respone.content.decode("utf-8"))
        return result["success"]

    def safe_release(self, lockName):
        try:
            success = self.release(lockName)
        except Exception as e:
            logger.info("release lock failed: {0}".format(str(e)))
            success = False
        return success

@contextmanager
def distlock(lockObject, lockName, releaseTimeout=None):
    locked = lockObject.safe_acquire(lockName, releaseTimeout)
    yield locked
    if locked:
        lockObject.safe_release(lockName)

def get_app_unique_name(prefix=None):
    if prefix is None:
        prefix = os.sys.argv[0]
    return "{prefix}:{pid}:{tid}".format(prefix=prefix, pid=os.getpid(), tid=threading.get_ident())


from django.forms.widgets import NullBooleanSelect, Widget
from django.http import JsonResponse, HttpResponse, HttpResponseRedirect
from django.shortcuts import render
import simplejson
from urllib.request import urlopen
import urllib
from datetime import datetime
from elasticsearch import Elasticsearch
from glob import glob
from elasticsearch_dsl import Search, Q, Index
from elasticsearch_dsl.query import MatchAll
from django.core import serializers

es = Elasticsearch("http://localhost:9200")

def rest(request):
	try:
		term = request.GET['term']
	except:
		term = ''
	try:
		year_from = request.GET['year_from']
	except:
		year_from = "0"
	try:
		year_to = request.GET['year_to']
	except:
		year_to = "3000"
	try:
		lon = request.GET['lon']
	except:
		lon = "0"
	try:
		lat = request.GET['lat']
	except:
		lat= "0"
	try:
		station = request.GET['station']
	except:
		station = '*'
	try:
		genre = request.GET['genre']
	except:
		genre='*'
	try:
		author = request.GET['author']
	except:
		author = '*'
	try:
		distributor = request.GET['distributor']
	except:
		distributor = '*'
	try:
		keywords = request.GET['keywords']
	except:
		keywords = '*'
	try:
		abstract = request.GET['abstract']
	except:
		abstract = '*'

	print(term)
	print(station)

	result = esearch(all_fields = term, year_from=year_from, year_to=year_to, lon=lon,
					lat=lat, station=station.lower(), genre=genre.lower(), author=author.lower(), distributor=distributor.lower(),
					keywords=keywords.lower(), abstract=abstract.lower())

	return JsonResponse(result, safe=True, json_dumps_params={'ensure_ascii': False})
#-------------------------------------------------------------------------

def home(request):
    #index_elastic()
    context = {}
    #context['form'] = SelectionForm()
    #context['result'] = SelectionForm.fields
    return render(request, "home.html", context)

def result(request):
    context = {}
    #context['result'] = SelectionForm()
    return render(request, "result.html")

#-------------------------------------------------------------------------

def search_index(request):
	results = []
	keywords_term = ""
	abstract_term = ""
	all_fields_term = ""
	year_from_term = ""
	year_to_term = ""

	"""
	if request.GET.get('keywords') and request.GET.get('abstract'):
		keywords_term = request.GET['keywords']
		abstract_term = request.GET['abstract']
	elif request.GET.get('keywords'):
		keywords_term = request.GET['keywords']
	elif request.GET.get('abstract'):
		abstract_term = request.GET['abstract']
	elif request.GET.get('all_fields'):
		all_fields_term = request.GET['all_fields']
	"""

	try:
		keywords_term = request.GET['keywords']
	except:
		pass
	try:
		abstract_term = request.GET['abstract']
	except:
		pass
	try:
		all_fields_term = request.GET['all_fields']
	except:
		pass
	try:
		year_from_term = request.GET['year_from']
	except:
		pass
	try:
		year_to_term = request.GET['year_to' ]
	except:
		pass

	search_term = keywords_term or abstract_term or all_fields_term or year_from_term or year_to_term

	#print(search_term)
	#results = esearch(keywords = keywords_term, abstract=abstract_term, all_terms = all_fields_term)
	results = esearch(keywords = keywords_term,
					  abstract = abstract_term,
					  all_fields = all_fields_term,
					  year_from = year_from_term,
					  year_to = year_to_term)

	#print(results)
	context = {'results': results, 'count': len(results), 'search_term': search_term }
	return render(request, 'search.html', context)

#----------------------------------------------------------------

#----------------------------------------------------------------

def esearch(keywords = "",
			abstract = "",
			all_fields = "",
			year_from = "",
			year_to = "",
			lon = "",
			lat= "",
			station= "",
			genre= "",
			author="",
			distributor="",
			):

	client = es
	if all_fields == "*":
		filter_type_all_fields = "wildcard"
	else:
		filter_type_all_fields = "match_phrase"

	if keywords == "*":
		filter_type_keywords = "wildcard"
	else:
		filter_type_keywords = "match"

	if abstract == "*":
		filter_type_abstract = "wildcard"
	else:
		filter_type_abstract = "match"

	if station == '*':
		filter_type_provider = "wildcard"
	else:
		filter_type_provider = "match_phrase"

	if genre == '*':
		filter_type_genre = "wildcard"
	else:
		filter_type_genre = "match_phrase"

	if author == '*':
		filter_type_author = "wildcard"
	else:
		filter_type_author = "match_phrase"

	if distributor == '*':
		filter_type_distributor = "wildcard"
	else:
		filter_type_distributor = "match_phrase"

	if lon == "0":
		lon_gte = "-90.0"
		lon_lte = "90.0"

	else:
		lon_gte = (float(lon) - 1)
		lon_lte = (float(lon) + 1)

	if lat == "0":
		lat_gte = "-90.0"
		lat_lte = "90.0"

	else:
		lat_gte = (float(lat) - 1)
		lat_lte = (float(lat) + 1)

	q = Q("bool",

		should=[
		Q(filter_type_all_fields, keywords=keywords),
		Q(filter_type_all_fields, abstract = abstract),
		Q(filter_type_all_fields, keywords=all_fields),
		Q(filter_type_all_fields, abstract = all_fields),
		Q(filter_type_all_fields, name = all_fields),
		Q(filter_type_all_fields, material = all_fields),
		Q(filter_type_all_fields, publisher = all_fields),
		Q(filter_type_all_fields, description = all_fields),
		Q(filter_type_all_fields, provider = all_fields),
		Q(filter_type_all_fields, distributionInfo = all_fields),
		Q(filter_type_all_fields, about = all_fields),
		Q(filter_type_all_fields, citation = all_fields),
		Q(filter_type_all_fields, responsibleParty = all_fields),
		Q(filter_type_all_fields, creator = all_fields),
		Q(filter_type_all_fields, accountablePerson = all_fields),
		Q(filter_type_all_fields, locationCreated = all_fields),
		],
		minimum_should_match=1
	)

	s = Search(using = client, index = "envri")\
			.filter("range", temporal = {'gte': year_from, 'lte': year_to})\
			.filter("range", longitude = {'gte': lon_gte, 'lte': lon_lte})\
			.filter("range", latitude = {'gte': lat_gte, 'lte': lat_lte})\
			.filter(filter_type_provider, provider = station)\
			.filter(filter_type_genre, genre = genre)\
			.filter(filter_type_distributor, distributor = distributor)\
			.filter(filter_type_author, author = author)\
			.query(q)[:1000]

	response = s.execute()
	search = get_results_rest(response)
	return search

def get_results_rest(response):
	results = {}
	for hit in response:
		result = {
			'identifier': str(hit.identifier),
			'name' : str(hit.name),
			'temporal' : str(hit.temporal),
			'author' : [name for name in hit.author],
			'landing_page' : str(hit.landing_page),
			'keywords' : [keyword for keyword in hit.keywords],
			'distributor' : str(hit.distributor),
			'station': str(hit.provider),
			'genre' : str(hit.genre),
			'longitude': str(hit.longitude),
			'latitude': str(hit.latitude),
			'abstract': str(hit.abstract)
		}
		results[hit.identifier] = result
	return results

def get_results(response):
	results = []
	for hit in response:
		result_tuple = (hit.identifier, hit.landing_page, hit.name)
		results.append(result_tuple)
	return results

#-------------------------------------------------------------

#-------------------------------------------------------------


# Bartłomiej Janiszewski

def unikalne_adresy_ip():
    plik = open('apache_logs', mode='r')
    ip_log = [(element.split())[0] for element in plik.readlines()]
    new_ip_log = list(set(ip_log))
    return new_ip_log

    # ip_log =[]
    # for element in plik.readlines():
    #     element = element.split()
    #     element = element[0]
    #     ip_log.append(element)
    #
    # new_ip_log = list(set(ip_log))
    # return new_ip_log

if __name__ == '__main__':
    print(unikalne_adresy_ip())


#!/usr/bin/python3
"""Task 1 - matrix divide
This is our function to be tested
"""

def matrix_divided(matrix, div):
    """Divides a list of integers or floats
    Args:
        matrix (list): a list of integers or floats
        div (int or div): second parameter
    Returns:
        Returns a new matrix
    Raises:
        TypeError: if the mattric or div is of the incorrect type
        ZeroDivisionError: if div is 0
    """
    if not isinstance(div, (float, int)) or div != div:
        raise TypeError('div must be a number')
    if div == 0:
        raise ZeroDivisionError('division by zero')
    if type(matrix) is not list:
        raise TypeError('matrix must be a matrix (list of lists) '
                        'of integers/floats')
    types_row = map(lambda x: isinstance(x, list), matrix)
    if not all(types_row):
        raise TypeError('matrix must be a matrix (list of lists) '
                        'of integers/floats')
    for row in matrix:
        types_element = map(lambda x: isinstance(x, (float, int)), row)
        if not all(types_element):
            raise TypeError('matrix must be a matrix (list of lists) '
                            'of integers/floats')
    for row in matrix:
        types_element = map(lambda x: x == x
                            and x != float('inf')
                            and x != -float('inf'),
                            row)
        if not all(types_element):
            raise OverflowError
    sizes = map(lambda x: len(x) == len(matrix[0]), matrix)
    if not all(sizes):
        raise TypeError('Each row of the matrix must have the same size')

    mat_div = list(map(lambda x:
                       list(map(lambda y:
                                round(y / div, 2), x)), matrix))
    return mat_div


'''
PROBLEM: For given string and substring, when does substring first occur?
DIFFICULTY: Trivial
'''

def v1(string, substring):
    if substring == '':
        return 0

    for i in range(0, len(string) - len(substring) + 1):
        for j in range(len(substring)):
            char = string[i+j]
            sub = substring[j]
            if char != sub:
                break
            if j == len(substring)-1:
                return i
    return -1

def main():
    tests = [
        [('hello', ''), 0],
        [('hello', 'll'), 2],
        [('helol', 'll'), -1],
    ]

    import testSuite
    t = testSuite.init(tests)
    t.test(v1)

main()


### Author: EMF Badge team
### Description: Handles connecting to a wifi access point based on a valid wifi.json file
### License: MIT

import network
import os
import json
import pyb

_nic = None

def nic():
    global _nic
    if not _nic:
        _nic = network.CC3100()
    return _nic

def create_default_config():
    with open("wifi.json", "wt") as file:
        file.write(json.dumps({"ssid": "emfcamp-insecure"}))
        file.flush()
    os.sync()

def connection_details():
    data = {}
    try:
        if "wifi.json" in os.listdir():
            with open("wifi.json") as f:
                data = json.loads(f.read())
    except ValueError as e:
        print(e)

    if "ssid" not in data:
        raise OSError("Couldn't find a valid wifi.json. See https://badge.emf.camp for more information")

    return data

def ssid():
    return connection_details()["ssid"]

def connect(wait = True, timeout = 10):
    if nic().is_connected():
        return
    details = connection_details()

    if "pw" in details and details["pw"]:
        if wait:
            nic().connect(details["ssid"], details["pw"], timeout=timeout)
            wait_for_connection()
        else:
            nic().connect(details["ssid"], details["pw"], timeout=None)
    else:
        if wait:
            nic().connect(details["ssid"], timeout=timeout)
            wait_for_connection()
        else:
            nic().connect(details["ssid"], timeout=None)

def wait_for_connection():
    while not nic().is_connected():
        nic().update()
        pyb.delay(100)

def is_connected():
    return nic().is_connected()

def connection_text():
    return "Connecting to wifi '%s'. If this doesn't work, please check your wifi.json. More information: badge.emfcamp.org/TiLDA_MK3/wifi" % (ssid())


import time
from devices import anode
import traceback
from multiprocessing import dummy

# init info for the wiener device.

class Anode:
    def __init__(self, com, channellist):
        """channellist example [QdoubleSpinBox, QlineEdit, QlineEdit2, real name in panel]"""
        self.channel = channellist
        self.scanner_time = 0.3
        self.voltage = 0
        self.current = 0
        self.setvoltage = 0
        dummy.Process(target=self.monitor, args=(com,)).start()

    def monitor(self, com):
        isinit = 1
        while isinit:
            try:
                self.anode = anode.Anode(com)
                self.setvoltage = self.anode.getvalidvoltagesetvalue()
                self.channel[0].setValue(self.setvoltage)

                self.channel[1].setText('0V')
                self.channel[2].setText('0uA')
                isinit = 0
            except:
                traceback.print_exc()
                time.sleep(5)

        while 1:
            try:
                setvoltage = self.channel[0].value()
                if self.setvoltage != setvoltage:
                    self.anode.setvoltage(setvoltage)
                    self.setvoltage = setvoltage

                voltage = self.anode.getvoltage()
                if self.voltage != voltage:
                    self.channel[1].setText(str(voltage)[:5]+'V')
                    self.voltage = voltage

                current = self.anode.getcurrent()
                if self.current != current:
                    self.channel[2].setText(str(current*10E5)[:5] + 'uA')
                    self.current = current

                time.sleep(self.scanner_time)
            except:
                traceback.print_exc()
                time.sleep(1)


import time
import os.path
from datetime import datetime

from classes.DocumentsAnalyzer import DocumentsAnalyzer

####
# Parameter definitions.
####
output_dir = os.path.abspath('../../outputs/dict_anal_2')
da = DocumentsAnalyzer(output_dir, False)

price_type = 'adjclose'
c_dicts = ['custom_dict_orig', 'custom_dict_fs_added', 'custom_dict_only_fs']
const_boundaries = (-2, 2)

from_date = datetime(2015, 8, 2).date()
to_date = datetime(2016, 4, 2).date()

dict_name = c_dicts[2]
base_filename = '_' + price_type + '_' + dict_name.replace('_', '-')

####
# Testing part
####
# start_time = time.time()
# print("TOTAL RUNTIME:")
# print("--- %s seconds ---" % (time.time() - start_time))

da.analyze_company(1, from_date, to_date, 'comp1' + base_filename, price_type, const_boundaries, dict_name, True, 2)
#da.analyze_company(217, from_date, to_date, 'comp1' + base_filename, price_type, const_boundaries, dict_name, True)

#da.analyze_all_companies(from_date, to_date, 'daystats' + base_filename, 'sma', const_boundaries, dict_name)
exit()

####
# EXECUTION part
####

for d_name in c_dicts:
    base_filename = '_' + price_type + '_' + d_name.replace('_', '-')
    da.analyze_all_companies(from_date, to_date, 'daystats' + base_filename, price_type, const_boundaries, d_name, 2)


import math
class VectorCMP:
    def ValueOfVector(self,Vector):
        total = 0.0
        for count in Vector.items():
            total = total + count ** 2
        return math.sqrt(total)

    def relation(self,Vector1,Vector2):
        DotProduct = 0
        for word,count in Vector1.items():
            if word in Vector2:
                DotProduct = DotProduct + count * Vector2[word]
        return DotProduct/(self.ValueOfVector(Vector1) * self.ValueOfVector(Vector2))


from os import urandom
from sys import byteorder
from time import sleep
import tweepy
import settings

cons_key = settings.CONSUMER_KEY
cons_sec = settings.CONSUMER_SECRET
acc_key = settings.ACCESS_KEY
acc_sec = settings.ACCESS_SECRET

auth = tweepy.auth.OAuthHandler(cons_key, cons_sec)
auth.set_access_token(acc_key, acc_sec)
api = tweepy.API(auth)

def big_number():
    num_l = []
    for i in range(1, 5):
        n_bytes = urandom(8)
        num = int.from_bytes(n_bytes, byteorder)
        num_l.insert(0, str(num))
    return "".join(num_l)

def tweet(api, tweet):
    api.update_status(tweet)
    sleep(86400)

try:
    print("INFO - Running")
    number = big_number()
    tweet(api, number)
except KeyboardInterrupt:
    print("WARN - Stopping")


# author: rluthi
# date: 04.2016
# version 0.1

import Settings as S
import subprocess
import logging
import time
import RPi.GPIO as GPIO
import numpy as np
import math

log = logging.getLogger('root')

class LampController:
  # Define GPIO signals to use
  # Physical pins 11,15,16,18
  # GPIO17,GPIO22,GPIO23,GPIO2
  stepPins = [17,22,23,24]

  # Define advanced sequence
  # as shown in manufacturers datasheet
  seq = [[1,0,0,1],
         [1,0,0,0],
         [1,1,0,0],
         [0,1,0,0],
         [0,1,1,0],
         [0,0,1,0],
         [0,0,1,1],
         [0,0,0,1]]

  # Default delay between steps [ms]
  delayBetweenSteps = 2 # [ms]

  # Steps needed to turn the lamp on at 100%
  steps2turnOnLamp = 3800

  def __init__(self):
    log.info("Initialization...")
    GPIO.setmode(GPIO.BCM)
    # Set all pins as output and to false
    for pin in self.stepPins:
      GPIO.setup(pin,GPIO.OUT)
      GPIO.output(pin, False)

    # Number of steps in one sequence
    self.stepsInOneSequence = len(self.seq)

    # Number of steps done during this sequence
    self.stepsDone = 0;
    self.running = False

  ## EXTERNAL METHODS ##

  def shutdown(self):
    log.info("Shutting down...")
    self.turnLampOff()
    self.setAllOutputGPIOtoFalse()

  def turnLampOnToPercentage(self, percentage):
    try:
      log.info("Setting the lamp to " + str(percentage) + "%")
      if (percentage > 100 or percentage < 0):
        log.warning("Wrong percentage value!")
        raise ValueError("Must be between 0 and 100")

      targetSteps = int(math.floor(self.steps2turnOnLamp * percentage / 100))
      nbStepsToGo = targetSteps - self.stepsDone
      self.doSteps(-nbStepsToGo)
      self.stepsDone += nbStepsToGo;
    except:
      log.warning("Something has gone wrong! Shutting down...")
      self.shutdown()

  ## INTERNAL METHODS ##

  def setAllOutputGPIOtoFalse(self):
    for pin in self.stepPins:
      GPIO.output(pin, False)
    log.info("All output GPIO set to False")

  def turnLampOff(self):
    log.info("Turing the lamp off!")
    self.doSteps(self.stepsDone);
    self.stepsDone = 0;

  # A step is a change of GPIO output values to push the pole further.
  def doSteps(self, nbSequencesToDo):
    nbStepsDone = 0;
    rotDirection = np.sign(nbSequencesToDo)
    nbSequencesDone = 0
    stepInSequence = 0
    delayBetweenSteps_s = self.delayBetweenSteps / float(1000)

    # The sign information of nbSequencesToDo is recorded in rotDirection
    nbSequencesToDo = abs(nbSequencesToDo)

    while nbSequencesDone < nbSequencesToDo:
      # print("Step: " + str(nbSequencesDone + 1))
      for i, pin in enumerate(self.stepPins):
        if self.seq[stepInSequence][i] == 1:
          GPIO.output(pin, True)
        else:
          GPIO.output(pin, False)

      # Increment or decrement stepInSequence depending of rotation direction
      stepInSequence += rotDirection * 1

      # Pause
      time.sleep(delayBetweenSteps_s)

      # Reinitialize stepInSequence when the end of a sequence is reached
      if (stepInSequence>=self.stepsInOneSequence):
        stepInSequence = 0
      elif (stepInSequence<0): # this happens when rotDirection = -1
        stepInSequence = 7
      # Increment the number of steps performed
      nbSequencesDone += 1


"""
M01_MAIN.PY
This is the main script to train and evaluate the LSTM model for the SWL
prediction
"""

from torch.utils.data import DataLoader
import m02_initialization as init
import m03_pre_process as preprocess
import m04_model as model
import m05_training as training
import m06_testing as testing
import m07_post_process as postprocess
import time

# Initialize configurations and hyperparameters
cfg = init.Initialize()

# Preprocess data
print('Preprocessing Data...')
print()

a = time.time()

dataset = preprocess.Initialize_Data(cfg)

train_data = preprocess.Load_Data(dataset,cfg,training=True)
vali_data = preprocess.Load_Data(dataset,cfg,validation=True)
test_data = preprocess.Load_Data(dataset,cfg,testing=True)

b = time.time()

train_loader = DataLoader(train_data, batch_size = cfg.batch_size_train, shuffle=False, drop_last=True)
vali_loader = DataLoader(vali_data, batch_size = cfg.batch_size_vali, shuffle=False, drop_last=True)
test_loader = DataLoader(test_data, batch_size = cfg.batch_size_test, shuffle=False, drop_last=True)

print('Preprocessing runtime: %.4f secs' %(b - a))
print()

# Initialize the LSTM model
lstm = model.ANN(cfg)

print(lstm)
print()

# Train the LSTM model

print('Start training...')
print()
trainer = training.Training(cfg, lstm)
trainer.train(train_loader, vali_loader)
print('Training finished...')
print()

# Evaluate (test) the trained model

print('Evaluating model...')
print()
tester = testing.Testing(cfg, trainer)
tester.evaluate(test_loader)

# Postprocess the data and plot figures

print('Postprocessing and plotting...')
print()

pp = postprocess.Post_process(cfg, trainer, tester, dataset, train_data, vali_data, test_data)

print('Finished!')
print()


import numpy as np
import copy
from numpy.core.fromnumeric import size
from Optimization.Optimizers import Sgd

# given the input data size and output data size
class FullyConnected:

    # a Optimizer Object
    _optimizer = False
    _optimizer_w = False
    _optimizer_b = False

    def __init__(self, input_size, output_size):
        # interface of input data
        self.input = None
        # weight and bias are random value matrix; +1 means bias vector
        self.weight_shape = (input_size, output_size)
        self.bias_shape = (output_size, )
        self.weights = np.random.uniform(0, 1, size=self.weight_shape)
        self.bias = np.random.uniform(0, 1, size=self.bias_shape)
        # transmit difference
        self.gradient_weights = None
        self.gradient_bias = None

    def initialize(self, weight_initializer, bias_initializer):

        fan_in = self.weight_shape[0]
        fan_out = self.weight_shape[1]

        self.weights = weight_initializer.initialize(self.weight_shape, fan_in, fan_out)

        self.bias = bias_initializer.initialize(self.bias_shape, fan_in, fan_out)

    """
    optimizer for weights and bias will be separate
    """
    @property
    def optimizer(self):
        return self._optimizer
    @optimizer.setter
    def optimizer(self, Obj):
        self._optimizer = Obj
        self._optimizer_b = copy.deepcopy(self._optimizer)
        self._optimizer_w = copy.deepcopy(self._optimizer)

    # Input matrix is (N,x+1); Weights matrix is (x+1,m); Output matrix is (N,m);
    def forward(self, input_tensor):
        # bias input is a unit col vector,shape(N,1)
        self.input = input_tensor
        bias_input = np.ones(input_tensor.shape[0])
        self.input_plus = np.c_[input_tensor, bias_input]

        # combine weights and bias together
        weight_bias = np.vstack((self.weights, self.bias))
        # print("weight = ", self.weights.shape, "bias = ", self.bias.shape)
        output = np.dot(self.input_plus, weight_bias)
        return output

    # backword with gradient; error_tensor is (N, m);
    def backward(self, error_tensor):
        # partial difference of input, drop last col of matrix self.weights; (N,x) = (N,m) * (m,x)
        gradient_input = np.dot(error_tensor, self.weights.T)
        # partial difference of weight, (x,m) = (x,N) * (N,m)
        self.gradient_weights = np.dot(self.input.T, error_tensor)
        # gradient (1, m)
        self.gradient_bias = np.sum(error_tensor, axis=0).reshape(1, error_tensor.shape[1])

        # cal weights update
        if self._optimizer_w:
            self.weights = self._optimizer_w.calculate_update(self.weights, self.gradient_weights)
        if self._optimizer_b:
            self.bias = self._optimizer_b.calculate_update(self.bias, self.gradient_bias)

        return gradient_input


from lex import *
from emit import *
import parse
import parser_java
import parser_cpp
import parser_py
import sys

def main():
    # print("V3 Compiler")

    # if len(sys.argv) != 2:
    #     sys.exit("Error: Compiler needs source file as argument.")
    with open("hello.tiny", 'r', encoding='utf-8') as inputFile:
        it = inputFile.read()

    lexer = Lexer(it)
    lang = sys.argv[1]
    # print(lang)

    if lang == 'C':
        emitter = Emitter("out.c")
        parser = parse.Parser(lexer, emitter)
        parser.program() # Start the parser.
        emitter.writeFile() # Write the output to file.

    elif lang == 'C++':
        emitter = Emitter("out.cpp")
        parser = parser_cpp.Parser(lexer, emitter)
        parser.program() # Start the parser.
        emitter.writeFile() # Write the output to file.

    elif lang == 'Java':
        emitter = Emitter("out.java")
        parser = parser_java.Parser(lexer, emitter)
        parser.program() # Start the parser.
        emitter.writeFile() # Write the output to file.

    elif lang == 'Python':
        emitter = Emitter("out.py")
        parser = parser_py.Parser(lexer, emitter)
        parser.program() # Start the parser.
        emitter.writeFile() # Write the output to file.

    print("Result: Compiling Completed")

main()


import pygame
from buttons.button import Button

class ImageButton(Button):

    def __init__(self, screen, x, y, image_path, scale):
        image = pygame.image.load(image_path).convert_alpha()

        width = image.get_width()
        height = image.get_height()
        super().__init__(screen, x, y, width, height)

        self.image = pygame.transform.scale(image, (int(width * scale), int(height * scale)))

        self.rect = self.image.get_rect()
        self.rect.topleft = (x, y)

    def draw(self):
        self.screen.blit(self.image, (self.rect.x, self.rect.y))


##############################################################################
#
# Copyright (c) 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Stateful content workflow manager.

$Id$
"""
import unittest

from zope.interface import Interface, implements
from zope.interface.verify import verifyClass
from zope.annotation.interfaces import IAttributeAnnotatable
from zope.annotation.interfaces import IAnnotatable, IAttributeAnnotatable
from zope.lifecycleevent import ObjectCreatedEvent
from zope.lifecycleevent.interfaces import IObjectCreatedEvent
from zope.traversing.api import traverse

from zope.app.container.contained import Contained

from zope.app.workflow.interfaces import IProcessDefinition
from zope.app.workflow.interfaces import IProcessInstanceContainerAdaptable
from zope.app.workflow.interfaces import IProcessInstanceContainer
from zope.app.workflow.stateful.interfaces import IContentWorkflowsManager
from zope.app.workflow.instance import ProcessInstanceContainerAdapter
from zope.app.workflow.stateful.contentworkflow import ContentWorkflowsManager
from zope.app.workflow.stateful.contentworkflow \
     import NewObjectProcessInstanceCreator
from zope.app.workflow.tests.workflowsetup import WorkflowSetup

from zope.app.testing import ztapi, setup

# define and create dummy ProcessDefinition (PD) for tests
class DummyProcessDefinition(Contained):
    implements(IProcessDefinition, IAttributeAnnotatable)

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

    def __str__(self):
        return'PD #%d' % self.n

    def createProcessInstance(self, definition_name):
        return 'PI #%d' % self.n

    # Implements (incompletely) IRegistered to satisfy the promise that
    # it is IRegisterable.
    # Only the method addUsage is implemented.
    def addUsage(self, location):
        pass

class IFace1(Interface):
    pass

class IFace2(Interface):
    pass

class IFace3(Interface):
    pass

class TestObject1(object):
    implements(IFace1, IProcessInstanceContainerAdaptable,
               IAttributeAnnotatable)

class TestObject2(object):
    implements(IFace2, IProcessInstanceContainerAdaptable,
               IAttributeAnnotatable)

class TestObject3(object):
    implements(IFace3, IProcessInstanceContainerAdaptable,
               IAttributeAnnotatable)

class ContentWorkflowsManagerTest(WorkflowSetup, unittest.TestCase):

    def setUp(self):
        WorkflowSetup.setUp(self)
        ztapi.provideAdapter(IAnnotatable, IProcessInstanceContainer,
                             ProcessInstanceContainerAdapter)

    def testInterface(self):
        verifyClass(IContentWorkflowsManager, ContentWorkflowsManager)

    def getManager(self):
        manager = ContentWorkflowsManager()
        manager._registry = {IFace1: ('default',), IFace2: ('default',)}
        self.default['manager'] = manager
        return traverse(self.default, 'manager')

    def test_getProcessDefinitionNamesForObject(self):
        manager = self.getManager()
        self.assertEqual(
            manager.getProcessDefinitionNamesForObject(TestObject1()),
            ('default',))
        self.assertEqual(
            manager.getProcessDefinitionNamesForObject(TestObject2()),
            ('default',))
        self.assertEqual(
            manager.getProcessDefinitionNamesForObject(TestObject3()),
            ())

    def test_register(self):
        manager = self.getManager()
        manager._registry = {}
        manager.register(IFace1, 'default')
        self.assertEqual(manager._registry, {IFace1: ('default',)})

    def test_unregister(self):
        manager = self.getManager()
        manager.unregister(IFace1, 'default')
        self.assertEqual(manager._registry, {IFace2: ('default',)})

    def test_getProcessNamesForInterface(self):
        manager = self.getManager()
        self.assertEqual(
            manager.getProcessNamesForInterface(IFace1),
            ('default',))
        self.assertEqual(
            manager.getProcessNamesForInterface(IFace2),
            ('default',))
        self.assertEqual(
            manager.getProcessNamesForInterface(IFace3),
            ())

    def test_getInterfacesForProcessName(self):
        manager = self.getManager()
        ifaces = manager.getInterfacesForProcessName(u'default')
        self.assertEqual(len(ifaces), 2)
        for iface in [IFace1, IFace2]:
            self.failUnless(iface in ifaces)
        self.assertEqual(
            manager.getInterfacesForProcessName(u'foo'), ())

    def test_notify(self):
        # setup ProcessDefinitions

        setup.addUtility(self.sm, 'definition1', IProcessDefinition,
                         DummyProcessDefinition(1))
        setup.addUtility(self.sm, 'definition2', IProcessDefinition,
                         DummyProcessDefinition(2))

        manager = self.getManager()
        manager._registry = {IFace1: ('definition1',),
                             IFace2: ('definition1', 'definition2')}
        setup.addUtility(self.sm, '', IContentWorkflowsManager,
                         manager)

        obj = TestObject2()
        event = ObjectCreatedEvent(obj)
        NewObjectProcessInstanceCreator(obj, event)
        pi = obj.__annotations__['zope.app.worfklow.ProcessInstanceContainer']
        self.assertEqual(pi.keys(), ['definition2', 'definition1'])

def test_suite():
    return unittest.TestSuite((
        unittest.makeSuite(ContentWorkflowsManagerTest),
        ))

if __name__ == '__main__':
    unittest.main()


import json
import os
import socket
import pip
import argparse
from math import ceil

parser = argparse.ArgumentParser(prog='startbackend.sh')
parser.add_argument("-l", "--local", help="Run from localhost", dest="local",
	action="store_const",const=True,default=False)
parser.add_argument("-p", "--port", help="Port to host from", dest="port",
	default=80, type=int)
parser.add_argument("-n", "--regen-host", help="Regenerate host in config", dest="host",
	action="store_const",const=True,default=False)
parser.add_argument("-b", "--queue-backup", help="Backup queue and load from backup on start", dest="backup",
	action="store_const",const=True,default=False)
parser.add_argument("-r", "--regen-config", help="Regenerate config.json", dest="regen",
	action="store_const",const=True,default=False)
parser.add_argument("-s", "--skip-install", help="Skip package installation", dest="skip",
	action="store_const",const=True,default=False)
parser.add_argument("--install-all", help="Don't ask for confirmation on install", dest="all",
	action="store_const",const=True,default=False)
args = parser.parse_args()

def qsort(l):
		if l == []:
				return []
		else:
				pivot = l[0]
				lesser = qsort([x for x in l[1:] if x < pivot])
				greater = qsort([x for x in l[1:] if x >= pivot])
				return lesser + [pivot] + greater

def copyconf():
	data = json.load(open(os.path.join("..", "www", "defaultconf.json")))
	data["host"] = getIps()[0]
	json.dump(data, open(os.path.join("..", "www", "config.json"), "w"), indent=2)

PACKAGES_UX = [
	"websockets",
	"netifaces"
]
PACKAGES_WIN = [
	"websockets",
	"netifaces",
	"pyserial",
	"pyautoit"
]
def getpacks():
	if args.skip: return
	pl = [str(i).split(" ")[0] for i in pip.get_installed_distributions()]
	packages = (PACKAGES_WIN if os.name == "nt" else PACKAGES_UX)
	installed = False
	for pack in packages:
		if pack in pl:
			continue
		installed = True
		confirm = ("y" if args.all else "")
		while confirm not in ["y", "n"]:
			confirm = input("Install dependency "+pack+"? (y/n) ").lower().strip().rstrip()
		if confirm == "n":
			print("WARNING: Program may not run without this library.")
			continue
		if pip.main(["install", pack]) and os.name != "nt":
			confirm = ("y" if args.all else "")
			while confirm not in ["y", "n"]:
				confirm = input("Install failed, try again with elevated permissions? (y/n) ").lower().strip().rstrip()
			if confirm == "n":
				print("WARNING: Program may not run without this library.")
				continue
			os.system("sudo pip3 install "+pack)
	if installed:
		for pack in packages:
			if pack not in pl:
				print("Failed to install all dependencies.")
	if installed:
		print("Sucessfully installed all dependencies!")

def _comparel(list1, list2):
	list1diff, list2diff = False, False
	for i in list1:
		if i not in list2:
			list1diff = True; break
	for i in list2:
		if i not in list1:
			list2diff = True; break
	if list1diff and list2diff: return "ne"
	elif list1diff:             return "l1"
	elif list2diff:             return "l2"
	else:                       return "eq"

def _prettyl(l, starttext, minlen=0):
	for i in l:
		if len(i)+1 > minlen:
			minlen = len(i)+1

	indent = " "*(len(starttext)+1)
	for i in range(max(1, int(ceil(len(l)/3.0)))):
		if i: print(indent, end="")
		else: print(starttext, end=" ")
		if i == int(ceil(len(l)/3.0))-1:
			printl = [" "*(minlen-len(j))+j for j in l[i*3:]]
			print(",".join(printl))
		else:
			printl = [" "*(minlen-len(j))+j for j in l[i*3:i*3+3]]
			print(",".join(printl), end=",\n")

def _fillblanks(odict, adict):
	keys = list(adict.keys())
	for i in keys:
		if i not in odict:
			odict[i] = adict[i]
	return odict

def main():
	getpacks()
	if args.regen or not os.path.exists(os.path.join("..", "www", "config.json")):
		copyconf()
	if args.host:
		data = json.load(open(os.path.join("..", "www", "config.json")))
		data["host"] = getIps()[0]
		json.dump(data, open(os.path.join("..", "www", "config.json"), "w"), indent=2)
	if args.local:
		data = json.load(open(os.path.join("..", "www", "config.json")))
		data["host"] = "localhost"
		json.dump(data, open(os.path.join("..", "www", "config.json"), "w"), indent=2)
	else:
		data = json.load(open(os.path.join("..", "www", "config.json")))
		if "host" in data and data["host"] == "localhost":
			print("Last time you ran this program, it was in local mode.")
			confirm = ""
			while confirm not in ["y", "n"]:
				confirm = input("Do you want to regenerate the host? (y/n) ").lower().strip().rstrip()
			if confirm == "y":
				data["host"] = getIps()[0]
			json.dump(data, open(os.path.join("..", "www", "config.json"), "w"), indent=2)
	data = json.load(open(os.path.join("..", "www", "config.json")))
	defaultdata = json.load(open(os.path.join("..", "www", "defaultconf.json")))
	if "host" not in data:
		data["host"] = getIps()[0]
	data = _fillblanks(data, defaultdata)
	json.dump(data, open(os.path.join("..", "www", "config.json"), "w"), indent=2)

	print("Initialization complete.")

def getIps():
	from netifaces import interfaces, ifaddresses, AF_INET
	ips = []
	for ifaceName in interfaces():
		addresses = [i['addr'] for i in ifaddresses(ifaceName).get(AF_INET, [{"addr":"not found"}])]
		if "not found" not in addresses and "127.0.0.1" not in addresses:
			ips += addresses
	return ips

if __name__ == "__main__":
	main()


"""
340. Longest Substring with At Most K Distinct Characters

Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct characters.

Example 1:

Input: s = "eceba", k = 2
Output: 3
Explanation: The substring is "ece" with length 3.
Example 2:

Input: s = "aa", k = 1
Output: 2
Explanation: The substring is "aa" with length 2.

Constraints:

1 <= s.length <= 5 * 104
0 <= k <= 50

"""

class LengthOfLongestSubstringKDistinct:

    def doit_slidingwindow(self, s: str, k: int) -> int:

        counter = [0] * 256
        i = numChars = 0
        best = 0

        for j in range(len(s)):

            if counter[ord(s[j])] == 0:
                numChars += 1

            counter[ord(s[j])] += 1

            while i < len(s) and numChars > k:
                counter[ord(s[i])] -= 1
                if counter[ord(s[i])] == 0:
                    numChars -= 1
                i += 1

            best = max(best, j - i + 1)

        return best

    """
            Approach 2: Sliding Window + Ordered Dictionary.
        How to achieve \mathcal{O}(N)O(N) time complexity

        Approach 1 with a standard hashmap couldn't ensure \mathcal{O}(N)O(N) time complexity.

        To have \mathcal{O}(N)O(N) algorithm performance, one would need a structure, which provides four operations in \mathcal{O}(1)O(1) time :

        Insert the key

        Get the key and check if the key exists

        Delete the key

        Return the first or last added key/ value

        The first three operations in \mathcal{O}(1)O(1) time are provided by the standard hashmap, and the forth one - by linked list.

        There is a structure called ordered dictionary, it combines behind both hashmap and linked list. In Python this structure is called OrderedDict and in Java LinkedHashMap.

        Ordered dictionary is quite popular for interviews. for example, check out the Implementing a LRU Cache question by Google.

        Algorithm

        Let's use ordered dictionary instead of standard hashmap to trim the algorithm from approach 1 :

        Return 0 if the string is empty or k is equal to zero.
        Set both pointers to the beginning of the string left = 0 and right = 0 and initialize max substring length max_len = 1.
        While right pointer is less than N:
        If the current character s[right] is already in the ordered dictionary hashmap -- delete it, to ensure that the first key in hashmap is the leftmost character.
        Add the current character s[right] in the ordered dictionary and move right pointer to the right.
        If ordered dictionary hashmap contains k + 1 distinct characters, remove the leftmost one and move the left pointer so that sliding window contains again k distinct characters only.
        Update max_len.
        Implementation

        Complexity Analysis

        Time complexity : O(N) since all operations with ordered dictionary : insert/get/delete/popitem (put/containsKey/remove) are done in a constant time.

        Space complexity : O(k) since additional space is used only for an ordered dictionary with at most k + 1 elements.
    """

    def doit_slidingwindow(self, s: str, k: int) -> int:
        from collections import OrderedDict
        n = len(s)
        if k == 0 or n == 0:
            return 0

        # sliding window left and right pointers
        left, right = 0, 0
        # hashmap character -> its rightmost position
        # in the sliding window
        hashmap = OrderedDict()

        max_len = 1

        while right < n:
            character = s[right]
            # if character is already in the hashmap -
            # delete it, so that after insert it becomes
            # the rightmost element in the hashmap
            if character in hashmap:
                del hashmap[character]
            hashmap[character] = right
            right += 1

            # slidewindow contains k + 1 characters
            if len(hashmap) == k + 1:
                # delete the leftmost character
                _, del_idx = hashmap.popitem(last = False)
                # move left pointer of the slidewindow
                left = del_idx + 1

            max_len = max(max_len, right - left)

        return max_len


import boto3
from botocore.client import ClientError

from moto.s3.responses import DEFAULT_REGION_NAME
import pytest

import sure  # noqa # pylint: disable=unused-import

from moto import mock_s3, mock_kms

@pytest.mark.parametrize(
    "key_name",
    [
        "the-key",
        "the-unicode-💩-key",
        "key-with?question-mark",
        "key-with%2Fembedded%2Furl%2Fencoding",
    ],
)
@mock_s3
def test_copy_key_boto3(key_name):
    s3 = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    s3.create_bucket(Bucket="foobar")

    key = s3.Object("foobar", key_name)
    key.put(Body=b"some value")

    key2 = s3.Object("foobar", "new-key")
    key2.copy_from(CopySource=f"foobar/{key_name}")

    resp = client.get_object(Bucket="foobar", Key=key_name)
    resp["Body"].read().should.equal(b"some value")
    resp = client.get_object(Bucket="foobar", Key="new-key")
    resp["Body"].read().should.equal(b"some value")

@mock_s3
def test_copy_key_boto3_with_sha256_checksum():
    # Setup
    s3 = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    key_name = "key"
    new_key = "new_key"
    bucket = "foobar"
    expected_hash = "YWIzZDA3ZjMxNjljY2JkMGVkNmM0YjQ1ZGUyMTUxOWY5ZjkzOGM3MmQyNDEyNDk5OGFhYjk0OWNlODNiYjUxYg=="

    s3.create_bucket(Bucket=bucket)
    key = s3.Object("foobar", key_name)
    key.put(Body=b"some value")

    # Execute
    key2 = s3.Object(bucket, new_key)
    key2.copy(
        CopySource={"Bucket": bucket, "Key": key_name},
        ExtraArgs={"ChecksumAlgorithm": "SHA256"},
    )

    # Verify
    resp = client.get_object_attributes(
        Bucket=bucket, Key=new_key, ObjectAttributes=["Checksum"]
    )

    assert "Checksum" in resp
    assert "ChecksumSHA256" in resp["Checksum"]
    assert resp["Checksum"]["ChecksumSHA256"] == expected_hash

@mock_s3
def test_copy_key_with_version_boto3():
    s3 = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    s3.create_bucket(Bucket="foobar")
    client.put_bucket_versioning(
        Bucket="foobar", VersioningConfiguration={"Status": "Enabled"}
    )

    key = s3.Object("foobar", "the-key")
    key.put(Body=b"some value")
    key.put(Body=b"another value")

    all_versions = client.list_object_versions(Bucket="foobar", Prefix="the-key")[
        "Versions"
    ]
    old_version = [v for v in all_versions if not v["IsLatest"]][0]

    key2 = s3.Object("foobar", "new-key")
    key2.copy_from(CopySource=f"foobar/the-key?versionId={old_version['VersionId']}")

    resp = client.get_object(Bucket="foobar", Key="the-key")
    resp["Body"].read().should.equal(b"another value")
    resp = client.get_object(Bucket="foobar", Key="new-key")
    resp["Body"].read().should.equal(b"some value")

@mock_s3
def test_copy_object_with_bucketkeyenabled_returns_the_value():
    s3 = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    bucket_name = "test-copy-object-with-bucketkeyenabled"
    s3.create_bucket(Bucket=bucket_name)

    key = s3.Object(bucket_name, "the-key")
    key.put(Body=b"some value")

    key2 = s3.Object(bucket_name, "new-key")
    key2.copy_from(
        CopySource=f"{bucket_name}/the-key",
        BucketKeyEnabled=True,
        ServerSideEncryption="aws:kms",
    )

    resp = client.get_object(Bucket=bucket_name, Key="the-key")
    src_headers = resp["ResponseMetadata"]["HTTPHeaders"]
    src_headers.shouldnt.have.key("x-amz-server-side-encryption")
    src_headers.shouldnt.have.key("x-amz-server-side-encryption-aws-kms-key-id")
    src_headers.shouldnt.have.key("x-amz-server-side-encryption-bucket-key-enabled")

    resp = client.get_object(Bucket=bucket_name, Key="new-key")
    target_headers = resp["ResponseMetadata"]["HTTPHeaders"]
    target_headers.should.have.key("x-amz-server-side-encryption")
    # AWS will also return the KMS default key id - not yet implemented
    # target_headers.should.have.key("x-amz-server-side-encryption-aws-kms-key-id")
    # This field is only returned if encryption is set to 'aws:kms'
    target_headers.should.have.key("x-amz-server-side-encryption-bucket-key-enabled")
    str(
        target_headers["x-amz-server-side-encryption-bucket-key-enabled"]
    ).lower().should.equal("true")

@mock_s3
def test_copy_key_with_metadata():
    s3 = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    s3.create_bucket(Bucket="foobar")

    key = s3.Object("foobar", "the-key")
    metadata = {"md": "Metadatastring"}
    content_type = "application/json"
    initial = key.put(Body=b"{}", Metadata=metadata, ContentType=content_type)

    client.copy_object(Bucket="foobar", CopySource="foobar/the-key", Key="new-key")

    resp = client.get_object(Bucket="foobar", Key="new-key")
    resp["Metadata"].should.equal(metadata)
    resp["ContentType"].should.equal(content_type)
    resp["ETag"].should.equal(initial["ETag"])

@mock_s3
def test_copy_key_replace_metadata():
    s3 = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    s3.create_bucket(Bucket="foobar")

    key = s3.Object("foobar", "the-key")
    initial = key.put(Body=b"some value", Metadata={"md": "Metadatastring"})

    client.copy_object(
        Bucket="foobar",
        CopySource="foobar/the-key",
        Key="new-key",
        Metadata={"momd": "Mometadatastring"},
        MetadataDirective="REPLACE",
    )

    resp = client.get_object(Bucket="foobar", Key="new-key")
    resp["Metadata"].should.equal({"momd": "Mometadatastring"})
    resp["ETag"].should.equal(initial["ETag"])

@mock_s3
def test_copy_key_without_changes_should_error():
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    bucket_name = "my_bucket"
    s3 = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    key_name = "my_key"
    key = s3.Object(bucket_name, key_name)

    s3.create_bucket(Bucket=bucket_name)
    key.put(Body=b"some value")

    with pytest.raises(ClientError) as e:
        client.copy_object(
            Bucket=bucket_name,
            CopySource=f"{bucket_name}/{key_name}",
            Key=key_name,
        )
        e.value.response["Error"]["Message"].should.equal(
            "This copy request is illegal because it is trying to copy an object to itself without changing the object's metadata, storage class, website redirect location or encryption attributes."
        )

@mock_s3
def test_copy_key_without_changes_should_not_error():
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    bucket_name = "my_bucket"
    s3 = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    key_name = "my_key"
    key = s3.Object(bucket_name, key_name)

    s3.create_bucket(Bucket=bucket_name)
    key.put(Body=b"some value")

    client.copy_object(
        Bucket=bucket_name,
        CopySource=f"{bucket_name}/{key_name}",
        Key=key_name,
        Metadata={"some-key": "some-value"},
        MetadataDirective="REPLACE",
    )

    new_object = client.get_object(Bucket=bucket_name, Key=key_name)

    assert new_object["Metadata"] == {"some-key": "some-value"}

@mock_s3
def test_copy_key_reduced_redundancy():
    s3 = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    bucket = s3.Bucket("test_bucket")
    bucket.create()

    bucket.put_object(Key="the-key", Body=b"somedata")

    client.copy_object(
        Bucket="test_bucket",
        CopySource="test_bucket/the-key",
        Key="new-key",
        StorageClass="REDUCED_REDUNDANCY",
    )

    keys = dict([(k.key, k) for k in bucket.objects.all()])
    keys["new-key"].storage_class.should.equal("REDUCED_REDUNDANCY")
    keys["the-key"].storage_class.should.equal("STANDARD")

@mock_s3
def test_copy_non_existing_file():
    s3 = boto3.resource("s3", region_name=DEFAULT_REGION_NAME)
    src = "srcbucket"
    target = "target"
    s3.create_bucket(Bucket=src)
    s3.create_bucket(Bucket=target)

    s3_client = boto3.client("s3")
    with pytest.raises(ClientError) as exc:
        s3_client.copy_object(
            Bucket=target, CopySource={"Bucket": src, "Key": "foofoofoo"}, Key="newkey"
        )
    err = exc.value.response["Error"]
    err["Code"].should.equal("NoSuchKey")
    err["Message"].should.equal("The specified key does not exist.")
    err["Key"].should.equal("foofoofoo")

@mock_s3
def test_copy_object_with_versioning():
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)

    client.create_bucket(
        Bucket="blah", CreateBucketConfiguration={"LocationConstraint": "eu-west-1"}
    )
    client.put_bucket_versioning(
        Bucket="blah", VersioningConfiguration={"Status": "Enabled"}
    )

    client.put_object(Bucket="blah", Key="test1", Body=b"test1")
    client.put_object(Bucket="blah", Key="test2", Body=b"test2")

    client.get_object(Bucket="blah", Key="test1")["VersionId"]
    obj2_version = client.get_object(Bucket="blah", Key="test2")["VersionId"]

    client.copy_object(
        CopySource={"Bucket": "blah", "Key": "test1"}, Bucket="blah", Key="test2"
    )
    obj2_version_new = client.get_object(Bucket="blah", Key="test2")["VersionId"]

    # Version should be different to previous version
    obj2_version_new.should_not.equal(obj2_version)

    client.copy_object(
        CopySource={"Bucket": "blah", "Key": "test2", "VersionId": obj2_version},
        Bucket="blah",
        Key="test3",
    )
    obj3_version_new = client.get_object(Bucket="blah", Key="test3")["VersionId"]
    obj3_version_new.should_not.equal(obj2_version_new)

    # Copy file that doesn't exist
    with pytest.raises(ClientError) as e:
        client.copy_object(
            CopySource={"Bucket": "blah", "Key": "test4", "VersionId": obj2_version},
            Bucket="blah",
            Key="test5",
        )
    e.value.response["Error"]["Code"].should.equal("NoSuchKey")

    response = client.create_multipart_upload(Bucket="blah", Key="test4")
    upload_id = response["UploadId"]
    response = client.upload_part_copy(
        Bucket="blah",
        Key="test4",
        CopySource={"Bucket": "blah", "Key": "test3", "VersionId": obj3_version_new},
        UploadId=upload_id,
        PartNumber=1,
    )
    etag = response["CopyPartResult"]["ETag"]
    client.complete_multipart_upload(
        Bucket="blah",
        Key="test4",
        UploadId=upload_id,
        MultipartUpload={"Parts": [{"ETag": etag, "PartNumber": 1}]},
    )

    response = client.get_object(Bucket="blah", Key="test4")
    data = response["Body"].read()
    data.should.equal(b"test2")

@mock_s3
def test_copy_object_from_unversioned_to_versioned_bucket():
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)

    client.create_bucket(
        Bucket="src", CreateBucketConfiguration={"LocationConstraint": "eu-west-1"}
    )
    client.create_bucket(
        Bucket="dest", CreateBucketConfiguration={"LocationConstraint": "eu-west-1"}
    )
    client.put_bucket_versioning(
        Bucket="dest", VersioningConfiguration={"Status": "Enabled"}
    )

    client.put_object(Bucket="src", Key="test", Body=b"content")

    obj2_version_new = client.copy_object(
        CopySource={"Bucket": "src", "Key": "test"}, Bucket="dest", Key="test"
    ).get("VersionId")

    # VersionId should be present in the response
    obj2_version_new.should_not.equal(None)

@mock_s3
def test_copy_object_with_replacement_tagging():
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    client.create_bucket(Bucket="mybucket")
    client.put_object(
        Bucket="mybucket", Key="original", Body=b"test", Tagging="tag=old"
    )

    # using system tags will fail
    with pytest.raises(ClientError) as err:
        client.copy_object(
            CopySource={"Bucket": "mybucket", "Key": "original"},
            Bucket="mybucket",
            Key="copy1",
            TaggingDirective="REPLACE",
            Tagging="aws:tag=invalid_key",
        )

    e = err.value
    e.response["Error"]["Code"].should.equal("InvalidTag")

    client.copy_object(
        CopySource={"Bucket": "mybucket", "Key": "original"},
        Bucket="mybucket",
        Key="copy1",
        TaggingDirective="REPLACE",
        Tagging="tag=new",
    )
    client.copy_object(
        CopySource={"Bucket": "mybucket", "Key": "original"},
        Bucket="mybucket",
        Key="copy2",
        TaggingDirective="COPY",
    )

    tags1 = client.get_object_tagging(Bucket="mybucket", Key="copy1")["TagSet"]
    tags1.should.equal([{"Key": "tag", "Value": "new"}])
    tags2 = client.get_object_tagging(Bucket="mybucket", Key="copy2")["TagSet"]
    tags2.should.equal([{"Key": "tag", "Value": "old"}])

@mock_s3
@mock_kms
def test_copy_object_with_kms_encryption():
    client = boto3.client("s3", region_name=DEFAULT_REGION_NAME)
    kms_client = boto3.client("kms", region_name=DEFAULT_REGION_NAME)
    kms_key = kms_client.create_key()["KeyMetadata"]["KeyId"]

    client.create_bucket(
        Bucket="blah", CreateBucketConfiguration={"LocationConstraint": "eu-west-1"}
    )

    client.put_object(Bucket="blah", Key="test1", Body=b"test1")

    client.copy_object(
        CopySource={"Bucket": "blah", "Key": "test1"},
        Bucket="blah",
        Key="test2",
        SSEKMSKeyId=kms_key,
        ServerSideEncryption="aws:kms",
    )
    result = client.head_object(Bucket="blah", Key="test2")
    assert result["SSEKMSKeyId"] == kms_key
    assert result["ServerSideEncryption"] == "aws:kms"