import pyautogui
import webbrowser
import time, sys, random

def initializePyAutoGUI():
    # Initialized PyAutoGUI
    # https://pyautogui.readthedocs.io/en/latest/introduction.html
    # When fail-safe mode is True, moving the mouse to the upper-left corner will abort your program.
    pyautogui.FAILSAFE = True

for i in range(0,10000):
    time.sleep(2)

    #pyautogui.size()
    #FULL SCREEN

    #exit undock from space station
    Undock_from_station = [1030,172]
    pyautogui.moveTo(Undock_from_station[0],Undock_from_station[1],1)
    pyautogui.click()
    time.sleep(random.randint(15,20))
    #select mining TAB
    select_mining_tab = [937,162]
    pyautogui.moveTo(select_mining_tab[0],select_mining_tab[1],1)
    pyautogui.click()
    time.sleep(0.5)
    #go to mining  post
    select_mining_belt = [941,243]
    select_minigbelt_worpto0 = [964,230]
    pyautogui.doubleClick(select_mining_belt[0],select_mining_belt[1],1)
    pyautogui.keyDown('s')
    time.sleep(0.25)
    pyautogui.keyUp('s')
    time.sleep(35)
    # pyautogui.rightClick(select_mining_belt[0],select_mining_belt[1],1)
    # pyautogui.moveTo(select_minigbelt_worpto0[0],select_minigbelt_worpto0[1],1)
    # pyautogui.click()q
    select_mining_tab = [1068,162]
    pyautogui.moveTo(select_mining_tab[0],select_mining_tab[1],1)
    pyautogui.click()
    time.sleep(0.5)
    #mining asteroid belt
    minig_asteroid1 = [931,204]
    minig_asteroid2 = [931,224]
    minig_asteroid3 = [931,244]
    #start_shield_hardener = [772,766]
    #start_afterburner = [824,763]
    lock_target = [1023,83]

    #get drones out
    pyautogui.keyDown('altleft')
    pyautogui.press('F2')
    pyautogui.keyUp('altleft')
    time.sleep(0.5)
    pyautogui.keyDown('altleft')
    pyautogui.press('F3')
    pyautogui.keyUp('altleft')
    time.sleep(0.5)
    #MINING FIRST ASTEROID
    pyautogui.moveTo(minig_asteroid1[0],minig_asteroid1[1],2)
    pyautogui.doubleClick()
    time.sleep(0.5)
    pyautogui.keyDown('w')
    time.sleep(0.2)
    pyautogui.keyUp('w')
    time.sleep(random.randint(20,25))
    pyautogui.moveTo(lock_target[0],lock_target[1],2)
    pyautogui.click()
    time.sleep(1)
    pyautogui.keyDown('F1')
    time.sleep(0.2)
    pyautogui.keyUp('F1')
    time.sleep(1)
    #MINING SECOUND ASTEROID
    pyautogui.moveTo(minig_asteroid2[0],minig_asteroid2[1],2)
    pyautogui.click()
    time.sleep(1)
    pyautogui.moveTo(lock_target[0],lock_target[1],2)
    pyautogui.click()
    time.sleep(2)
    pyautogui.moveTo(692,54,2)
    pyautogui.click()
    pyautogui.keyDown('F2')
    time.sleep(0.2)
    pyautogui.keyUp('F2')

    #deploy droness
    time.sleep(60)
    pyautogui.keyDown('shiftleft')
    pyautogui.press('f')
    pyautogui.keyUp('shiftleft')

    #time to wait to full fill cargos
    time.sleep(130)
    #GO HOME
        #drow back your drones
    pyautogui.keyDown('shiftleft')
    pyautogui.press('r')
    pyautogui.keyUp('shiftleft')
    time.sleep(3)
    pyautogui.keyDown('shiftleft')
    pyautogui.press('r')
    pyautogui.keyUp('shiftleft')
    time.sleep(5)

        #Dock to station
    pyautogui.moveTo(211,363,1)
    pyautogui.rightClick()
    pyautogui.moveTo(240,373,1)
    pyautogui.click()
    pyautogui.keyDown('F1')
    time.sleep(0.2)
    pyautogui.keyUp('F1')
    time.sleep(0.5)
    pyautogui.keyDown('F2')
    time.sleep(0.2)
    pyautogui.keyUp('F2')
    time.sleep(random.randint(45,60))

        #Moving ORE TO HANGAR
    pyautogui.moveTo(108,604,1) #select ship ore hangar
    pyautogui.click()
    pyautogui.moveTo(377,579,1) #rightclick in ore ship hangar
    pyautogui.rightClick()
    pyautogui.moveTo(406,588,1) #sellect all
    pyautogui.click()
    pyautogui.moveTo(264,597,1)
    pyautogui.dragTo(100,702,1,button='left')


import numpy as np

class Perceptron():

    def __init__(self,X, y, threshold = 0.5, learning_rate = 0.1, max_epoch = 10):
        self.threshold = threshold
        self.learning_rate = learning_rate
        self.y = y
        self.X = X
        self.max_epoch = max_epoch

    def initialize(self, init_type = 'zeros'):
        if init_type == 'random':
            self.weights = np.random.rand(len(self.X[0]))*0.5
        if init_type == 'zeros':
            self.weights = np.zeros(len(self.X[0]))

    def train(self):
        epoch = 0
        while True:
            error_count = 0
            epoch +=1
            for (X,y) in zip(self.X, self.y):
                error_count +=self.train_observation(X, y, error_count)
            if error_count ==0:
                print('training successfull')
                break
            if epoch >= self.max_epoch:
                print('reached maximum epoch')
                break

    def train_observation(self, X, y, error_count):
        result = np.dot(X, self.weights) > self.threshold
        error = y - result
        if error !=0:
            error_count +=1
            for index, value in enumerate(X):
                self.weights[index] += self.learning_rate * error * value
        return error_count

    def predict(self, X):
        return int(np.dot(X, self.weights) > self.threshold)

X = [(1,0,0),(1,1,0),(1,1,1),(1,1,1),(1,0,1),(1,0,1)]
y = [1,1,0,0,1,1]

p=Perceptron(X,y)
p.initialize()
p.train()
print(p.predict((0,1,0)))
print(p.predict((0,0,0)))


# from pudb import set_trace; set_trace()
from typing import List

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        """We create a gap of n steps between a left pointer and right pointer.
        When the right pointer reaches the end, the left pointer will point at
        the node right before the target deletion. Then we can easily remove the
        target. Use a dummy node at the very beginning to simplify syntax.

        O(N), 36 ms, 43% ranking.
        """
        dummy = ListNode(next=head)
        left, right = dummy, dummy
        for _ in range(n):
            right = right.next
        while right.next:  # find the node before the one to be removed
            left, right = left.next, right.next
        left.next = left.next.next  # remove the target node
        return dummy.next

# sol = Solution3()
# tests = [
#     ('abab', True),
#     ('aba', False),
#     ('abcabcabcabc', True),
#     ('abcabcababcabcab', True),
#     ('abcbac', False),
#     ('aabaabaab', True),
#     ('a', False),
#     ('aaaaaaa', True),
#     ('aaaaab', False),
# ]

# for i, (s, ans) in enumerate(tests):
#     res = sol.repeatedSubstringPattern(s)
#     if res == ans:
#         print(f'Test {i}: PASS')
#     else:
#         print(f'Test {i}; Fail. Ans: {ans}, Res: {res}')


from twilio.rest import Client
import os
import time
import schedule

def send_msg():
    account_sid = os.environ.get("ACCOUNT_SID")
    auth_token = os.environ.get("AUTH_TOKEN")
    client = Client(account_sid, auth_token)

    client.messages.create(
        from_='whatsapp:+14155238886',
        body='Good Morning Tushar',
        to='whatsapp:+919959686272'
    )
schedule.every().day.at("07:30").do(send_msg)
while True:
    schedule.run_pending()
    print("sent!")


from urllib.request import Request, urlopen, ssl, socket
from urllib.error import URLError, HTTPError
import json
from datetime import datetime

def getexpirydate(base_url,port):
    out=[]
    hostname = base_url
    context = ssl.create_default_context()
    data ={}
    with socket.create_connection((hostname, port)) as sock:
        with context.wrap_socket(sock, server_hostname=hostname) as ssock:
            data = json.dumps(ssock.getpeercert())
            # print(ssock.getpeercert())
    for i in data.split(","):
        if(("notBefore" in i) or ("notAfter" in i)):
            out.append(i.split('"')[3])

    return(out)
base_urls =['stackoverflow.com','geeksforgeeks.org','leetcode.com']
port = '443'
output={}
for base_url in base_urls:
    x=[]
    for i in getexpirydate(base_url,port):
        datetime_object=datetime.strptime(i,'%b %d %H:%M:%S %Y %Z')
        print(datetime_object)
        x.append(datetime_object)
    output[base_url]=x
print(output)


import tensorflow as tf
import pandas as pd
from IPython import clear_output
from helper import make_input_fn, convert_to_training_data

clear_output()
r_train = convert_to_training_data('test-img.jpg')['R']
df_train = convert_to_training_data('download.jfif')

# extracting the last 10% of sample data to be used as evaluation set
num_of_eval_samples = int(0.1 * r_train.size)
r_eval = r_train[-num_of_eval_samples:]
r_train = r_train.iloc[:-num_of_eval_samples]
df_eval = df_train[-num_of_eval_samples:]
df_train = df_train[:-num_of_eval_samples]

# populating the feature_columns
feature_columns = []
for feature_name in df_train.columns:
    feature_columns.append(tf.feature_column.numeric_column(
        feature_name, dtype=tf.float64))

# here we will call the input_function that was returned to us to get a dataset object we can feed to the model
train_input_fn = make_input_fn(df_train, r_train)
eval_input_fn = make_input_fn(df_eval, r_eval, num_epochs=1, shuffle=False)

linear_est = tf.estimator.LinearRegressor(feature_columns=feature_columns)
# We create a linear estimtor by passing the feature columns we created earlier

linear_est.train(train_input_fn)  # train
# get model metrics/stats by testing on tetsing data

pred_dicts = list(linear_est.predict(eval_input_fn))
predicted_output = pd.Series([pred['predictions'][0] for pred in pred_dicts])

# the result variable is simply a dict of stats about our model
print('Predicted output:')
print(predicted_output.head())
tf.saved_model.save(linear_est, '/')


from exceptions import OGCException, ServerConfigurationError
from mapnik import Map, Color, Envelope, render, Image, Layer, Style, Projection as MapnikProjection, Coord
from PIL.Image import new
from PIL.ImageDraw import Draw
from StringIO import StringIO
from copy import deepcopy
from traceback import format_exception, format_exception_only
from sys import exc_info
import re
import sys

try:
    from lxml import etree as ElementTree
except ImportError:
    import xml.etree.ElementTree as ElementTree
except ImportError:
    import elementtree.ElementTree as ElementTree

# from elementtree import ElementTree
# ElementTree._namespace_map.update({'http://www.opengis.net/wms': 'wms',
#                                    'http://www.opengis.net/ogc': 'ogc',
#                                    'http://www.w3.org/1999/xlink': 'xlink',
#                                    'http://www.w3.org/2001/XMLSchema-instance': 'xsi'
#                                    })

PIL_TYPE_MAPPING = {'image/jpeg': 'jpeg', 'image/png': 'png'}

class ParameterDefinition:

    def __init__(self, mandatory, cast, default=None, allowedvalues=None, fallback=False):
        """ An OGC request parameter definition.  Used to describe a
            parameter's characteristics.

            @param mandatory: Is this parameter required by the request?
            @type mandatory: Boolean.

            @param default: Default value to use if one is not provided
                            and the parameter is optional.
            @type default: None or any valid value.

            @param allowedvalues: A list of allowed values for the parameter.
                                  If a value is provided that is not in this
                                  list, an error is raised.
            @type allowedvalues: A python tuple of values.

            @param fallback: Whether the value of the parameter should fall
                             back to the default should an illegal value be
                             provided.
            @type fallback: Boolean.

            @return: A L{ParameterDefinition} instance.
        """
        if mandatory not in [True, False]:
            raise ServerConfigurationError("Bad value for 'mandatory' parameter, must be True or False.")
        self.mandatory = mandatory
        if not callable(cast):
            raise ServerConfigurationError('Cast parameter definition must be callable.')
        self.cast = cast
        self.default = default
        if allowedvalues and type(allowedvalues) != type(()):
            raise ServerConfigurationError("Bad value for 'allowedvalues' parameter, must be a tuple.")
        self.allowedvalues = allowedvalues
        if fallback not in [True, False]:
            raise ServerConfigurationError("Bad value for 'fallback' parameter, must be True or False.")
        self.fallback = fallback

class BaseServiceHandler:

    CONF_CONTACT_PERSON_PRIMARY = [
        ['contactperson', 'ContactPerson', str],
        ['contactorganization', 'ContactOrganization', str]
    ]

    CONF_CONTACT_ADDRESS = [
        ['addresstype', 'AddressType', str],
        ['address', 'Address', str],
        ['city', 'City', str],
        ['stateorprovince', 'StateOrProvince', str],
        ['postcode', 'PostCode', str],
        ['country', 'Country', str]
    ]

    CONF_CONTACT = [
        ['contactposition', 'ContactPosition', str],
        ['contactvoicetelephone', 'ContactVoiceTelephone', str],
        ['contactelectronicmailaddress', 'ContactElectronicMailAddress', str]
    ]

    def processParameters(self, requestname, params):
        finalparams = {}
        for paramname, paramdef in self.SERVICE_PARAMS[requestname].items():
            if paramname not in params.keys() and paramdef.mandatory:
                raise OGCException('Mandatory parameter "%s" missing from request.' % paramname)
            elif paramname in params.keys():
                try:
                    params[paramname] = paramdef.cast(params[paramname])
                except OGCException:
                    raise
                except:
                    raise OGCException('Invalid value "%s" for parameter "%s".' % (params[paramname], paramname))
                if paramdef.allowedvalues and params[paramname] not in paramdef.allowedvalues:
                    if not paramdef.fallback:
                        raise OGCException('Parameter "%s" has an illegal value.' % paramname)
                    else:
                        finalparams[paramname] = paramdef.default
                else:
                    finalparams[paramname] = params[paramname]
            elif not paramdef.mandatory and paramdef.default:
                finalparams[paramname] = paramdef.default
        return finalparams

    def processServiceCapabilities(self, capetree):
        if len(self.conf.items('service')) > 0:
            servicee = capetree.find('{http://www.opengis.net/wms}Service')
            for item in self.CONF_SERVICE:
                if self.conf.has_option_with_value('service', item[0]):
                    value = self.conf.get('service', item[0]).strip()
                    try:
                        item[2](value)
                    except:
                        raise ServerConfigurationError('Configuration parameter [%s]->%s has an invalid value: %s.' % ('service', item[0], value))
                    if item[0] == 'onlineresource':
                        element = ElementTree.Element('%s' % item[1])
                        servicee.append(element)
                        element.set('{http://www.w3.org/1999/xlink}href', value)
                        element.set('{http://www.w3.org/1999/xlink}type', 'simple')
                    elif item[0] == 'keywordlist':
                        element = ElementTree.Element('%s' % item[1])
                        servicee.append(element)
                        keywords = value.split(',')
                        keywords = map(str.strip, keywords)
                        for keyword in keywords:
                            kelement = ElementTree.Element('Keyword')
                            kelement.text = keyword
                            element.append(kelement)
                    else:
                        element = ElementTree.Element('%s' % item[1])
                        element.text = value
                        servicee.append(element)
            if len(self.conf.items_with_value('contact')) > 0:
                element = ElementTree.Element('ContactInformation')
                servicee.append(element)
                for item in self.CONF_CONTACT:
                    if self.conf.has_option_with_value('contact', item[0]):
                        value = self.conf.get('contact', item[0]).strip()
                        try:
                            item[2](value)
                        except:
                            raise ServerConfigurationError('Configuration parameter [%s]->%s has an invalid value: %s.' % ('service', item[0], value))
                        celement = ElementTree.Element('%s' % item[1])
                        celement.text = value
                        element.append(celement)
                for item in self.CONF_CONTACT_PERSON_PRIMARY + self.CONF_CONTACT_ADDRESS:
                    if item in self.CONF_CONTACT_PERSON_PRIMARY:
                        tagname = 'ContactPersonPrimary'
                    else:
                        tagname = 'ContactAddress'
                    if self.conf.has_option_with_value('contact', item[0]):
                        if element.find(tagname) == None:
                            subelement = ElementTree.Element(tagname)
                            element.append(subelement)
                        value = self.conf.get('contact', item[0]).strip()
                        try:
                            item[2](value)
                        except:
                            raise ServerConfigurationError('Configuration parameter [%s]->%s has an invalid value: %s.' % ('service', item[0], value))
                        celement = ElementTree.Element('%s' % item[1])
                        celement.text = value
                        subelement.append(celement)

class Response:

    def __init__(self, content_type, content):
        self.content_type = content_type
        self.content = content

class Version:

    def __init__(self, version):
        version = version.split('.')
        if len(version) != 3:
            raise OGCException('Badly formatted version number.')
        try:
            version = map(int, version)
        except:
            raise OGCException('Badly formatted version number.')
        self.version = version

    def __repr__(self):
        return '%s.%s.%s' % (self.version[0], self.version[1], self.version[2])

    def __cmp__(self, other):
        if isinstance(other, str):
            other = Version(other)
        if self.version[0] < other.version[0]:
            return -1
        elif self.version[0] > other.version[0]:
            return 1
        else:
            if self.version[1] < other.version[1]:
                return -1
            elif self.version[1] > other.version[1]:
                return 1
            else:
                if self.version[2] < other.version[2]:
                    return -1
                elif self.version[2] > other.version[2]:
                    return 1
                else:
                    return 0

class ListFactory:

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

    def __call__(self, string):
        seq = string.split(',')
        return map(self.cast, seq)

def ColorFactory(colorstring):
    if re.match('^0x[a-fA-F0-9]{6}$', colorstring):
        return Color(eval('0x' + colorstring[2:4]), eval('0x' + colorstring[4:6]), eval('0x' + colorstring[6:8]))
    else:
        raise OGCException('Invalid color value. Must be of format "0xFFFFFF".')

class CRS:

    def __init__(self, namespace, code):
        self.namespace = namespace.lower()
        self.code = int(code)
        self.proj = None

    def __repr__(self):
        return '%s:%s' % (self.namespace, self.code)

    def __eq__(self, other):
        if str(other) == str(self):
            return True
        return False

    def inverse(self, x, y):
        if not self.proj:
            self.proj = Projection('+init=%s:%s' % (self.namespace, self.code))
        return self.proj.inverse(Coord(x, y))

    def forward(self, x, y):
        if not self.proj:
            self.proj = Projection('+init=%s:%s' % (self.namespace, self.code))
        return self.proj.forward(Coord(x, y))

class CRSFactory:

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

    def __call__(self, crsstring):
        if not re.match('^[A-Z]{3,5}:\d+$', crsstring):
            raise OGCException('Invalid format for the CRS parameter: %s' % crsstring, 'InvalidCRS')
        crsparts = crsstring.split(':')
        if crsparts[0] in self.allowednamespaces:
            return CRS(crsparts[0], crsparts[1])
        else:
            raise OGCException('Invalid CRS Namespace: %s' % crsparts[0], 'InvalidCRS')

def copy_layer(obj):
    lyr = Layer(obj.name)
    lyr.abstract = obj.abstract
    lyr.active = obj.active
    lyr.clear_label_cache = obj.clear_label_cache
    lyr.datasource = obj.datasource
    #lyr.maxzoom = obj.maxzoom
    #lyr.minzoom = obj.minzoom
    lyr.queryable = obj.queryable
    lyr.srs = obj.srs
    lyr.title = obj.title
    if hasattr(obj,'wmsdefaultstyle'):
        lyr.wmsdefaultstyle = obj.wmsdefaultstyle
    if hasattr(obj,'wmsextrastyles'):
        lyr.wmsextrastyles = obj.wmsextrastyles
    return lyr

def copy_style(obj):
    sty = Style()
    for rule in obj.rules:
       sty.rules.append(rule)
    return sty

class WMSBaseServiceHandler(BaseServiceHandler):

    def GetMap(self, params):
        m = self._buildMap(params)
        im = Image(params['width'], params['height'])
        render(m, im)
        return Response(params['format'], im.tostring(PIL_TYPE_MAPPING[params['format']]))

    def GetFeatureInfo(self, params, querymethodname='query_point'):
        m = self._buildMap(params)
        if params['info_format'] == 'text/plain':
            writer = TextFeatureInfo()
        elif params['info_format'] == 'text/xml':
            writer = XMLFeatureInfo()
        if params['query_layers'] and params['query_layers'][0] == '__all__':
            for layerindex, layer in enumerate(m.layers):
                featureset = getattr(m, querymethodname)(layerindex, params['i'], params['j'])
                features = featureset.features
                if features:
                    writer.addlayer(layer.name)
                    for feat in features:
                        writer.addfeature()
                        for prop in feat.properties:
                            writer.addattribute(prop[0], prop[1])
        else:
            for layerindex, layername in enumerate(params['query_layers']):
                if layername in params['layers']:
                    if m.layers[layerindex].queryable:
                        featureset = getattr(m, querymethodname)(layerindex, params['i'], params['j'])
                        features = featureset.features
                        if features:
                            writer.addlayer(m.layers[layerindex].name)
                            for feat in features:
                                writer.addfeature()
                                for prop in feat.properties:
                                    writer.addattribute(prop[0], prop[1])
                    else:
                        raise OGCException('Requested query layer "%s" is not marked queryable.' % layername, 'LayerNotQueryable')
                else:
                    raise OGCException('Requested query layer "%s" not in the LAYERS parameter.' % layername)
        return Response(params['info_format'], str(writer))

    def _buildMap(self, params):
        if str(params['crs']) not in self.allowedepsgcodes:
            raise OGCException('Unsupported CRS "%s" requested.' % str(params['crs']).upper(), 'InvalidCRS')
        if params['bbox'][0] >= params['bbox'][2]:
            raise OGCException("BBOX values don't make sense.  minx is greater than maxx.")
        if params['bbox'][1] >= params['bbox'][3]:
            raise OGCException("BBOX values don't make sense.  miny is greater than maxy.")
        if params.has_key('styles') and len(params['styles']) != len(params['layers']):
            raise OGCException('STYLES length does not match LAYERS length.')
        m = Map(params['width'], params['height'], '+init=%s' % params['crs'])
        if params.has_key('transparent') and params['transparent'] == 'FALSE':
            if params['bgcolor']:
                m.background = params['bgcolor']
        else:
            m.background = Color(0, 0, 0, 0)
        maplayers = self.mapfactory.layers
        orderedmaplayers = self.mapfactory.ordered_layers
        mapstyles = self.mapfactory.styles
        mapaggregatestyles = self.mapfactory.aggregatestyles
        # a non WMS spec way of requesting all layers
        if params['layers'] and params['layers'][0] == '__all__':
            for layername in orderedmaplayers:
                layer = copy_layer(layername)
                reqstyle = layer.wmsdefaultstyle
                if reqstyle in mapaggregatestyles.keys():
                    for stylename in mapaggregatestyles[reqstyle]:
                        layer.styles.append(stylename)
                else:
                    layer.styles.append(reqstyle)
                for stylename in layer.styles:
                    if stylename in mapstyles.keys():
                        m.append_style(stylename, mapstyles[stylename])
                m.layers.append(layer)
        else:
            for layerindex, layername in enumerate(params['layers']):
                try:
                    layer = copy_layer(maplayers[layername])
                except KeyError:
                    raise OGCException('Layer "%s" not defined.' % layername, 'LayerNotDefined')
                try:
                    reqstyle = params['styles'][layerindex]
                except IndexError:
                    reqstyle = ''
                if reqstyle and reqstyle not in layer.wmsextrastyles:
                    raise OGCException('Invalid style "%s" requested for layer "%s".' % (reqstyle, layername), 'StyleNotDefined')
                if not reqstyle:
                    reqstyle = layer.wmsdefaultstyle
                if reqstyle in mapaggregatestyles.keys():
                    for stylename in mapaggregatestyles[reqstyle]:
                        layer.styles.append(stylename)
                else:
                    layer.styles.append(reqstyle)
                for stylename in layer.styles:
                    if stylename in mapstyles.keys():
                        m.append_style(stylename, mapstyles[stylename])
                    else:
                        raise ServerConfigurationError('Layer "%s" refers to non-existent style "%s".' % (layername, stylename))
                m.layers.append(layer)
        m.zoom_to_box(Envelope(params['bbox'][0], params['bbox'][1], params['bbox'][2], params['bbox'][3]))
        return m

class BaseExceptionHandler:

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

    def getresponse(self, params):
        code = ''
        message = '\n'
        if not params:
            message = '''

Welcome to the Mapnik OGCServer.

Ready to accept map requests...

For more info see: trac.mapnik.org

            '''
            return self.htmlhandler('', message)
        excinfo = exc_info()
        if self.debug:
            messagelist = format_exception(excinfo[0], excinfo[1], excinfo[2])
        else:
            messagelist = format_exception_only(excinfo[0], excinfo[1])
        message += ''.join(messagelist)
        if isinstance(excinfo[1], OGCException) and len(excinfo[1].args) > 1:
            code = excinfo[1].args[1]
        exceptions = params.get('exceptions', None)
        if self.debug:
            return self.htmlhandler(code, message)
        if not exceptions or not self.handlers.has_key(exceptions):
            exceptions = self.defaulthandler
        return self.handlers[exceptions](self, code, message, params)

    def htmlhandler(self,code,message):
        if code:
           resp_text = '
OGCServer Error:

%s
\n
Traceback:

%s
\n' %  (message, code)
        else:
           resp_text = message
        return Response('text/html', resp_text)

    def xmlhandler(self, code, message, params):
        ogcexcetree = deepcopy(self.xmltemplate)
        e = ogcexcetree.find(self.xpath)
        e.text = message
        if code:
            e.set('code', code)
        return Response(self.xmlmimetype, ElementTree.tostring(ogcexcetree))

    def inimagehandler(self, code, message, params):
        im = new('RGBA', (int(params['width']), int(params['height'])))
        im.putalpha(new('1', (int(params['width']), int(params['height']))))
        draw = Draw(im)
        for count, line in enumerate(message.strip().split('\n')):
            draw.text((12,15*(count+1)), line, fill='#000000')
        fh = StringIO()
        im.save(fh, PIL_TYPE_MAPPING[params['format']])
        fh.seek(0)
        return Response(params['format'], fh.read())

    def blankhandler(self, code, message, params):
        bgcolor = params.get('bgcolor', '#FFFFFF')
        bgcolor = bgcolor.replace('0x', '#')
        transparent = params.get('transparent', 'FALSE')
        if transparent == 'TRUE':
            im = new('RGBA', (int(params['width']), int(params['height'])))
            im.putalpha(new('1', (int(params['width']), int(params['height']))))
        else:
            im = new('RGBA', (int(params['width']), int(params['height'])), bgcolor)
        fh = StringIO()
        im.save(fh, PIL_TYPE_MAPPING[params['format']])
        fh.seek(0)
        return Response(params['format'], fh.read())

class Projection(MapnikProjection):

    def epsgstring(self):
        return self.params().split('=')[1].upper()

class TextFeatureInfo:

    def __init__(self):
        self.buffer = ''

    def addlayer(self, name):
        self.buffer += '\n[%s]\n' % name

    def addfeature(self):
        pass#self.buffer += '\n'

    def addattribute(self, name, value):
        self.buffer += '%s=%s\n' % (name, str(value))

    def __str__(self):
        return self.buffer

class XMLFeatureInfo:

    basexml = """<?xml version="1.0"?>
    <resultset>
    </resultset>
    """

    def __init__(self):
        self.rootelement = ElementTree.fromstring(self.basexml)

    def addlayer(self, name):
        layer = ElementTree.Element('layer')
        layer.set('name', name)
        self.rootelement.append(layer)
        self.currentlayer = layer

    def addfeature(self):
        feature = ElementTree.Element('feature')
        self.currentlayer.append(feature)
        self.currentfeature = feature

    def addattribute(self, name, value):
        attribute = ElementTree.Element('attribute')
        attname = ElementTree.Element('name')
        attname.text = name
        attvalue = ElementTree.Element('value')
        attvalue.text = unicode(value)
        attribute.append(attname)
        attribute.append(attvalue)
        self.currentfeature.append(attribute)

    def __str__(self):
        return '<?xml version="1.0"?>\n' + ElementTree.tostring(self.rootelement)


class Solution:
    def scoreOfParentheses(self, S: str) -> int:
        stack = []
        for c in S:
            if c == '(':
                stack.append(-1)
            else:
                v = 0
                while stack[-1] != -1:
                    v += stack.pop()

                stack.pop()
                stack.append(max(1, v*2))

        return sum(stack)

def test(S, ans):
    s = Solution()
    r = s.scoreOfParentheses(S)
    if r != ans:
        print('not correcnt', 'S', S, 'mine',  r, 'answer', ans)

test("()", 1)
test("(())", 2)
test("()()", 2)
test("(()(()))", 6)


#!/usr/bin/python2

import random
import threading
import Queue
import time

debug = False

def printT ( strg ):
    """print with timestamp"""
    print( time.ctime() + "  " + strg )

class PlcTimeout(Exception):
    """Readline timed out"""
    pass

class FakePLC( threading.Thread ):

    def printX( self, strn, force=False ):
        if (self.debugLevel >= 3) or force:
            printT("PLC:  " + strn)

    def __init__( self, dbgLevel ):
        super(FakePLC,self).__init__()
        self.outQ    = Queue.Queue()
        self.cmd     = [None,None,None]
        self.hitlist = [0, 1, 2]
        self.pos     = "<Empty>"
        self.stopbit = False
        self.cnt     = 0
        self.debugLevel = dbgLevel
        self.printX("thread starting")

    def _getIndex( self, command ):
        if command[0:2]   == "G:":
            return 0
        elif command[0:2] == "P:":
            return 1
        elif command[0:2] == "C:":
            return 2
        return -1

    def stop( self ):
        self.stopbit = True

    def run( self ):
        # emulate delays of commands in to commands out
        while not self.stopbit:
            random.shuffle( self.hitlist )
            for i in self.hitlist:
                if self.cmd[i] is not None:
                    time.sleep( random.randrange(0,2) )
                    # noinspection PyTypeChecker
                    self.printX( "run cmd = " + self.cmd[i] )
                    self.tag     = self.cmd[i][0:2]
                    self.op      = self.cmd[i][3:].rstrip()

                    self.printX("run op = " + self.op)

                    if self.op == "Reset":
                        time.sleep(2)
                        self.pos  = "<NoPosition>"
                        self.resp = "ResetDone"

                    elif self.op == "Stop":
                        time.sleep(1)
                        self.stopbit = True
                        self.resp = "Stop"

                    elif self.op == "Home":
                        self.pos  = "0.00"
                        self.resp = "0.00"

                    elif self.op[0:2] == "Go":
                        self.resp = self.op[2:].rstrip()
                        self.pos  = self.resp

                    elif self.op[0:3] == "Pos":
                        self.resp = self.pos

                    else:
                        self.resp = "Ok"

                    self.resp = self.tag + " " + self.resp

                    # corruption
                    if self.cnt == 5:
                        self.resp = "* " + self.tag + " " + self.resp
                        self.printX("run Resp = " + self.resp, force=True )

                    self.cnt = self.cnt + 1
                    self.printX("run Resp = " + self.resp )
                    self.cmd[i] = None
                    self.outQ.put( self.resp )

        # wait for output queue to empty
        while not self.outQ.empty():
            pass

    ##################################################
    # same as Serial
    def close( self ):
        pass

    def flushInput( self ):
        pass

    def write( self, bcommand ):
        self.command = bcommand.decode().rstrip()             # bString -> String

        inx = self._getIndex( self.command )
        if inx is None:
            self.printX("Badly formatted command dropped")
        elif self.cmd[inx] is not None:
            self.printX("Unit busy, dropping command:" + self.command)
        else:
            self.cmd[inx] = self.command

    def readline(self):
        for i in range(1,100):
            try:
                return self.outQ.get_nowait().encode() + "\r" # String -> bString
            except:
                time.sleep(0.1)

        return PlcTimeout

######################################################################
if __name__ == "__main__":

    plc = FakePLC(1)
    plc.start()

    printT   ( "C: Reset")
    plc.write(b'C: Reset\r' )
    printT   ( "    => " + plc.readline().decode())

    printT   ( "G: Home")
    plc.write(b'G: Home\r' )
    printT   ( "    => " + plc.readline().decode())

    printT   ( "P: Home")
    plc.write(b'P: Home\r' )
    printT   ( "    => " + plc.readline().decode())

    printT   ( "P: Go45.2")
    plc.write(b'P: Go45.2\r' )
    printT   ( "    => " + plc.readline().decode())

    printT   ( "P: Pos")
    plc.write(b'P: Pos\r' )
    printT   ( "    => " + plc.readline().decode())

    printT   ( "P: Go123.1")
    plc.write(b'P: Go123.1\r' )
    printT   ( "G: Go321")
    plc.write(b'G: Go321\r')
    printT   ( "    => " + plc.readline().decode())
    printT   ( "    => " + plc.readline().decode())

    plc.stop()
    plc.join()


# https://www.acmicpc.net/problem/9019 문제 제목 : DSLR , 언어 : Python, 날짜 : 2020-01-11, 결과 : 성공
# 처음 봤을때는 그냥 BFS돌리면 풀리겠구나 했는데 생각치도 못한곳에서 발목을 잡혔다.
# 맨처음에는 함수 D,S,L,R을 각각 선언했다. 함수 L,R의 리턴값을 구하는 과정에서 스트링을 쓰면 편리하다고 생각해서
# 정수형 > 문자열 > 정수형 이런식의 형변환이 이루어 지게끔 코드를 작성했다. 하지만 이 부분이 문제였다.
# 그래서 결국 질문게시판을 돌아다니며 다른분들의 L, R 부분의 코드를 참고해 코드를 완성시켰다.
# 왜 이런생각을 하지 못했을까..
# 맨 아래에는 맨 처음 작성했던 시간초과가 났던 코드를 첨부한다.

import sys
from collections import deque

T = int(sys.stdin.readline())
for _ in range(T):

    A, B = map(int, sys.stdin.readline().split())
    list_queue = deque([A])
    list_check = [0]*10000#{i:0 for i in range(10000)}
    list_str = ['D', 'S', 'L', 'R']

    while list_queue:
        num = list_queue.popleft()
        if num == B:
            break
        for i in range(4):
            if i == 0: # D
                num_save = (num*2)%10000
            elif i == 1: # S
                if num > 0:
                    num_save = num - 1
                else:
                    num_save = 9999
            elif i == 2: # L
                num_save = (num % 1000) * 10 + num//1000
            else: # R
                num_save = (num // 10) + (num%10) * 1000
            if not list_check[num_save]:
                list_check[num_save] = [num, list_str[i]]
                list_queue.append(num_save)

    list_result = []
    last_num = B
    count = 0
    while not last_num == A:
        last_num, action = list_check[last_num]
        list_result.append(action)
        count+=1
    for i in range(count):
        print(list_result[-1 - i], end = '')
    print()

# 시간초과 코드(아래)
import sys
from collections import deque

def D(N):
    return (N*2)%10000
def S(N):
    if N > 0:
        return N-1
    else:
        return 9999
def L(N):
    return int(N[1] + N[2] + N[3] +N[0])
    #list_N = deque(str(N))
    #list_N.append(list_N.popleft())
    #return int("".join(list_N))
    #return
def R(N):
    #list_N = deque(str(N))
    #list_N.appendleft(list_N.pop())
    #return int("".join(list_N))
    return int(N[3] + N[0] + N[1] +N[2])
#print(L(4123))

T = int(sys.stdin.readline())
for _ in range(T):

    A, B = map(int, sys.stdin.readline().split())
    list_queue = deque([A])
    list_check = [0]*10000#{i:0 for i in range(10000)}
    list_func = [D, S, L, R]
    list_str = ['D', 'S', 'L', 'R']

    while list_queue:
        num = list_queue.popleft()
        num_str = str(num)
        num_str = '0'*(4 - len(num_str)) + num_str
        if num == B:
            break
        for i in range(4):
            if i <= 1:
                num_save = list_func[i](num)
            else:
                num_save = list_func[i](num_str)
            if not list_check[num_save]:
                list_check[num_save] = [num, list_str[i]]
                list_queue.append(num_save)

    list_result = []
    last_num = B
    count = 0
    while not last_num == A:
        last_num, action = list_check[last_num]
        list_result.append(action)
        count+=1
    for i in range(count):
        print(list_result[-1 - i], end = '')
    print()


import os
import shutil

from argparse import ArgumentParser

def main(experiment: str):
    if experiment == "main":
        with open("results.csv", "w") as fp:
            fp.write(
                "Seed,Fold,Baseline,Topk,Explainer,Lambda_1,Lambda_2,Accuracy,Comprehensiveness,Cross Entropy,"
                "Log Odds,Sufficiency\n"
            )

    if experiment == "lambda_study":
        with open("lambda_study.csv", "w") as fp:
            fp.write(
                "Seed,Fold,Baseline,Topk,Explainer,Lambda_1,Lambda_2,Accuracy,Comprehensiveness,Cross Entropy,"
                "Log Odds,Sufficiency\n"
            )

    elif experiment == "extremal_mask_params":
        with open("extremal_mask_params.csv", "w") as fp:
            fp.write("Metric,Baseline,Topk,Model\n")

    else:
        raise NotImplementedError

    if os.path.exists("lightning_logs"):
        shutil.rmtree("lightning_logs")

def parse_args():
    parser = ArgumentParser()
    parser.add_argument(
        "--experiment",
        "-e",
        type=str,
        required=True,
        help="Name of the experiment. Either 'main', 'lambda_study' or 'extremal_mask_params'.",
    )
    return parser.parse_args()

if __name__ == "__main__":
    args = parse_args()
    main(experiment=args.experiment)


from google.cloud import bigquery
import os
import json

PROJECT_ID = 'data-test-sde'
KEY_FILE_PATH = 'key/data-test-sde-app-key.json'
DATASET_RAW = 'raw'

def get_biquery_client():
    '''
    return client connection to bigquery
    '''
    client = bigquery.Client.from_service_account_json(KEY_FILE_PATH, project=PROJECT_ID)
    return client

def execute_biquery_insert(ds_name, tbl_name, rows_to_insert):
    '''
    wrapper to execute bigquery table insert
    '''
    client = get_biquery_client()
    tbl_ref = client.dataset(ds_name).table(tbl_name)
    table = client.get_table(tbl_ref)  # API call
    errors = client.insert_rows(table, rows_to_insert) # API request
    return errors

def set_response(code, body):
    '''
    helper function to create response object
    '''
    resp = {}
    resp['statusCode']=code
    resp['body']=json.dumps(body)
    return resp

def lambda_handler(event, context):
  try:
    params=event["queryStringParameters"]
    table = params["table_name"]
    rows = []
    params.pop("table_name", None)
    rows.append(params)
    errors = execute_biquery_insert(DATASET_RAW, table, rows)
    if len(errors)==0:
        response = set_response(200, 'Row added successfully')
    else:
        response = set_response(404, errors[0])
  except Exception as ex:
      response = set_response(500, str(ex))
  print(response)
  return response

if __name__ == '__main__':
  event = {
    "queryStringParameters": {
      "category_id": "4",
      "external_id": "123",
      "name": "banana lipstick",
      "table_name": "products",
      "type": "product"
    }
  }
  lambda_handler(event, None)


from flask import Flask, request, jsonify
import numpy as np
from models import superresolution, detect_layout, lp_ocr, layout_parse_text
from config import exec_net, lp_model
from helper import plot_layout, to_rgb

app = Flask(__name__)

@app.route("/")
def index():
    return '''

Welcome to Computer Vision ML Models API!

Developed by Mohamad Oghli

    '''

@app.route("/models")
def models():
    return '''

Currently Available Models

            Model
            Endpoint
            Parameter

            Super Resolution
            /models/super_resolution
            Image

    '''

@app.route('/models/super_resolution', methods=['POST'])
def sr_inference():
    data = request.get_json()
    if 'image' in data:
        req_image = np.array(data['image'], dtype="uint8")
        org_image, sr_image = superresolution(req_image, exec_net)
        return jsonify({"origin": org_image.tolist(), "super": sr_image.tolist()})
    return jsonify({"message": "Sorry, Invalid Image Parameter!"})

@app.route('/models/layout_ocr', methods=['POST'])
def lp_ocr_agent():
    data = request.get_json()
    if 'image' in data:
        req_image = np.array(data['image'], dtype="uint8")
        #req_image = to_rgb(req_image)
        ocr_text = lp_ocr(req_image, 'eng')
        return jsonify({"ocr": ocr_text})
    return jsonify({"message": "Sorry, Invalid Image Parameter!"})

@app.route('/models/layout_parser', methods=['POST'])
def lp_inference():
    data = request.get_json()
    if 'image' in data:
        req_image = np.array(data['image'], dtype="uint8")
        # Convert the image from BGR (cv2 default loading style)
        # to RGB
        req_image = to_rgb(req_image)
        layout = detect_layout(req_image, lp_model)
        lp_image = plot_layout(req_image, layout)
        return jsonify({"layout": lp_image.tolist()})
    return jsonify({"message": "Sorry, Invalid Image Parameter!"})

@app.route('/models/layout_parser/get_text', methods=['POST'])
def lp_get_text():
    data = request.get_json()
    if 'image' in data:
        req_image = np.array(data['image'], dtype="uint8")
        req_image = to_rgb(req_image)
        lp_text = layout_parse_text(req_image, lp_model)
        return jsonify({"layout_text": lp_text})
    return jsonify({"message": "Sorry, Invalid Image Parameter!"})

if __name__ == "__main__":
    app.run()


import torch
import torchvision
import torch.nn as nn
import torch.optim as optim
import numpy as np
import matplotlib.pyplot as plt
import os
from models import CNN
from PIL import Image

BATCH_SIZE = 100
WEIGHT_DECAY = 0.005
LEARNING_RATE = 0.0001
EPOCH = 11
PATH = "Dataset"

transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor(),torchvision.transforms.Normalize((0.5,), (0.5,))])

tensor = torchvision.transforms.ToTensor()

trainset = torchvision.datasets.MNIST(root = PATH, train = True, download = True, transform = transform)
# print(trainset[0])

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
net = CNN()
net = net.to(device)
net.load_state_dict(torch.load('checkpoints/ckpt_e10.pth', map_location=device))
criterion = nn.CrossEntropyLoss()

input_ = Image.open("./img_1.jpg")
label = 0

# print(np.array(input_))

input_ = transform(input_)
# print(input_)
input_ = input_.unsqueeze(0)

input_ = input_.to(device)
outputs = net(input_)
print(input_)
print(outputs)
loss = criterion(outputs, tensor([label]))
_, predicted = outputs.max(1)


# -*- coding=utf-8 -*-
"""
Created by lichen on 2018/8/7.
"""

import time
import random

from freetime.util import log as ftlog
from freetime.core.timer import FTLoopTimer
from newfish.entity import config, share_system
from newfish.entity.share_system import RandomChest

class ShareFishGroup(object):
    """
    分享宝箱鱼群
    """
    def __init__(self, table):
        self.table = table
        self._interval = 60         # 间隔
        self._totalTime = 0
        self.checkTimer = FTLoopTimer(self._interval, -1, self._checkCondition)
        self.checkTimer.start()

    def clearTimer(self):
        if self.checkTimer:
            self.checkTimer.cancel()
            self.checkTimer = None

    def _checkCondition(self):
        """检查条件"""
        self._totalTime += self._interval
        # 所有人可见的宝箱出现时间600s
        if self._totalTime % 600 == 0:
            groupId = self._getFishGroupId()
            if groupId:
                self._addShareFishGroup(groupId)
        else:
            # 玩家个人宝箱出现时间
            for player in self.table.players:
                if player:
                    appearCount, playTime, expiresTime, state = self._getShareData(player.userId)
                    if ftlog.is_debug():
                        ftlog.debug("ShareFishGroup_checkCondition", player.userId, appearCount, playTime, expiresTime)
                    appearMinTime = 180 + 120 * appearCount
                    appearMaxTime = 240 + 120 * appearCount
                    groupId = self._getFishGroupId()
                    if (appearMinTime <= playTime * 60 <= appearMaxTime and time.time() > expiresTime and
                       state == share_system.ShareRewardState.Unavailable and groupId):
                        self._addShareFishGroup(groupId, player.userId)

    def _getShareData(self, userId):
        """获取分享宝箱鱼的数据"""
        shareClass = RandomChest(userId)
        return shareClass.shareData[share_system.INDEX_OTHER_DATA].get("appearCount", 0), \
               shareClass.shareData[share_system.INDEX_OTHER_DATA].get("playTime", 0), \
               shareClass.shareData[share_system.INDEX_OTHER_DATA].get("expiresTime", 0), \
               shareClass.shareData[share_system.INDEX_OTHER_DATA].get("state", 0)

    def addAppearCount(self, userId=None):
        """添加分享鱼出现的次数"""
        if userId:
            shareClass = RandomChest(userId)                # 随机分享宝箱
            appearCount = shareClass.shareData[share_system.INDEX_OTHER_DATA].get("appearCount", 0) + 1
            shareClass.shareData[share_system.INDEX_OTHER_DATA]["appearCount"] = appearCount
            shareClass.shareData[share_system.INDEX_OTHER_DATA]["playTime"] = 0
            shareClass.saveData()

    def _getFishGroupId(self):
        """获取鱼群Id"""
        shareFishConf = config.getShareFishConf(self.table.runConfig.fishPool)      # 获取分享宝箱鱼配置
        randInt = random.randint(1, 10000)
        for fish in shareFishConf["fishes"]:
            probb = fish["probb"]
            if probb[0] <= randInt <= probb[1]:
                fishType = fish["fishType"]
                allShareGroupIds = self.table.runConfig.allShareGroupIds
                groupId = random.choice(allShareGroupIds[fishType])
                return groupId
        return None

    def _addShareFishGroup(self, groupId, userId=None):
        """添加分享宝箱鱼群"""
        if ftlog.is_debug():
            ftlog.debug("_addShareFishGroup", groupId, userId)
        self.table.insertFishGroup(groupId, userId=userId, sendUserId=userId)
        self.addAppearCount(userId)


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# The above encoding declaration is required and the file must be saved as UTF-8
from ..entities.column import Column
from ..entities.widget import Widget

class ColumnService(object):
    def __init__(self, requester):
        self.__requester = requester

    def getColumn(self, columnId):
        """

        :rtype: Column
        """
        columnJson = self.__requester.getColumn(columnId)
        column = Column(columnJson, self.__requester)
        return column

    def getColumnByName(self, name, columns):
        """

        :rtype: Column
        """
        for column in columns:
            if column.name == name:
                return column
        return None

    def createColumn(self, widget_or_widgetCommonId, column_name, position=None):
        """

        :rtype: Column
        """
        widgetCommonId = widget_or_widgetCommonId
        if isinstance(widget_or_widgetCommonId, Widget):
            widgetCommonId = widget_or_widgetCommonId.widgetCommonId

        columnJson = self.__requester.createColumn(widgetCommonId, column_name, position)
        column = Column(columnJson, self.__requester)
        return column


from shop import Shop
from store import Store
from request import Request, show

if __name__ == '__main__':
    store1 = Store(name='склад111', items={'gingerbread': 25, 'apple': 15}, capacity=100)
    store1.add('gingerbread', 25)
    store1.add('orange', 4)

    shop1 = Shop(name='магазин5*5', items={}, capacity=6)
    shop1.add('orange', 1)

    # request_1 = 'Доставить 2 orange из склад1 в магазин5'

    while 1:
        show(store1.get_items(), store1.get_name)
        show(shop1.get_items(), shop1.get_name)

        req_1 = Request(input('\nEnter query: '))
        what = req_1.product
        how_much = req_1.amount
        maximum = shop1.capacity

        existed_in_destination = shop1.items.get(what, 0)
        existed_in_repository = store1.items.get(what, 0)
        summary = existed_in_repository + existed_in_destination
        free = shop1.get_free_space()
        movement_necessity = how_much - existed_in_destination
        if movement_necessity < 0:
            movement_necessity = 0

        if summary == 0:
            print("Отсутствует на складе и в магазине")
            continue

        if how_much > (existed_in_destination + free):
            print('Уменьшите количество до ', existed_in_destination + free)
            print('свободных мест на полке в магазине для ', free)
            continue

        if how_much > summary:
            print('Уменьшите количество, на складе и в магазине всего ', summary)
            continue

        store1.remove(what, movement_necessity)
        print(f'Перемещается со склада в магазин товар {movement_necessity} {what}')

        shop1.add(what, movement_necessity)
        print(f'товар {movement_necessity} {what} доставлен')

        shop1.remove(what, how_much)
        print(f'товар {how_much} {what} выдан')

        # exit()


import cv2
import numpy as np

img = cv2.imread("Resources/imag.png")

width,height = 250,350
pts1 = np.float32([[111,219],[287,188],[154,482],[352,440]])
pts2 = np.float32([[0,0],[width,0],[0,height],[width,height]])

# to change the orientation of image we use below func.
matrix = cv2.getPerspectiveTransform(pts1,pts2)
imgOut = cv2.warpPerspective(img,matrix,(width,height))

cv2.imshow("Image",img)
cv2.imshow("Output", imgOut)

cv2.waitKey(0)


from docx import Document
from docx.shared import Inches
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from docx.enum.text import WD_ALIGN_PARAGRAPH
import os, glob
import os
from freq import *
from django.conf import settings
from django.core.files.storage import default_storage
import ntpath
from docx.enum.text import WD_COLOR_INDEX
import matplotlib.patches as mpatches
from django.conf import settings

#script_dir_root = os.path.dirname(__file__)
script_dir = settings.STATIC_ROOT
mapas_dir = os.path.join(script_dir, 'mapas')
graficas_dir = os.path.join(script_dir, 'graficas')

def mapa(latitud, longitud, nombre, type):

    colors=['red','green','blue','black', 'orange','gray','yellow']
    ruh_m = plt.imread(os.path.join(script_dir, 'map.png'))
    nombre=nombre+".png"
    # BBox = ((-74.1704,  -74.0097,
    #     4.5982, 4.7138))
    BBox = ((-74.2453,  -73.9239,
        4.5412, 4.7725))

    fig, ax = plt.subplots()
    if type==True:
        for i in range(len(latitud)):
            ax.scatter( longitud[i],latitud[i], s=1, zorder=1, alpha= 1, c=colors[i])
    else:
        ax.scatter( longitud,latitud, s=1, zorder=1, alpha= 1, c='b')
    ax.set_title('Drive Test Powered by Sostecnible')
    ax.set_xlim(BBox[0],BBox[1])
    ax.set_ylim(BBox[2],BBox[3])
    # red_patch = mpatches.Patch(color='red', label='The red data')
    # ax.legend(handles=[red_patch])
    # legend1 = ax.legend()
    # ax.add_artist(legend1)
    ax.imshow(ruh_m, zorder=0, extent = BBox, aspect= 'auto')
    dir = os.path.join(script_dir, 'mapas')
    dir2 = os.path.join(dir, nombre)
    print(dir2)
    plt.savefig(dir2,  dpi=250)
    plt.clf()
    plt.cla()
    plt.close()

def generar_mapas(df):
    latitud=df['LAT']
    longitud=df['LON']
    lista=[1, 0, 3, 4]
    for i in lista:
        nombre="mapa_"+str(i)
        if i==1:
            mapa(latitud, longitud, nombre, False)
        else:
            lista=df.loc[df['SYSTEM'] ==i]
            latitud=lista['LAT']
            longitud=lista['LON']
            mapa(latitud, longitud, nombre, False)

def generar_histogramas(df):
    lista=[ 'PLMN', 'SYSTEM','BAND']
    for i in lista:
        nombre = os.path.join(graficas_dir, str(i))
        histogram(i, nombre, df)

def generar_mapas_roaming(df):

    a = df['PLMN'].unique()
    latitud=[]
    longitud=[]
    nombre="REDES"
    for i in a:
        # nombre="mapa_"+str(i)
        lista=df.loc[df['PLMN'] ==i]
        latitud.append(lista['LAT'])
        longitud.append(lista['LON'])

    print(len(longitud))
    print(len(latitud))

    mapa(latitud, longitud, nombre, True)

def generar_mapas_roaming_2(df):

    a = df['PLMN'].unique()

    for i in a:
        print (i)
        nombre="mapa_"+str(i)
        lista=df.loc[df['PLMN'] ==i]
        latitud=lista['LAT']
        longitud=lista['LON']
        mapa(latitud, longitud, nombre, False)

def generar_mapas_ca(df):
    lista=df.loc[df['CA'] ==2]
    if len(lista)>0:

        latitud=lista['LAT']
        longitud=lista['LON']
        nombre="mapa_CA"
        # latitud=[]
        # longitud=[]
        # for i in a:
        #     print (i)
        #     lista=df.loc[df['CA'] ==i]
        #     latitud.append(lista['LAT'])
        #     longitud.append(lista['LON'])

        mapa(latitud, longitud, nombre, False)
    else:
        pass

def guardar():

    f = open(os.path.join(script_dir, 'base.docx'), 'rb')
    document = Document(f)

    lista=['PLMN', 'SYSTEM','BAND', 'gps']
    puntos=[".0",""]

    for i in lista:
        nombre = os.path.join(graficas_dir, str(i))

        if i=='gps':
            document.add_paragraph(
            'GPS ', style='parrafo')

        else:
            document.add_paragraph(
            'histograma '+str(i), style='parrafo')

        document.add_picture(nombre+".png", width=Inches(5))
        last_paragraph = document.paragraphs[-1]
        last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

    for i, j in zip([1, 4,3,0, 'CA'], ['mapa recorrido', 'mapa 4G', 'mapa 3G','mapa sin cobertura','mapa CA']):

        mapa=os.path.join(mapas_dir, 'mapa_'+str(i)+'.png')

        if not os.path.isfile(mapa):
            continue

        document.add_paragraph(
        j, style='parrafo'
        )
        document.add_picture(mapa, width=Inches(5))
        last_paragraph = document.paragraphs[-1]
        last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

        mapa_redes= os.path.join(mapas_dir, 'REDES.png')

    document.add_paragraph(
    'Mapa red redes', style='parrafo'
    )
    document.add_picture(mapa_redes, width=Inches(5))
    last_paragraph = document.paragraphs[-1]
    last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
    #
    for punto in puntos:

        mapa_360= os.path.join(mapas_dir, 'mapa_732360'+punto+'.png')
        if not os.path.isfile(mapa_360):
            continue

        for i, j in zip([732360,732130,732123,732103,732101]  , ['mapa red 360', 'mapa red 130', 'mapa red 123','mapa red 103', 'mapa red 101']):

            mapa= os.path.join(mapas_dir, 'mapa_'+str(i)+punto+'.png')
            if not os.path.isfile(mapa):
                continue
            document.add_paragraph(
            j, style='parrafo'
            )

            document.add_picture(mapa, width=Inches(5))
            last_paragraph = document.paragraphs[-1]
            last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

    document.add_paragraph(
    "",style='parrafo').add_run(
           "Para complementar por favor verificar evidencias en el siguiente enlace LINK EVIDENCIAS."
           ).font.highlight_color = WD_COLOR_INDEX.YELLOW

    doc_dir = os.path.join(script_dir, 'demo.docx')

    document.save(doc_dir)
    f.close()

def borrar():
    dir_1 = os.path.join(script_dir, 'mapas')
    dir_2 = os.path.join(script_dir, 'graficas')
    # dir = "/Users/juans/Documents/informe_drivetest/mapas"
    for i in [dir_1, dir_2]:
        for file in os.scandir(i):
             os.remove(file.path)

def main_map(df):
    df.replace(os.sep,ntpath.sep)
    df=df[1:]
    df=pd.read_csv(df,  sep=';')
    borrar()
    gps_(df,graficas_dir)
    generar_histogramas(df)
    generar_mapas_ca(df)
    generar_mapas(df)
    generar_mapas_roaming(df)
    generar_mapas_roaming_2(df)
    # #generar_mapas_ca(df)
    guardar()

    #borrar()

#
# if __name__ == '__main__':
#     #revisar()
#     main()


import numpy as np
class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        ngas = np.array(gas)
        ncost = np.array(cost)

        diff = list(ngas-ncost)
        if sum(diff)<0:
            return -1

        stack = []
        stackans = 0
        i=0
        while i<len(diff):
            if diff[i]>=0:
                stack.append([diff[i],i])
                stackans+=diff[i]
            else:
                if stackans+diff[i]>=0:
                    stack.append([diff[i],i])
                    stackans+=diff[i]
                else:
                    stackans=0
                    stack=[]
            i+=1

        return stack[0][1]


import time
from project.Locators.locators import Locators

class AirtimeRechargePage():
    def __init__(self, driver):
        self.driver = driver

        self.buy_airtime_button_xpath = Locators.buy_airtime_button_xpath
        self.phone_number_textbox2_id = Locators.phone_number_textbox2_id
        self.airtime_price_textbox_id = Locators.airtime_price_textbox_id
        self.next_button_id = Locators.next_button_id
        self.wallet_payment_radio_button_xpath = Locators.wallet_payment_radio_button_xpath
        self.confirm_payment_button_id = Locators.confirm_payment_button_id
        self.pay_button_id = Locators.pay_button_id
        self.success_home_button_id = Locators.success_home_button_id
        self.okay_button_id = Locators.okay_button_id

    def click_buy_airtime_button(self):
        self.driver.find_element_by_xpath(Locators.buy_airtime_button_xpath)\
            .click()

    def enter_phone_number(self, phonenumber):
        self.driver.find_element_by_id(Locators.phone_number_textbox2_id)\
            .send_keys(phonenumber)

    def enter_airtime_price(self, price):
        self.driver.find_element_by_id(Locators.airtime_price_textbox_id)\
            .send_keys(price)
        self.driver.find_element_by_id(Locators.next_button_id).click()

    def wallet_payment(self):
        self.driver.find_element_by_xpath(Locators.wallet_payment_radio_button_xpath)\
            .click()
        self.driver.find_element_by_id(Locators.confirm_payment_button_id).click()
        time.sleep(9)
        self.driver.find_element_by_id(Locators.pay_button_id).click()

    def success_payment(self):
        self.driver.find_element_by_id(Locators.success_home_button_id).click()
        time.sleep(3)
        self.driver.find_element_by_id(Locators.okay_button_id).click()


from tortoise import fields
from tortoise.models import Model
from tortoise.contrib.pydantic import pydantic_model_creator

class HostUser(Model):
    id = fields.IntField(pk=True)
    host_email = fields.CharField(max_length=50, unique=True)
    host_id = fields.CharField(max_length=100, unique=True)
    created_at = fields.DatetimeField(auto_now_add=True)
    modified_at = fields.DatetimeField(auto_now=True)

    class Meta:
        ordering = ['host_email']

class HostedMeeting(Model):
    """
    This references a hosted meeting by host user
    """

    id = fields.IntField(pk=True)
    meeting_id = fields.CharField(max_length=100)
    start_time = fields.DatetimeField()
    end_time = fields.DatetimeField(null=True,default=None)
    timezone = fields.CharField(max_length=20)
    event = fields.CharField(max_length=20,null=True)
    created_at = fields.DatetimeField(auto_now_add=True)
    modified_at = fields.DatetimeField(auto_now=True)

    hostuser = fields.ForeignKeyField(
        "models.HostUser", related_name="hostuser", description="user hosted this meeting"
    )

HostUserPydantic = pydantic_model_creator(HostUser)
HostedMeetingPydantic = pydantic_model_creator(HostedMeeting)


#!/usr/bin/env python
""" yaml test """

from itertools import chain
from collections import namedtuple
import yaml

Stack = namedtuple("stack", ["file_name", "name", "parameters"])

KEY_REQUIRE = "require"
KEY_STACKS = "stacks"
KEY_NAME = "name"
KEY_PARAMETERS = "args"

def scope_pick(scope, part):
    """ get part of scope """
    parts = [scope[part], ]
    try:
        while True:
            required = parts[0][0][KEY_REQUIRE]
            parts[0].pop(0)
            parts = [scope[required]] + parts
    except (KeyError, TypeError):
        pass
    for stack in chain(*parts):
        try:
            stack_file, values = stack.popitem()
            stack_name = values[KEY_NAME]
            parameters = []
            for key, value in values[KEY_PARAMETERS].items():
                parameters.append({
                    "ParameterKey" : key,
                    "ParameterValue": value})
        except AttributeError:
            stack_file = stack
            stack_name = stack
            parameters = []
        except KeyError:
            print("bad_template")
        yield Stack(file_name=stack_file,
                    name=stack_name,
                    parameters=parameters)

if __name__ == "__main__":
    full_scope = yaml.load(open("test.yaml").read())
    print(list(scope_pick(full_scope, "apps")))


import os
import cv2
import numpy as np
import os
from skimage.metrics import peak_signal_noise_ratio
from skimage.metrics import structural_similarity
import math

from PIL import Image
PATH = "gallary/eval_gallary/cost_spn_epoch2"
DRANGE = 2 ** 16 / 4000.0

def psnr(img1, img2):
    mse = np.mean( (img1 - img2) ** 2 )
    if mse == 0:
        return 100
    PIXEL_MAX = 255.0
    return 20 * math.log10(PIXEL_MAX / math.sqrt(mse))

def ssim(y_true , y_pred):
    u_true = np.mean(y_true)
    u_pred = np.mean(y_pred)
    var_true = np.var(y_true)
    var_pred = np.var(y_pred)
    std_true = np.sqrt(var_true)
    std_pred = np.sqrt(var_pred)
    c1 = np.square(0.01*7)
    c2 = np.square(0.03*7)
    ssim = (2 * u_true * u_pred + c1) * (2 * std_pred * std_true + c2)
    denom = (u_true ** 2 + u_pred ** 2 + c1) * (var_pred + var_true + c2)
    return ssim/denom

def rmse(src, ref, size):
    diff_sqr = np.square(src - ref)
    return np.sqrt(diff_sqr.sum() / (size + 1e-8))

def mse(src, ref, size):
    diff_sqr = np.square(src - ref)
    return diff_sqr.sum() / (size + 1e-8)

def mae(src, ref, size):
    diff_abs = np.abs(src-ref)
    return diff_abs.sum() / (size + 1e-8)

def evaluate(src, ref, size):

    metrics = np.zeros(5)

    metrics[0] = rmse(src, ref, size)
    metrics[1] = mae(src, ref, size)
    metrics[2] = mse(src, ref, size)
    metrics[3] = ssim(src, ref)
    metrics[4] = peak_signal_noise_ratio(src, ref, data_range = DRANGE)

    return metrics

gt_depth_names = os.listdir(os.path.join(PATH, 'unscale_gt'))
gt_depth_names.sort(key=lambda x: x.split("_")[3]+x.split("_")[5])
gt_depth_paths = [os.path.join(PATH, 'unscale_gt', depth_name) for depth_name in gt_depth_names]

pred_depth_names = os.listdir(os.path.join(PATH, 'unscale_pred'))
pred_depth_names.sort(key=lambda x: x.split("_")[3]+x.split("_")[5])
pred_depth_paths = [os.path.join(PATH, 'unscale_pred', depth_name) for depth_name in pred_depth_names]

raw_depth_names = os.listdir(os.path.join(PATH, 'unscale_raw'))
raw_depth_names.sort(key=lambda x: x.split("_")[3]+x.split("_")[5])
raw_depth_paths = [os.path.join(PATH, 'unscale_raw', depth_name) for depth_name in raw_depth_names]

t_valid = 0.0001

mask_metrics = np.zeros((len(raw_depth_names), 5))
metrics = np.zeros((len(raw_depth_names), 5))
gt_metrics = np.zeros((len(raw_depth_names), 5))
gt_mask_metrics = np.zeros((len(raw_depth_names), 5))
mask_ssims = np.zeros(len(pred_depth_names))

for i in range(len(raw_depth_names)):

    raw_name = raw_depth_names[i]
    pred_name = pred_depth_names[i]
    gt_name = gt_depth_names[i]

    raw_path = raw_depth_paths[i]
    pred_path = pred_depth_paths[i]
    gt_path = gt_depth_paths[i]

    pred = Image.open(pred_path)
    raw = Image.open(raw_path)
    gt = Image.open(gt_path)

    pred = np.array(pred, dtype=np.uint16)
    raw = np.array(raw, dtype=np.uint16)
    gt = np.array(gt, dtype=np.uint16)

    pred = pred / 4000.0
    raw = raw / 4000.0
    gt = gt / 4000.0

    mask = raw > t_valid
    num_valid = mask.sum()
    num_pixel = pred.shape[0] * pred.shape[1]

    mask_pred = pred[mask]
    mask_raw = raw[mask]
    mask_gt = gt[mask]

    mask_ssims[i] = ssim(mask_pred, mask_raw)

    metrics[i] = evaluate(raw, pred, num_pixel)
    mask_metrics[i] = evaluate(mask_pred, mask_raw, num_valid)
    gt_metrics[i] = evaluate(gt, pred, num_pixel)
    gt_mask_metrics[i] = evaluate(mask_gt ,mask_pred, num_valid)

print(np.mean(metrics, axis=0))
print(np.mean(mask_metrics, axis=0))
print(np.mean(gt_metrics, axis=0))
print(np.mean(gt_mask_metrics, axis=0))


# ----------------------------------------------------------------------------------------------------------------
# This program evaluates data stored a Stelar Data File (a sdf-file) into magnetization relaxation functions and
# then calls one of the parameterization routines: logmoments(), lmfit_kohlrausch(), or lmfit_exponential().
# ----------------------------------------------------------------------------------------------------------------
# In particular, the following steps are executed:
# 1) open the sdf-file for reading;
# 2) read the file line by line looking for the parameters ZONE, T1MX, BRLX, BS, NBLK, BGRD, BINI, and BEND;
# 3) once a DATA block is encountered, read the data to a 2-d array of Re& Im values;
# 4) quantify magnitization using time-domain data (FID's);
# 5) reconstruct a time scale from the read parameters and stacks it against the quantified magnetization.
# 6) proceed with parameterization of thus-built relaxation functions, exercising one of the three options:
#   -- mono-exponential fit to the magnetization relaxation curve, which yields one output parameter (T1);
#   -- stretched-exponential fit, which yields two output parameters (arithmetic mean T1 and stretching exponent beta);
#   -- logarithmic moment analysis, which gives up to three parameters (geometric mean T1, geometric standard deviation,
#      and a skewness parameter).
# 7) plot the magnetization decays and the sough-after parameters against the relaxation field (a.k.a. relaxation profiles).
# 8) write the results in a text file profile_output.txt.
#
# v1.0 August 2017
# Author: Oleg V. Petrov, TU Ilmenau
# E-mail: oleg.petrov@tu-ilmenau.de
import os

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import logarithmic_moment_analysis as lma
import lmfit_exponential
import lmfit_kohlrausch
import re
from math import gamma
import warnings

warnings.filterwarnings("always")

datafile = "land_SM_dips.sdf"  # Stelar's data file (sdf)
datadir = os.path.join( os.getcwd(), "..", "input")

def export(save_path, profiles, the_header, fig):
    input_basename = datafile.split('.')[0]
    fig.savefig(os.path.join(save_path, '{}_out.png'.format(input_basename)), format='png', dpi=175)
    np.savetxt(
        os.path.join(save_path, '{}_out.txt'.format(input_basename)),
        profiles,
        fmt='%.4e',
        delimiter='\t',
        header=the_header
    )

def main():
    # __________________ Adjustable parameters: __________________

    [zone_from, zone_to] = [0, 999]  # zones of interest ([1, 999]: full scope)
    [fid_from, fid_to] = [0, 20]  # FID integration limits, in points

    # parameterization options:
    method = 'stretched'  # 'monoexp': mono-exponential fit; 'stretched': stretched-exponential fit; 'logmoments': logarithmic moment analysis
    plotfit_toggle = True  # show best-fit curves along with relaxation functions
    reusable_toggle = False  # use best-fit parameters as initial values in the next fiting session
    extrapol_toggle = True  # use best-fit parameters to extrapolate relaxation functions toward zero time
    verbose_toggle = True  # print whatever a fitting routine reports
    accus = 2

    # plotting parameters (the following are less frequently modified):
    default_rcParams = {'axes.grid': True,
                        'axes.formatter.limits': [-2, 2],
                        'figure.subplot.hspace': 0.3,
                        'figure.subplot.left': 0.13,
                        'figure.subplot.right': 0.89,
                        'font.family': 'sans-serif',
                        'font.size': 12,
                        'font.weight': 'normal',
                        'grid.alpha': 0.8,
                        'grid.color': 'k',
                        'legend.fontsize': 'large',
                        'legend.frameon': True,
                        'legend.loc': 'upper right',
                        'lines.color': 'b',
                        'lines.linestyle': 'None',
                        'lines.linewidth': 1.0,
                        'lines.marker': 'o',
                        'lines.markersize': 6,
                        'xtick.color': 'k',
                        'xtick.labelsize': 'medium',
                        'ytick.color': 'k',
                        'ytick.labelsize': 'medium'}

    ax1_rcParams = default_rcParams.copy()
    ax1_rcParams.update({})

    ax2_rcParams = default_rcParams.copy()
    ax2_rcParams.update({})

    ax3_rcParams = default_rcParams.copy()
    ax3_rcParams.update({'axes.grid': False,
                         'axes.color_cycle': 'r',
                         'axes.labelcolor': 'r',
                         'lines.linestyle': '-',
                         'lines.marker': '^',
                         'ytick.color': 'r'})
    mpl.rc('axes', grid=True)
    # ____________ end of adjustable parameters ____________

    with plt.rc_context(default_rcParams):
        fig = plt.figure()
        fig.canvas._master.geometry("512x704-0+0")

    with plt.rc_context(ax1_rcParams):
        ax1 = fig.add_subplot(2, 1, 1)  # ax1 will show relaxation functions and best-fit curves
        ax1.set_title('Relaxation functions')
        ax1.set_xlabel('Time, s')
        ax1.set_ylabel('Magnetization, arb. u.')
        ax1.plot([], [], clip_on=False)

    with plt.rc_context(ax2_rcParams):
        ax2 = fig.add_subplot(2, 1, 2)  # ax2 and ax3 will show relaxation parameters
        ax2.set_title('Relaxation parameter(s)')
        ax2.set_xlabel('Relaxation field, MHz')
        ax2.set_ylabel('T1, s')
        ax2.plot([], [], clip_on=False)

    if (method is not 'monoexp') and (method is not 'biexp'):

        with plt.rc_context(ax3_rcParams):
            ax3 = ax2.twinx()
            if method == 'stretched':
                ax2.set_ylabel('Arithmetic mean T1, s')
                ax3.set_ylabel('Beta')
            elif method == 'logmoments':
                ax2.set_ylabel('Geometric mean T1, s')
                ax3.set_ylabel('Geometric SD')
            else:
                raise TypeError
            ax3.plot([], [], clip_on=False)
            for yticklabels in ax3.get_yticklabels():
                yticklabels.set_rotation(45)
        ax2.spines['right'].set_edgecolor(ax3_rcParams['ytick.color'])

    plt.show(block=False)
    ax1.set_xscale("log")
    ax2.set_xscale("log")
    ax2.set_yscale("log")
    if 'ax3' in locals():
        ax3.set_xscale("log")

    for ax in fig.axes:
        ax.xaxis._autolabelpos = False
        ax.yaxis._autolabelpos = False
        ax.margins(0.02, 0.02)

    # _______________ Start magnetization evaluation... _______________
    profiles = []
    # read the sdf file in lines:
    with open(os.path.join(datadir, datafile)) as sdf:
        for line in sdf:
            if "ZONE" in line:
                zone = int(re.search(r'\d+', line).group())
                if zone > zone_to: break
            elif "T1MX=" in line:
                try:
                    t1mx = float(re.search(r'\d+\.\d+', line).group())
                except:
                    t1mx = float(re.search(r'\s\d+', line).group())
            elif "BRLX" in line:
                brlx = float(re.search(r'\d+\.\d+', line).group())
            elif "BS" in line:
                bs = int(re.search(r'\d+', line).group())
            elif "NBLK" in line:
                nblk = int(re.search(r'\d+', line).group())
            elif "BGRD" in line:
                bgrd = line.split('=\t')[1]
                bgrd = bgrd.strip()
            elif "BINI" in line:
                try:
                    bini = float(re.search(r'\d+\.\d+', line).group())
                except:
                    bini = float(re.search(r'\d+', line).group())
                if re.search('T1MX', line):
                    bini *= t1mx
            elif "BEND" in line:
                try:
                    bend = float(line.split('=\t')[1])
                except:
                    bend = float(re.search(r'\d+\.\d+', line).group())
                # bend = float(re.search(r'\d+', line).group())
                if re.search('T1MX', line):
                    bend *= t1mx
                if bgrd == 'LOG':
                    tau = np.logspace(np.log10(bini), np.log10(bend), nblk)
                    # print tau
                else:
                    tau = np.linspace(bini, bend, nblk)
            elif "DATA" in line:
                if zone < zone_from: continue
                data = np.zeros((nblk * bs, 2))
                for i in range(nblk * bs):
                    line = sdf.next()
                    data[i, 0] = line.split()[0]
                    data[i, 1] = line.split()[1]
                fids = data[:, 0] + 1j * data[:, 1]
                fids = fids.reshape((nblk, bs))

                # __________________ Quantitation: ___________________
                magnetization = np.zeros((nblk, 2))
                magnetization[:, 0] = tau
                magnetization[:, 1] = abs(fids[:, fid_from:fid_to]).sum(axis=1)
                magnetization = magnetization[magnetization[:, 0].argsort()]

                # ________________ Parameterization: _________________
                magnetization_fit = magnetization.copy()

                if method == 'monoexp':
                    model = lmfit_exponential.minimize(magnetization[:, 0], magnetization[:, 1],
                                                       options={'order': 1, 'reusable': reusable_toggle,
                                                                'verbose': verbose_toggle})
                    magnetization_fit[:, 1] = magnetization[:, 1] + model.residual

                    # update profiles:
                    profiles.append([brlx, 1. / model.params['r1']])

                elif method == 'biexp':
                    model = lmfit_exponential.minimize(magnetization[:, 0], magnetization[:, 1],
                                                       options={'order': 2, 'reusable': reusable_toggle,
                                                                'verbose': verbose_toggle})
                    magnetization_fit[:, 1] = magnetization[:, 1] + model.residual

                    # update profiles:
                    profiles.append([brlx, 1. / model.params['r1'], 1. / model.params['r2'], model.params['a1'],
                                     model.params['a2']])

                elif method == 'stretched':
                    meanT1 = 0.
                    beta = 0.
                    for i in range(accus):
                        model = lmfit_kohlrausch.minimize(magnetization[:, 0], magnetization[:, 1],
                                                          options={'reusable': reusable_toggle})
                        beta += model.params['beta']
                        meanT1 += (gamma(1. / model.params['beta']) / model.params['r']) / model.params['beta']
                    magnetization_fit[:, 1] = magnetization[:, 1] + model.residual
                    meanT1 /= accus
                    beta /= accus
                    # update profiles:
                    profiles.append([brlx, meanT1, beta])

                elif method == 'logmoments':
                    logm1 = 0.
                    logm2 = 0.
                    logm3 = 0.
                    for i in range(accus):
                        logms, y_fit = lma.logmoments(magnetization[:, 0], magnetization[:, 1],
                                                      extrapol=extrapol_toggle,
                                                      fit_options={'order': 3, 'reusable': reusable_toggle,
                                                                   'verbose': verbose_toggle})
                        logm1 += logms[0]
                        logm2 += logms[1]
                        logm3 += logms[2]
                    logm1 /= accus
                    logm2 /= accus
                    logm3 /= accus
                    magnetization_fit[:, 1] = y_fit
                    # update profiles:
                    profiles.append([brlx, np.exp(logm1), np.exp(logm2 ** 0.5), logm3 / logm2 ** 1.5])
                else:
                    raise TypeError

                    # update subplots:
                with plt.rc_context(ax1_rcParams):
                    ax1.plot(magnetization[:, 0], magnetization[:, 1])
                    if plotfit_toggle:
                        the_color = ax1.lines[-1].get_color()
                        ax1.plot(magnetization_fit[:, 0], magnetization_fit[:, 1], '-', color=the_color)
                ax2.lines[0].set_xdata([item[0] for item in profiles])
                ax2.lines[0].set_ydata([item[1] for item in profiles])
                if 'ax3' in locals():
                    ax3.lines[0].set_xdata([item[0] for item in profiles])
                    ax3.lines[0].set_ydata([item[2] for item in profiles])
                for ax in fig.axes:
                    ax.relim()
                for ax in fig.axes:
                    ax.autoscale_view()
                fig.canvas.draw()
                fig.canvas.flush_events()

        # save the figure as png:
        for ax in fig.axes:
            ax.xaxis._autolabelpos = True
            ax.yaxis._autolabelpos = True
        if 'ax3' in locals():
            ax3.yaxis._autolabelpos = True

        # write profile(s) in a text file:
        if method == 'monoexp': the_header = ' Field(MHz)	T1(s)'
        if method == 'biexp': the_header = ' Field(MHz)	T11(s)	T11(s)	A1	A2'
        if method == 'stretched': the_header = ' Field(MHz)	Mean T1(s)	Beta'
        if method == 'logmoments': the_header = ' Field(MHz)	Mean T1(s)	SD	Skewness'

        try:
            save_dir = os.path.join('./out')
            if not os.path.exists(save_dir):
                os.makedirs(save_dir)
            export(save_dir, profiles, the_header, fig)
        except IOError:
            save_dir = os.path.join(datadir, 'out/')
            export(save_dir, profiles, the_header, fig)

if __name__ == "__main__":
    main()


#!/usr/bin/python3
from random import *

alphabet = 'abcdefghijklmnopqrstuvwxyz'
alphabet = [alphabet[i] for i in range(0, len(alphabet))]

special_char = [' ','.',',',';',':','!','?','(',')']

class txt:

    def crypt(key, source):

        crypt_txt = []
        text = open(source)

        for rows in text:
            letters = [rows[i] for i in range(0, len(rows))]

        letters.remove(letters[-1])
        print(letters)

        letters.remove('.')
        letters.remove(letters[0])

        for letter in letters:
            for digit in alphabet:

                if digit == letter:
                    crypt_txt.append(alphabet[alphabet.index(digit) + key])

            for char in special_char:
                if char == letter:
                    crypt_txt.append(char)

        text = str(alphabet[key])+'.'+''.join(crypt_txt)
        print(text)
        # KEY = alphabet[key] EX: [KEY = 2] KEY = alphabet[2] = 'c'

    def decrypt(source):

        old_txt = []
        text = open(source)

        for rows in text:
            letters = [rows[i] for i in range(0, len(rows))]

        letters.remove(letters[-1])
        print(letters)

        key = alphabet.index(letters[0])
        letters.remove('.')
        letters.remove(letters[0])

        for letter in letters:
            for digit in alphabet:
                if digit == letter:

                    old_txt.append(alphabet[alphabet.index(digit) - key])

        text = ''.join(old_txt)
        print(text)

txt.crypt(2, 'source.txt')


from bbpyp.common.model.equatable_state import EquatableState
from collections import Iterable

class DuckType(EquatableState):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        def create_properties(_self, **key_word_args):
            for key, value in key_word_args.items():
                if isinstance(value, str) or not isinstance(value, Iterable):
                    _self.__dict__[key] = value
                elif isinstance(value, dict):
                    _self.__dict__[key] = type(self)(**value)
                else:
                    _self.__dict__[key] = [
                        type(self)(**item) if isinstance(item, dict) else item for item in value]

        if len(args) == 1:
            self.__dict__["$value"] = args[0]
        elif len(args):
            self.__dict__["$value"] = list(args)

        create_properties(self, **kwargs)

    def __repr__(self):
        return f"{type(self).__name__}({self.__dict__})"

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

    def get_value(self):
        if self.is_atomic():
            return self.__dict__["$value"]
        else:
            return self.__dict__

    def is_atomic(self):
        return "$value" in self.__dict__.keys() and len(self.__dict__.keys()) == 1


# Code from OpenAI baselines
# https://github.com/openai/baselines/blob/master/baselines/common/plot_util.py

import numpy as np

def one_sided_ema(xolds, yolds, low=None, high=None, n=512, decay_steps=1., low_counts_threshold=1e-8):
    '''
    perform one-sided (causal) EMA (exponential moving average)
    smoothing and resampling to an even grid with n points.
    Does not do extrapolation, so we assume
    xolds[0] <= low && high <= xolds[-1]
    Arguments:
    xolds: array or list  - x values of data. Needs to be sorted in ascending order
    yolds: array of list  - y values of data. Has to have the same length as xolds
    low: float            - min value of the new x grid. By default equals to xolds[0]
    high: float           - max value of the new x grid. By default equals to xolds[-1]
    n: int                - number of points in new x grid
    decay_steps: float    - EMA decay factor, expressed in new x grid steps.
    low_counts_threshold: float or int
                          - y values with counts less than this value will be set to NaN
    Returns:
        tuple sum_ys, count_ys where
            xs        - array with new x grid
            ys        - array of EMA of y at each point of the new x grid
            count_ys  - array of EMA of y counts at each point of the new x grid
    '''

    low = xolds[0] if low is None else low
    high = xolds[-1] if high is None else high

    assert xolds[0] <= low, 'low = {} < xolds[0] = {} - extrapolation not permitted!'.format(
        low, xolds[0])
    assert xolds[-1] >= high, 'high = {} > xolds[-1] = {}  - extrapolation not permitted!'.format(
        high, xolds[-1])
    assert len(xolds) == len(
        yolds), 'length of xolds ({}) and yolds ({}) do not match!'.format(len(xolds), len(yolds))

    xolds = xolds.astype('float64')
    yolds = yolds.astype('float64')

    luoi = 0  # last unused old index
    sum_y = 0.
    count_y = 0.
    xnews = np.linspace(low, high, n)
    decay_period = (high - low) / (n - 1) * decay_steps
    interstep_decay = np.exp(- 1. / decay_steps)
    sum_ys = np.zeros_like(xnews)
    count_ys = np.zeros_like(xnews)
    for i in range(n):
        xnew = xnews[i]
        sum_y *= interstep_decay
        count_y *= interstep_decay
        while True:
            if luoi >= len(xolds):
                break
            xold = xolds[luoi]
            if xold <= xnew:
                decay = np.exp(- (xnew - xold) / decay_period)
                sum_y += decay * yolds[luoi]
                count_y += decay
                luoi += 1
            else:
                break
        sum_ys[i] = sum_y
        count_ys[i] = count_y

    ys = sum_ys / count_ys
    ys[count_ys < low_counts_threshold] = np.nan

    return xnews, ys, count_ys

def symmetric_ema(xolds, yolds, low=None, high=None, n=512, decay_steps=1., low_counts_threshold=1e-8):
    '''
    perform symmetric EMA (exponential moving average)
    smoothing and resampling to an even grid with n points.
    Does not do extrapolation, so we assume
    xolds[0] <= low && high <= xolds[-1]
    Arguments:
    xolds: array or list  - x values of data. Needs to be sorted in ascending order
    yolds: array of list  - y values of data. Has to have the same length as xolds
    low: float            - min value of the new x grid. By default equals to xolds[0]
    high: float           - max value of the new x grid. By default equals to xolds[-1]
    n: int                - number of points in new x grid
    decay_steps: float    - EMA decay factor, expressed in new x grid steps.
    low_counts_threshold: float or int
                          - y values with counts less than this value will be set to NaN
    Returns:
        tuple sum_ys, count_ys where
            xs        - array with new x grid
            ys        - array of EMA of y at each point of the new x grid
            count_ys  - array of EMA of y counts at each point of the new x grid
    '''
    xs, ys1, count_ys1 = one_sided_ema(
        xolds, yolds, low, high, n, decay_steps, low_counts_threshold=0)
    _,  ys2, count_ys2 = one_sided_ema(
        -xolds[::-1], yolds[::-1], -high, -low, n, decay_steps, low_counts_threshold=0)
    ys2 = ys2[::-1]
    count_ys2 = count_ys2[::-1]
    count_ys = count_ys1 + count_ys2
    ys = (ys1 * count_ys1 + ys2 * count_ys2) / count_ys
    ys[count_ys < low_counts_threshold] = np.nan
    return xs, ys, count_ys


from OpenGL.GL import *
import numpy as np
import glm
import sys;
import glfw

from pathlib import Path

class Shader:
	def __init__(self, source, shader_type):
		self._handle = glCreateShader(shader_type)
		glShaderSource(self._handle, source)
		glCompileShader(self._handle)

		# check if compilation was successful
		result = glGetShaderiv(shader_id, GL_COMPILE_STATUS)
		info_log_len = glGetShaderiv(shader_id, GL_INFO_LOG_LENGTH)
		if info_log_len:
			logmsg = glGetShaderInfoLog(shader_id)
			print(logmsg)
			sys.exit(10)

class VertexShader:
	def __init__(self, source):
		super(source, GL_VERTEX_SHADER)

class FragmentShader:
	def __init__(self, source):
		super(source, GL_FRAGMENT_SHADER)

class Program:
	def __init__(self, vertex, fragment, geometry=None):
		assert isinstance(vertex, str)
		assert isinstance(fragment, str)
		shaders = {
			GL_VERTEX_SHADER: vertex,
			GL_FRAGMENT_SHADER: fragment
		}

		# FIXME: check for a valid contex
		# and throw an error before using gl commands
		self.program_id = glCreateProgram()

		try:
			self.shader_ids = []
			for shader_type, shader_src in shaders.items():
				shader_id = glCreateShader(shader_type)
				glShaderSource(shader_id, shader_src)

				glCompileShader(shader_id)

				# check if compilation was successful
				result = glGetShaderiv(shader_id, GL_COMPILE_STATUS)
				info_log_len = glGetShaderiv(shader_id, GL_INFO_LOG_LENGTH)
				if info_log_len:
					logmsg = glGetShaderInfoLog(shader_id)
					print(logmsg)
					sys.exit(10)

				glAttachShader(self.program_id, shader_id)
				self.shader_ids.append(shader_id)

			glLinkProgram(self.program_id)

			# check if linking was successful
			result = glGetProgramiv(self.program_id, GL_LINK_STATUS)
			info_log_len = glGetProgramiv(self.program_id, GL_INFO_LOG_LENGTH)
			if info_log_len:
				logmsg = glGetProgramInfoLog(self.program_id)
				print(logmsg)
				sys.exit(11)

		except Exception as err:
			raise err

	def __enter__(self):
		glUseProgram(self.program_id)
		return self

	def __exit__(self, type, value, traceback):
		glUseProgram(0)

	def __del__(self):
		for shader_id in self.shader_ids:
			glDetachShader(self.program_id, shader_id)
			glDeleteShader(shader_id)
		glDeleteProgram(self.program_id)

	def get_uniform_location(self, name):
		location = glGetUniformLocation(self.program_id, name)
		assert location>=0
		return location

	def set_uniform(self, name, value: [np.ndarray, int, glm.mat4x4]):
		location = self.get_uniform_location(name)

		if isinstance(value, np.ndarray):
			if value.shape == (4, 4): # matrix
				glUniformMatrix4fv(location, 1, False, value)
			elif value.shape == (3,):
				glUniform3f(location, value[0], value[1], value[2])
			else:
				raise NotImplementedError('uniform {} {}'.format(type(value), value.shape))

		elif isinstance(value, glm.mat4x4):
			glUniformMatrix4fv(location, 1, False, np.array(value))
		elif isinstance(value, glm.vec3):
			glUniform3f(location, value.x, value.y, value.z)

		elif isinstance(value, tuple):
			if len(value)==3:
				glUniform3f(location, value[0], value[1], value[2])

		elif isinstance(value, bool):
				glUniform1i(location, value)
		elif isinstance(value, int):
				glUniform1i(location, value)
		elif isinstance(value, float):
				glUniform1f(location, value)
		else:
			raise NotImplementedError(type(value))

	def get_attribute_location(self, attribute_name):
		# assert self.program_id == glGetIntegerv(GL_CURRENT_PROGRAM)
		return glGetAttribLocation(self.program_id, attribute_name)

	def set_attribute(self, name, attribute):
		location = self.get_attribute_location(name)

		self.vao.add_vertex_attribute()


from setuptools import setup, find_packages
import os

with open("README.md", encoding='utf-8') as f:
    long_description = f.read()

setup(
    name = 'ComplexAssembler',
    version = '1.0',
    description = "Macrocomplex builder",
    scripts = ['ComplexAssembler/assemble.py'],
    long_description = long_description,
    long_description_content_type = 'text/markdown',
    entry_points={
        'console_scripts': [
            'assemble = ComplexAssembler.assemble:main'
        ]
    },
    url = 'https://github.com/anasf97/SBI-Project',
    author = 'Eva Brigos Barril, Jordi Busoms Pratdesaba, Ana Sanchez Fernandez',
    classifiers =[
    "Programming Language :: Python :: 3",
    "License :: OSI Approved :: MIT License"
    ],
    packages = find_packages(),
    install_requires = ['biopython', 'matplotlib', 'numpy', 'scipy']
)


if __name__ == "__main__":

    amount = 0
    for i in range(1000):
        sum1 = sum([int(j) for j in list(str(i))])
        for k in range(1000):
            sum2 = sum([int(j) for j in list(str(k))])
            if sum1 == sum2:
                amount += 1

    print(amount)


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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

import json
import os
import os.path
import urlparse

import urlparse

from scrapy import log
from scrapy.conf import settings

class JsonFileMergerPipeline(object):
    def open_spider(self, spider):
        self.root = os.path.realpath(spider.settings["JSON_FILE_DIRECTORY"])
        self.part_skeleton = spider.settings["PART_SKELETON_FILE"]

    def process_item(self, item, spider):
        if "manufacturer" in item and item["manufacturer"]:
            fn = item["manufacturer"].replace(" ", "-") + "/" + item["name"].replace(" ", "-").replace("/", "-") + ".json"
        else:
            fn = "UnknownManufacturer/" + item["site"] + "/" + item["name"].replace(" ", "-").replace("/", "-") + ".json"
        full_fn = os.path.join(self.root, fn)
        d = os.path.dirname(full_fn)
        if not os.path.isdir(d):
            os.makedirs(d)

        while os.path.islink(full_fn):
          full_fn = os.path.realpath(full_fn)

        if "sku" in item and item["sku"] != "":
          sku_fn = os.path.join(self.root, "_skus/" + item["site"] + "/" + item["sku"].replace(" ", "-").replace("/", "-"))
          d = os.path.dirname(sku_fn)
          if not os.path.isdir(d):
              os.makedirs(d)
          if os.path.islink(sku_fn):
            new_full_fn = os.path.realpath(sku_fn)

            # Update the existing file to a link to the new one. This may lose info.
            if full_fn != new_full_fn:
              if os.path.isfile(full_fn):
                os.remove(full_fn)
              print(new_full_fn, full_fn)
              os.symlink(os.path.relpath(new_full_fn, os.path.dirname(full_fn)), full_fn)

            full_fn = new_full_fn
          else:
            # Create a sku link to our full_fn
            os.symlink(os.path.relpath(full_fn, os.path.dirname(sku_fn)), sku_fn)

        part_info = {}
        if os.path.isfile(full_fn):
          with open(full_fn, "r") as f:
            part_info = json.loads(f.read())
        else:
          with open(self.part_skeleton, "r") as f:
            part_info = json.loads(f.read())

            # Delete any example objects.
            for i, variant in enumerate(part_info["variants"]):
              if "_example" in variant:
                del part_info["variants"][i]

        # Update to version 2.
        if "version" not in part_info:
          part_info["version"] = 2
          # Allow for multiple categories for parts such as PDBs that are also OSDs.
          if part_info["category"]:
            part_info["categories"] = [part_info["category"]]
          else:
            part_info["categories"] = []
          del part_info["category"]

          part_info["weight"] = ""

          # Store store urls as variants rather than a list so we know more about each.
          part_info["variants"] = []
          if "urls" in part_info and "store" in part_info["urls"]:
            for store_url in part_info["urls"]["store"]:
              part_info["variants"].append({"url": store_url})
          del part_info["urls"]["store"]

        # Scraped parts now have weight and price but I'm not sure how we want
        # to store it here. So we drop it for now.
        if "name" not in part_info or not part_info["name"]:
            part_info["name"] = item["name"]
        if "manufacturer" in item and ("manufacturer" not in part_info or not part_info["manufacturer"]):
            part_info["manufacturer"] = item["manufacturer"]
        if "weight" in item and ("weight" not in part_info or not part_info["weight"]):
          part_info["weight"] = item["weight"]

        # Remove all variants from this url
        part_info["variants"] = [x for x in part_info["variants"] if x["url"] != item["variants"][0]["url"]]

        # Re-add all variants.
        for variant in item["variants"]:
          part_info["variants"].append(variant)

        # Sort by url so we can be somewhat more stable in order than last one is last.
        part_info["variants"].sort(key=lambda x: x["url"])

        # also catalog subpart ids
        # also catalog interchangeable parts
        with open(full_fn, "w") as f:
            f.write(json.dumps(part_info, indent=1, sort_keys=True, separators=(',', ': ')))
        return item