import math
import torch
import torch.nn.functional as F
from torch import nn
from torchvision import models
import torch.optim as optim
import numpy as np
from collections import OrderedDict
from torch.utils import model_zoo
from time import time

from torch.autograd.variable import Variable
class SEModule(nn.Module):
    def __init__(self, channels, reduction):
        super(SEModule, self).__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.fc1 = nn.Conv2d(channels, channels // reduction, kernel_size=1, padding=0)
        self.relu = nn.ReLU(inplace=True)
        self.fc2 = nn.Conv2d(channels // reduction, channels, kernel_size=1, padding=0)
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        module_input = x
        x = self.avg_pool(x)
        x = self.fc1(x)
        x = self.relu(x)
        x = self.fc2(x)
        x = self.sigmoid(x)
        return module_input * x

class SCSEBlock(nn.Module):
    def __init__(self, channel, reduction=16):
        super(SCSEBlock, self).__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)

        self.channel_excitation = nn.Sequential(nn.Linear(channel, int(channel // reduction)),
                                                nn.ReLU(inplace=True),
                                                nn.Linear(int(channel // reduction), channel),
                                                nn.Sigmoid())

        self.spatial_se = nn.Sequential(nn.Conv2d(channel, 1, kernel_size=1,
                                                  stride=1, padding=0, bias=False),
                                        nn.Sigmoid())

    def forward(self, x):
        bahs, chs, _, _ = x.size()

        # Returns a new tensor with the same data as the self tensor but of a different size.
        chn_se = self.avg_pool(x).view(bahs, chs)
        chn_se = self.channel_excitation(chn_se).view(bahs, chs, 1, 1)
        chn_se = torch.mul(x, chn_se)

        spa_se = self.spatial_se(x)
        spa_se = torch.mul(x, spa_se)
        return torch.add(chn_se, 1, spa_se)

class ConvBn2d(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), dilation=1):
        super(ConvBn2d, self).__init__()

        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding,
                              bias=False, dilation=dilation)
        self.bn = nn.BatchNorm2d(out_channels)
        #self.bn = SynchronizedBatchNorm2d(out_channels)

    def forward(self, z):
        x = self.conv(z)
        x = self.bn(x)
        return x
class _SelfAttentionBlock(nn.Module):
    '''
    The basic implementation for self-attention block/non-local block
    Input:
        N X C X H X W
    Parameters:
        in_channels       : the dimension of the input feature map
        key_channels      : the dimension after the key/query transform
        value_channels    : the dimension after the value transform
        scale             : choose the scale to downsample the input feature maps (save memory cost)
    Return:
        N X C X H X W
        position-aware context features.(w/o concate or add with the input)
    '''

    def __init__(self, in_channels, key_channels, value_channels, out_channels=None, scale=1):
        super(_SelfAttentionBlock, self).__init__()
        self.scale = scale
        self.in_channels = in_channels
        self.out_channels = out_channels
        self.key_channels = key_channels
        self.value_channels = value_channels
        if out_channels == None:
            self.out_channels = in_channels
        self.pool = nn.MaxPool2d(kernel_size=(scale, scale))
        self.f_key = nn.Sequential(
            nn.Conv2d(in_channels=self.in_channels, out_channels=self.key_channels,
                      kernel_size=1, stride=1, padding=0),
            nn.BatchNorm2d(self.key_channels),
            nn.ReLU()
        )
        self.f_query = self.f_key
        self.f_value = nn.Conv2d(in_channels=self.in_channels, out_channels=self.value_channels,
                                 kernel_size=1, stride=1, padding=0)
        self.W = nn.Conv2d(in_channels=self.value_channels, out_channels=self.out_channels,
                           kernel_size=1, stride=1, padding=0)
        nn.init.constant_(self.W.weight, 0)
        nn.init.constant_(self.W.bias, 0)

    def forward(self, x):
        batch_size, h, w = x.size(0), x.size(2), x.size(3)
        if self.scale > 1:
            x = self.pool(x)

        value = self.f_value(x).view(batch_size, self.value_channels, -1)
        value = value.permute(0, 2, 1)
        query = self.f_query(x).view(batch_size, self.key_channels, -1)
        query = query.permute(0, 2, 1)
        key = self.f_key(x).view(batch_size, self.key_channels, -1)

        sim_map = torch.matmul(query, key)
        sim_map = (self.key_channels ** -.5) * sim_map
        sim_map = F.softmax(sim_map, dim=-1)

        context = torch.matmul(sim_map, value)
        context = context.permute(0, 2, 1).contiguous()
        context = context.view(batch_size, self.value_channels, *x.size()[2:])
        context = self.W(context)
        if self.scale > 1:
            context = F.interpolate(input=context, size=(h, w), mode='bilinear', align_corners=True)
        return context

class SelfAttentionBlock2D(_SelfAttentionBlock):
    def __init__(self, in_channels, key_channels, value_channels, out_channels=None, scale=1):
        super(SelfAttentionBlock2D, self).__init__(in_channels,
                                                   key_channels,
                                                   value_channels,
                                                   out_channels,
                                                   scale)
class BaseOC_Context_Module(nn.Module):
    """
    Output only the context features.
    Parameters:
        in_features / out_features: the channels of the input / output feature maps.
        dropout: specify the dropout ratio
        fusion: We provide two different fusion method, "concat" or "add"
        size: we find that directly learn the attention weights on even 1/8 feature maps is hard.
    Return:
        features after "concat" or "add"
    """

    def __init__(self, in_channels, out_channels, key_channels, value_channels, dropout, sizes=([1])):
        super(BaseOC_Context_Module, self).__init__()
        self.stages = []
        self.stages = nn.ModuleList(
            [self._make_stage(in_channels, out_channels, key_channels, value_channels, size) for size in sizes])
        self.conv_bn_dropout = nn.Sequential(
            nn.Conv2d(in_channels, out_channels, kernel_size=1, padding=0),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(),
        )

    def _make_stage(self, in_channels, output_channels, key_channels, value_channels, size):
        return SelfAttentionBlock2D(in_channels,
                                    key_channels,
                                    value_channels,
                                    output_channels,
                                    size)

    def forward(self, feats):
        priors = [stage(feats) for stage in self.stages]
        context = priors[0]
        for i in range(1, len(priors)):
            context += priors[i]
        output = self.conv_bn_dropout(context)
        return output
class ASP_OC_Module(nn.Module):
    def __init__(self, features, out_features=512, dilations=(12, 24, 36)):
        super(ASP_OC_Module, self).__init__()
        self.context = nn.Sequential(nn.Conv2d(features, out_features, kernel_size=3, padding=1, dilation=1, bias=True),
                                     nn.BatchNorm2d(out_features),
                                     nn.ReLU(),
                                     BaseOC_Context_Module(in_channels=out_features, out_channels=out_features,
                                                           key_channels=out_features // 2, value_channels=out_features,
                                                           dropout=0, sizes=([2])))
        self.conv2 = nn.Sequential(nn.Conv2d(features, out_features, kernel_size=1, padding=0, dilation=1, bias=False),
                                   nn.BatchNorm2d(out_features),
                                   nn.ReLU(),)
        self.conv3 = nn.Sequential(
            nn.Conv2d(features, out_features, kernel_size=3, padding=dilations[0], dilation=dilations[0], bias=False),
            nn.BatchNorm2d(out_features),
            nn.ReLU(),)
        self.conv4 = nn.Sequential(
            nn.Conv2d(features, out_features, kernel_size=3, padding=dilations[1], dilation=dilations[1], bias=False),
            nn.BatchNorm2d(out_features),
            nn.ReLU(),)
        self.conv5 = nn.Sequential(
            nn.Conv2d(features, out_features, kernel_size=3, padding=dilations[2], dilation=dilations[2], bias=False),
            nn.BatchNorm2d(out_features),
            nn.ReLU(),)

        self.conv_bn_dropout = nn.Sequential(
            nn.Conv2d(out_features * 5, out_features, kernel_size=1, padding=0, dilation=1, bias=False),
            nn.BatchNorm2d(out_features),
            nn.ReLU(),
            nn.Dropout2d(0.1)
        )

    def _cat_each(self, feat1, feat2, feat3, feat4, feat5):
        assert (len(feat1) == len(feat2))
        z = []
        for i in range(len(feat1)):
            z.append(torch.cat((feat1[i], feat2[i], feat3[i], feat4[i], feat5[i]), 1))
        return z

    def forward(self, x):
        if isinstance(x, Variable):
            _, _, h, w = x.size()
        elif isinstance(x, tuple) or isinstance(x, list):
            _, _, h, w = x[0].size()
        else:
            raise RuntimeError('unknown input type')

        feat1 = self.context(x)
        feat2 = self.conv2(x)
        feat3 = self.conv3(x)
        feat4 = self.conv4(x)
        feat5 = self.conv5(x)

        if isinstance(x, Variable):
            out = torch.cat((feat1, feat2, feat3, feat4, feat5), 1)
        elif isinstance(x, tuple) or isinstance(x, list):
            out = self._cat_each(feat1, feat2, feat3, feat4, feat5)
        else:
            raise RuntimeError('unknown input type')

        output = self.conv_bn_dropout(out)
        return output

class SENet(nn.Module):
    def __init__(self, block, layers, groups, reduction, dropout_p=0.2,
                 inplanes=128, input_3x3=True, downsample_kernel_size=3,
                 downsample_padding=1, num_classes=None):

        super(SENet, self).__init__()
        self.inplanes = inplanes
        if input_3x3:
            layer0_modules = [
                ('conv1', nn.Conv2d(3, 64, 3, stride=2, padding=1,
                                    bias=False)),
                ('bn1', nn.BatchNorm2d(64)),
                ('relu1', nn.ReLU(inplace=True)),
                ('conv2', nn.Conv2d(64, 64, 3, stride=1, padding=1,
                                    bias=False)),
                ('bn2', nn.BatchNorm2d(64)),
                ('relu2', nn.ReLU(inplace=True)),
                ('conv3', nn.Conv2d(64, inplanes, 3, stride=1, padding=1,
                                    bias=False)),
                ('bn3', nn.BatchNorm2d(inplanes)),
                ('relu3', nn.ReLU(inplace=True)),
            ]
        else:
            layer0_modules = [
                ('conv1', nn.Conv2d(3, inplanes, kernel_size=7, stride=2,
                                    padding=3, bias=False)),
                ('bn1', nn.BatchNorm2d(inplanes)),
                ('relu1', nn.ReLU(inplace=True)),
            ]
        # To preserve compatibility with Caffe weights `ceil_mode=True`
        # is used instead of `padding=1`.
        # layer0_modules.append(('pool', nn.MaxPool2d(3, stride=2,
        #                                             ceil_mode=True)))
        self.layer0 = nn.Sequential(OrderedDict(layer0_modules))
        self.layer1 = self._make_layer(
            block,
            planes=64,
            blocks=layers[0],
            groups=groups,
            reduction=reduction,
            downsample_kernel_size=1,
            downsample_padding=0
        )
        self.layer2 = self._make_layer(
            block,
            planes=128,
            blocks=layers[1],
            stride=2,
            groups=groups,
            reduction=reduction,
            downsample_kernel_size=downsample_kernel_size,
            downsample_padding=downsample_padding
        )
        self.layer3 = self._make_layer(
            block,
            planes=256,
            blocks=layers[2],
            stride=2,
            groups=groups,
            reduction=reduction,
            downsample_kernel_size=downsample_kernel_size,
            downsample_padding=downsample_padding
        )
        self.layer4 = self._make_layer(
            block,
            planes=512,
            blocks=layers[3],
            stride=2,
            groups=groups,
            reduction=reduction,
            downsample_kernel_size=downsample_kernel_size,
            downsample_padding=downsample_padding
        )
        self.avg_pool = nn.AvgPool2d(7, stride=1)
        self.dropout = nn.Dropout(dropout_p) if dropout_p is not None else None
        # if num_classes:
        #     self.last_linear = nn.Linear(512 * block.expansion, num_classes)

    def _make_layer(self, block, planes, blocks, groups, reduction, stride=1,
                    downsample_kernel_size=1, downsample_padding=0):
        downsample = None
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                nn.Conv2d(self.inplanes, planes * block.expansion,
                          kernel_size=downsample_kernel_size, stride=stride,
                          padding=downsample_padding, bias=False),
                nn.BatchNorm2d(planes * block.expansion),
            )

        layers = []
        layers.append(block(self.inplanes, planes, groups, reduction, stride,
                            downsample))
        self.inplanes = planes * block.expansion
        for i in range(1, blocks):
            layers.append(block(self.inplanes, planes, groups, reduction))

        return nn.Sequential(*layers)

class Bottleneck(nn.Module):
    """
    Base class for bottlenecks that implements `forward()` method.
    """

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)

        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out = self.se_module(out) + residual
        out = self.relu(out)

        return out
class SEResNeXtBottleneck(Bottleneck):
    """
    ResNeXt bottleneck type C with a Squeeze-and-Excitation module.
    """
    expansion = 4

    def __init__(self, inplanes, planes, groups, reduction, stride=1,
                 downsample=None, base_width=4):
        super(SEResNeXtBottleneck, self).__init__()
        width = int(math.floor(planes * (base_width / 64.)) * groups)
        self.conv1 = nn.Conv2d(inplanes, width, kernel_size=1, bias=False,
                               stride=1)
        self.bn1 = nn.BatchNorm2d(width)
        self.conv2 = nn.Conv2d(width, width, kernel_size=3, stride=stride,
                               padding=1, groups=groups, bias=False)
        self.bn2 = nn.BatchNorm2d(width)
        self.conv3 = nn.Conv2d(width, planes * 4, kernel_size=1, bias=False)
        self.bn3 = nn.BatchNorm2d(planes * 4)
        self.relu = nn.ReLU(inplace=True)
        self.se_module = SEModule(planes * 4, reduction=reduction)
        self.downsample = downsample
        self.stride = stride

def se_resnext101_32x4d(pretrained=True):
    model = SENet(SEResNeXtBottleneck, [3, 4, 23, 3], groups=32, reduction=16,
                  dropout_p=None, inplanes=64, input_3x3=False,
                  downsample_kernel_size=1, downsample_padding=0)
    if pretrained:
        url = 'http://data.lip6.fr/cadene/pretrainedmodels/se_resnext101_32x4d-3b2fe3d8.pth'
        pretrained_dict = model_zoo.load_url(url)
        model_dict = model.state_dict()
        #pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}
        for key in pretrained_dict.keys():
            if 'last_linear' in key:
                print(key)
                continue
            model_dict[key] = pretrained_dict[key]
        model.load_state_dict(model_dict)
        print("-----pretrain success_____")
    return model

class Decoder(nn.Module):
    def __init__(self, in_channels, channels, out_channels ,OC=False,dilation=(4,8,12)):
        super(Decoder, self).__init__()
        self.oc=OC
        self.conv1 =  ConvBn2d(in_channels,  channels, kernel_size=3, padding=1)
        self.conv2 =  ConvBn2d(channels, out_channels, kernel_size=3, padding=1)
        # self.conv1 = ConvBn2dV2(in_channels, channels, kernel_size=3, padding=1)
        # self.conv2 = ConvBn2dV2(channels, out_channels, kernel_size=3, padding=1)
        self.context = nn.Sequential(
                ASP_OC_Module(out_channels,out_channels,dilations=dilation)
                )
        # self.context = nn.Sequential(
        #     nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1),
        #     nn.BatchNorm2d(out_channels),
        #     nn.ReLU(),
        #     BaseOC_Module(in_channels=out_channels, out_channels=out_channels, key_channels=out_channels//2, value_channels=out_channels-out_channels//2,
        #                   dropout=0.05, sizes=([1]))
        # )
        self.scse_gate = SCSEBlock(out_channels)

    def forward(self, x):

        x = F.relu(self.conv1(x), inplace=True)
        x = F.relu(self.conv2(x), inplace=True)
        if self.oc:
            y = self.context(x)
        # x= self.conv1(F.elu(x,inplace=True))
        # x = self.conv2(F.elu(x, inplace=True))
        x = self.scse_gate(x)
        if self.oc:
            return torch.cat((x,y),1)
        else:
            return x

class Unet_scSE_hyper(nn.Module):
    # def load_pretrain(self, pretrain_file):
    #     pretrain_dict = torch.load(pretrain_file)
    #     state_dict = {}
    #     keys = list(pretrain_dict.keys())
    #     for key in keys:
    #         if 'last_layer' in key:
    #             continue
    #         state_dict[(key)] = pretrain_dict[key]
    #     self.encoder.load_state_dict(state_dict)

    def __init__(self,class_num = 17,dilation=False):
        super().__init__()
        self.dilation = dilation
        self.encoder =se_resnext101_32x4d()
        self.encoder1 = self.encoder.layer0
        #self.encoder1 = self.encoder.conv1
        self.encoder2 = self.encoder.layer1  # 256
        self.encoder3 = self.encoder.layer2  # 512
        self.encoder4 = self.encoder.layer3  # 1024
        self.encoder5 = self.encoder.layer4  # 2048
        self.center = nn.Sequential(
            ConvBn2d(2048, 1024, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            ConvBn2d(1024, 512, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=2, stride=2)
        )
        if self.dilation:
            self.center1 = nn.Sequential(
                ConvBn2d(512, 512, kernel_size=3, padding=2, dilation=2),
                nn.ReLU(inplace=True)
            )
            self.center2 = nn.Sequential(
                ConvBn2d(512, 512, kernel_size=3, padding=4, dilation=4),
                nn.ReLU(inplace=True)
            )
        self.decoder5 = Decoder(2048 + 512, 512, 64,OC=True,dilation=(2,4,6))
        self.decoder4 = Decoder(128 + 1024, 256, 64,OC=True,dilation=(4,8,12))
        self.decoder3 = Decoder(128 + 512, 128, 64)
        self.decoder2 = Decoder(64 + 256, 64, 64)
        self.decoder1 = Decoder(64, 32, 64)

        self.logit = nn.Sequential(
            nn.Conv2d(64*7, 64, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(64,class_num , kernel_size=1, padding=0),
        )

    def forward(self, x):
        #print('x',x.size())
        e1 = self.encoder1(x)  #; print('e1',e1.size())
        e2 = self.encoder2(e1)   #; print('e2',e2.size())
        e3 = self.encoder3(e2)   #; print('e3',e3.size())
        e4 = self.encoder4(e3)   #; print('e4',e4.size())
        e5 = self.encoder5(e4)   #; print('e5',e5.size())
        #e1,e2,e3,e4,e5 = self.encoder(x)
        f = self.center(e5)  #; print('center',f.size())
        if self.dilation:
            f1= self.center1(f)#; print('center',f1.size())
            f2=self.center2(f1)#; print('center',f2.size())
            # f3=self.center3(f2); print('center',f3.size())
            # f4=self.center4(f3); print('center',f4.size())
            #f5=self.center5(f4)
            f = torch.add(f,1,f1)
            f = torch.add(f,1,f2)
        # f=torch.cat((
        #     f,
        #     f1,
            # f2,
            # f3,
            # f4,
        # ),1)
        f = F.interpolate(f, scale_factor=2, mode='bilinear', align_corners=True)
        d5 = self.decoder5(torch.cat([f, e5], 1))   #; print('d5',d5.size())
        d5 = F.interpolate(d5, scale_factor=2, mode='bilinear', align_corners=True)
        d4 = self.decoder4(torch.cat([d5, e4], 1))   #; print('d4',d4.size())
        d4 = F.interpolate(d4, scale_factor=2, mode='bilinear', align_corners=True)
        d3 = self.decoder3(torch.cat([d4, e3], 1))   #; print('d3',d3.size())
        d3 = F.interpolate(d3, scale_factor=2, mode='bilinear', align_corners=True)
        d2 = self.decoder2(torch.cat([d3, e2], 1))   #; print('d2',d2.size())
        d2 = F.interpolate(d2, scale_factor=2, mode='bilinear', align_corners=True)
        d1 = self.decoder1(d2)   #; print('d1',d1.size())
        f = torch.cat((
            d1,
            F.interpolate(d2, scale_factor=1, mode='bilinear', align_corners=False),
            F.interpolate(d3, scale_factor=2, mode='bilinear', align_corners=False),
            F.interpolate(d4, scale_factor=4, mode='bilinear', align_corners=False),
            F.interpolate(d5, scale_factor=8, mode='bilinear', align_corners=False)
        ), 1)
        f = F.dropout2d(f, p=0.20)
        logit = self.logit(f)   #; print('logit',logit.size())
        return logit


from django.urls import path
from . import views

urlpatterns = [
    # var_route
    path('test/<value>/', views.test),

    # 입력받고 처리결과 보여주기
    path('throw/', views.throw, name='throw'),
    path('catch/', views.catch, name='catch'),
]


# Write a Python program to find the list with maximum and minimum length.
# Original list:
# [[0], [1, 3], [5, 7], [9, 11], [13, 15, 17]]
# List with maximum length of lists:
# (3, [13, 15, 17])
# List with minimum length of lists:
# (1, [0])

a=[[0], [1, 3], [5, 7], [9, 11], [13, 15, 17]]
i=0
max=a[0]
min=a[0]
c=0
while i<len(a):
    j=0
    while j<len(a[i]):
        if a[i]<min:
            min=a[i]
        else:
            max=a[i]
        j+=1
    i+=1
print((len(max),max))
print((len(min),min))


import win32com.client

# Initialize Outlook app:
outlook = win32com.client.Dispatch('outlook.application')

# In outlook, email, meeting invite, calendar, appointment etc... are all considered as Item object
# Create Outlook email object:
mail = outlook.CreateItem(0)

mail.To = 'somebody@company.com'
mail.Subject = 'Sample Email'
mail.Body = "This is the normal body"

# Additional Options:
#mail.HTMLBody = '
This is HTML Body
'
#mail.Attachments.Add('c:\\sample.xlsx')
#mail.Attachments.Add('c:\\sample2.xlsx')
#mail.CC = 'somebody@company.com'

if __name__ == '__main__':
    mail.Send()


"""
easy

Write a function that takes in a Binary Tree and returns a list of its
branch sums ordered from leftmost branch sum to rightmost branch sum.

A branch sum is the sum of all values in a Binary Tree branch.
A Binary Tree branch is a path of nodes in a tree that starts at the root node and ends at any leaf node.

Each BinaryTree node has an integer value, a left child node, and a right child node.
Children nodes can either be BinaryTree nodes themselves or None / null.

Sample Input
tree =     1
        /     \
       2       3
     /   \    /  \
    4     5  6    7
  /   \  /
 8    9 10
Sample Output
[15, 16, 18, 10, 11]
// 15 == 1 + 2 + 4 + 8
// 16 == 1 + 2 + 4 + 9
// 18 == 1 + 2 + 5 + 10
// 10 == 1 + 3 + 6
// 11 == 1 + 3 + 7

Solution 1
Time Complexity: O(n), space complexity: O(n) - n is the nodes in the tree
Strategy:
Solve using depth-first search.
Base case: when left and right nodes are both None,
add the current value to the running sum, then append the sum to the output array and return it.
Pass through the output array and running sum to the left and right nodes if they are not None.
Return the output array at the end.
"""
import unittest

class BinaryTree:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

def branchSums(root):
    output = []
    dfs(root, 0, output)
    return output

def dfs(node, running_sum, output):
    running_sum += node.value
    if node.left is None and node.right is None:
        output.append(running_sum)
        return

    if node.left is not None:
        dfs(node.left, running_sum, output)
    if node.right is not None:
        dfs(node.right, running_sum, output)

class BinaryTree(BinaryTree):
    def insert(self, values, i=0):
        if i >= len(values):
            return
        queue = [self]
        while len(queue) > 0:
            current = queue.pop(0)
            if current.left is None:
                current.left = BinaryTree(values[i])
                break
            queue.append(current.left)
            if current.right is None:
                current.right = BinaryTree(values[i])
                break
            queue.append(current.right)
        self.insert(values, i + 1)
        return self

class TestProgram(unittest.TestCase):
    def test_1(self):
        tree = BinaryTree(1).insert([2, 3, 4, 5, 6, 7, 8, 9, 10])
        self.assertEqual(branchSums(tree), [15, 16, 18, 10, 11])


import wx
import eos.db
from logbook import Logger
pyfalog = Logger(__name__)

class FitChangeImplantLocation(wx.Command):
    def __init__(self, fitID, source):
        wx.Command.__init__(self, True, "Drone add")
        self.fitID = fitID
        self.source = source
        self.old_source = None

    def Do(self):
        pyfalog.debug("Toggling implant source for fit ID: {0}", self.fitID)
        fit = eos.db.getFit(self.fitID)
        self.old_source = fit.implantSource
        fit.implantSource = self.source
        eos.db.commit()
        return True

    def Undo(self):
        cmd = FitChangeImplantLocation(self.fitID, self.old_source)
        return cmd.Do()


'''
逻辑回归练习
1. 载入数据
2. 数据处理，图集降维，特征规范化
3. 随机初始化参数
4. 计算代价函数【正向传播】，并计算梯度【反向传播】，
5. 迭代更新参数 【梯度下降】
6. 模型评估
激活函数：sigmoid函数
算法的评估：留一法，k折法，自助法
梯度下降： 小批次梯度下降
使用正则化方法
采用训练集，交叉验证集，测试集的划分数据方式
'''
import numpy as np
import matplotlib.pyplot as plt
import h5py   #是与H5文件中存储的数据集进行交互的常用软件包
from lr_utils import load_dataset
import random
#加载数据集和测试集
train_set_x_orig , train_set_y , test_set_x_orig , test_set_y , classes  = load_dataset()

m_train  = train_set_y.shape[1]  #训练集的规模，图片数
m_test  = test_set_y.shape[1]    #测试集的规模
num_px = train_set_x_orig.shape[1]   #图片的规模，大小均为64*64
"""
#现在看一看我们加载的东西的具体情况
print ("训练集的数量: m_train = " + str(m_train))
print ("测试集的数量 : m_test = " + str(m_test))
print ("每张图片的宽/高 : num_px = " + str(num_px))
print ("每张图片的大小 : (" + str(num_px) + ", " + str(num_px) + ", 3)")
print ("训练集_图片的维数 : " + str(train_set_x_orig.shape))
print ("训练集_标签的维数 : " + str(train_set_y.shape))
print ("测试集_图片的维数: " + str(test_set_x_orig.shape))
print ("测试集_标签的维数: " + str(test_set_y.shape))
"""
#要把numpy数组(a,b,c,d)规模转化为（b*c*d,a),即使用reshape的-1参数，也就是从维数和其他参数中推出剩余参数
train_set_x_flatten  = train_set_x_orig.reshape((train_set_x_orig.shape[0],-1)).T
test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0],-1).T
#print('降维之后的测试集：'+str(test_set_x_flatten.shape))

#标准化数据集，特征规范化归一化处理,因为图像数据都是0到255的数据，所以除以255让数据在0到1之内
train_set_x = train_set_x_flatten[:,0:150] / 255
verify_set_x = train_set_x_flatten[:,150:209]/255
test_set_x = test_set_x_flatten / 255

verify_set_y  = train_set_y[:,150:209]
train_set_y  = train_set_y[:,0:150]
#计算激活函数 ，sigmond函数
def sigmoid(z):
    '''参数：z-任何大小的标量或者numpy数组。实际上z= W.T*x+b
    返回值：s = sigmoid(z)'''
    s = 1 / ( 1+ np.exp(-z))
    return s

'''
#测试激活函数
a = np.array([[0,1,9.2,-9.2,100]])
print('sigmoid(a):'+str(sigmoid(a)))
print('log(z):'+str(np.log(sigmoid(a))))
exit()
'''
#初始化参数
def initialize_with_zeros(dim):
    '''此函数为w创建一个维度为（dim,1）的随机向量，并把b初始化为1
    参数： dim  -  我们想要的w矢量的大小（或者这种情况下的参数数量）
    返回：  w-维度为（dim，1）的随机向量，b-初始化的标量，对应于偏差'''
    w = np.random.rand(dim, 1)*0.01+0.0001
    b = 0
    # 使用断言来确保我要的数据是正确的
    assert (w.shape == (dim, 1))  # w的维度是(dim,1)
    assert (isinstance(b, float) or isinstance(b, int))  # b的类型是float或者是int

    return (w,b)

#前向传播和后向传播，计算代价函数和梯度
def propagate(w,b,X,Y,Lambda):
    '''实现前向和后向传播的成本函数及其梯度
    参数：
    w  - 权重，大小不等的数组（num_px * num_px * 3 ,1）
    b  - 偏差，一个标量
    X  - 矩阵类型为（num_px*num_px*3,训练数量）
    Y  - 真正的标签矢量，即监督的正确答案
    Lambda - 正则化系数，是一个超参数
    返回：cost: 逻辑回归的负对数似然成本
          dw :  相对于w的损失梯度
          db：  相对于b的损失梯度'''
    #使用小批次梯度下降,批次为32
    m  = 32
    random_index = random.randint(0,X.shape[1]-m)
    x =X[:,random_index:random_index+m]
    y =Y[:,random_index:random_index+m]
    #正向传播
    A = sigmoid(np.dot(w.T,x)+b) #计算激活函数值，即y
    cost  = (- 1 / m) * np.sum(y * np.log( A )+ ( 1 - y ) *(np.log( 1 - A ))) #计算代价函数值
    #添加正则化项
    cost += (Lambda/(2*m))*np.sum(w * w)
    #反向传播
    #print(x.shape,y.shape,w.shape)
    dw = (1 / m) * np.dot(x,( A - y ).T) + (Lambda / m)* w
    db = (1 / m) * np.sum( A - y)

    # 使用断言确保我的数据是正确的
    assert (dw.shape == w.shape)
    assert (db.dtype == float)
    cost = np.squeeze(cost) #降维，变成数
    assert (cost.shape == ())

    #创建字典，保存梯度
    grads  = {'dw':dw,'db':db}

    return (grads ,cost)
'''
#测试传播过程
print('===========test  propagate ===============')
#初始化参数
w,b,X,Y = np.array([[1],[2]]),2,np.array([[1,2],[3,4]]),np.array([[1,0]])
#2个样本，2个特征值
grads ,cost  =  propagate(w,b,X,Y)
print('dw='+str(grads['dw']))
print('db='+str(grads['db']))
print('cost='+str(cost))
'''

#更新参数，梯度下降
def optimize(w,b,X,Y,Lambda, num_iterations, learning_rate, print_cost =False):
    '''
    此函数通过运行梯度下降算法来优化w和b
    参数：
      w  -权重，和样本特征值规模相当
      b  -偏差，一个标量
      X  - 维度为（num_px*num_px*3,训练数据的数量）的数组
      Y  - 真正的’标签’矢量
      Lambda - 正则化系数
      num_iterations  -优化循环的迭代次数
      learning_rate    -梯度下降更新的学习率
      print_cost   -每一千步打印一次损失值，绘图

    返回：
      params   - 包含权重w和偏差b的字典
      grads    - 包含权重w和偏差下降梯度的字典
      costs    - 成本-优化期计算的所有成本列表，用于绘制学习曲线
    '''
    costs = []
    for i in range(num_iterations):
        grads,cost =propagate(w,b,X,Y,Lambda)

        dw = grads['dw']
        db = grads['db']
        #更新参数
        w = w - learning_rate * dw
        b = b - learning_rate * db

        #记录成本
        if i%1000 == 0:
            costs.append(cost)
        #打印成本数据
        if (print_cost) and (i%1000 == 0) :
            print('迭代的次数：%i,误差值：%f'%(i,cost))
        #用字典记录参数和梯度
        params  ={'w':w,'b':b}
        grads   = {'dw':dw,'db':db}

    return (params,grads,costs)
'''
#测试optimize
print("====================测试optimize====================")
w, b, X, Y = np.array([[1], [2]]), 2, np.array([[1,2], [3,4]]), np.array([[1, 0]])
params , grads , costs = optimize(w , b , X , Y , num_iterations=100 , learning_rate = 0.009 , print_cost = False)
print ("w = " + str(params["w"]))
print ("b = " + str(params["b"]))
print ("dw = " + str(grads["dw"]))
print ("db = " + str(grads["db"]))
'''

#输出预测值
def predict(w,b,X):
    '''
    使用学习逻辑回归参数预测 标签
    :param w:  权重
    :param b:  偏差
    :param X:   训练集数据
    :return:   Y_prediction 包含X中所有图片的所有预测
    '''
    m  = X.shape[1]  #图片的数量
    Y_prediction  = np.zeros((1,m))
    w = w.reshape(X.shape[0],1)

    #记预测猫在图片中出现的概率
    A = sigmoid(np.dot(w.T ,X)+b)
    for i in range(A.shape[1]):
        if A[0,i] > 0.5:
            Y_prediction[0,i] = 1
        else:
            Y_prediction[0,i] = 0
    assert(Y_prediction.shape == (1,m))

    return Y_prediction
'''
#测试predict
print("====================测试predict====================")
w, b, X, Y = np.array([[1], [2]]), 2, np.array([[1,2], [3,4]]), np.array([[1, 0]])
print("predictions = " + str(predict(w, b, X)))'''

def model(X_train,Y_train,X_test,Y_test,X_verify,Y_verify, learning_rate,Lambda,num_iterations=2000,print_cost =False):
    '''
    通过调用之间实现的函数来构建逻辑回归模型
    :param X_train: 训练集
    :param Y_train: 训练标签集
    :param X_test: 测试集
    :param Y_test:  测试标签集
    :param num_iterations: 迭代次数，超参数
    :param learning_rate:   学习率，超参数
    :param print_cost:   设置为true以每100次迭代打印成本
    :return: d--包含有关模型信息的字典
    '''
    #初始化参数
    w ,b =  initialize_with_zeros(X_train.shape[0])
    #通过学习得到参数，梯度和损失
    parameters , grads , costs = optimize(w,b,X_train,Y_train,Lambda,
                                          num_iterations,learning_rate,print_cost)

    #从字典参数中检索参数w和b
    w,b = parameters['w'],parameters['b']

    #预测测试集/训练集的例子
    Y_prediction_test = predict(w, b, X_test)
    Y_prediction_verify = predict(w,b,X_verify)
    Y_prediction_train = predict(w, b, X_train)
    # 打印训练后的准确性
    print("训练集准确性：", format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100), "%")
    print("交叉验证集准确性：", format(100 - np.mean(np.abs(Y_prediction_verify - Y_verify)) * 100), "%")
    print("测试集准确性：", format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100), "%")
    correct = 1 - np.mean(np.abs(Y_prediction_verify - Y_verify))

    d = {
        "costs": costs,
        "Y_prediction_test": Y_prediction_test,
        "Y_prediciton_train": Y_prediction_train,
        "w": w,
        "b": b,
        "learning_rate": learning_rate,
        "num_iterations": num_iterations,
         "correct":correct}
    return d
print("====================测试model====================")

Lambda =12
d = model(train_set_x, train_set_y, test_set_x, test_set_y,verify_set_x,verify_set_y,learning_rate=0.007,
                   Lambda=0.5, num_iterations = 20000,  print_cost = True)

#绘制图
costs = np.squeeze(d['costs'])
plt.plot(costs)
plt.ylabel('cost')
plt.xlabel('iterations (per thousands)')
plt.title("Learning rate =" + str(d["learning_rate"])+"\nlambda ="+str(Lambda))
plt.show()


"""Manejo de excepciones"""

"""Para controloar el error de división entre cero y el tipo de datos"""

try:
    #val1 = 100/0
    suma = 1000 + "Hola Pythonistas!"
except ZeroDivisionError:
    print("No es posible una división entre cero!!")
except TypeError:
    print("No es posible sumar tipo de dato entero y tipo string")


## time input as String
## hours
## minutes
## seconds
time = input('Enter time in 12 hour formate: ')
hours = int(time[0:2])
minutes = int(time[3:5])
seconds = int(time[6:8])
AM_PM = time[8:]

if AM_PM == 'PM' and hours != 12:
    hours+=12
elif AM_PM == 'AM' and hours == 12:
    hours = 0

#     formate string
print('{:02}:{:02}:{:02}'.format(hours,minutes,seconds))


#!/usr/bin/env python2.7

import zmq
import time
import argparse

def main(pport, sport):
        context = zmq.Context()
        publisher = context.socket(zmq.PUB)
        publisher.bind("tcp://*:%s" % sport)

        subscriber = context.socket(zmq.SUB)
        subscriber.bind("tcp://*:%s" % pport)
        subscriber.setsockopt(zmq.SUBSCRIBE, "")

        zmq.device(zmq.FORWARDER, subscriber, publisher)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-p", help="Broker publish socket", required=True, type=int)
    parser.add_argument("-s", help="Broker subscribe socket", required=True, type=int)
    args = parser.parse_args()
    print("Launched broker with publish port %d and subscriber port %d" % (args.p, args.s))
    main(args.p, args.s)


"""
Authors: Daniel Dantas, Gustavo Amarante, Gustavo Soares, Wilson Felicio
https://github.com/Finance-Hub/FinanceHub/blob/master/bloomberg/getbbgdata.py

https://www.bloomberg.com/professional/support/api-library/
Python -m pip install --index-url=https://bcms.bloomberg.com/pip/simple blpapi

"""

import pandas as pd
from src.letscode.Bloomberg.wrapperbloom import BBG # apenas a classe

start_date = '30-mar-2015'
end_date = pd.to_datetime('today')

bbg = BBG()

# Grabs tickers and fields
df = bbg.fetch_series(securities=['BRL Curncy', 'DXY Index'],
                      fields=['PX_LAST', 'VOLATILITY_90D'],
                      startdate=start_date,
                      enddate=end_date)
print(df)

# Grabs cashflow payments of corporate bonds
df = bbg.fetch_cash_flow('EI1436001 Govt', pd.to_datetime('03-jul-2017'))
print(df)

# Grabs weights of the components of an index
df = bbg.fetch_index_weights(index_name='IBOV Index', ref_date=pd.to_datetime('03-jul-2017'))
print(df)
print(df.sum())

# Grabs all the contracts from a generic series
futures_list = bbg.fetch_futures_list(generic_ticker='TY1 Comdty')
print(futures_list)

# grabs the first notice date for each contract
df_fn = bbg.fetch_contract_parameter(securities=futures_list, field='FUT_NOTICE_FIRST')
print(df_fn)

# fetches fields with bulk data
df_bulk = bbg.fetch_bulk_data(index_name='AAPL US Equity', field='PG_REVENUE', ref_date=start_date)
print(df_bulk)

# fetches historical dividends
df_div = bbg.fetch_dividends('AAPL US Equity', end_date)

# Bloomberg data point
bdp = BBG.fetch_contract_parameter('IBM US Equity', 'PX_LAST')
bdp.head()

# Bloomberg data history
dados = BBG.fetch_series("IBOV INDEX", ["PX_LAST", 'PX_OPEN'], "2019-11-01","2019-11-30")
dados.head()

# Outro modo de plotar os dados, usando orientação ao objeto dados
dados.plot()


from classes.FachadaSegurancaBDParent import FachadaSegurancaBDParent

class FachadaSegurancaBD(FachadaSegurancaBDParent):
    def __init__(self, sBanco):
        self.pConexao = FachadaSegurancaBDParent(sBanco=sBanco)

    def alteraSenhaUsuario(self, oUsuario, sSenha, voTransacao, sBanco):
        oUsuarioBD = self.inicializaUsuarioBD(sBanco)
        bResultado = oUsuarioBD.alteraSenha(oUsuario,sSenha)
        if bResultado and voTransacao != None and hasattr(voTransacao,'__iter__'):
            for oTransacao in voTransacao:
                 if oTransacao != None and isinstance(oTransacao, object):
                     if not self.insereTransacao(oTransacao, sBanco):
                         return False
        if bResultado and voTransacao != None and not hasattr(voTransacao,'__iter__'):
            if not self.insereTransacao(voTransacao, sBanco):
                return False
        return bResultado

    def recuperaTipoTransacaoPorDescricaoCategoria(self, sDescricao, sTransacao, sBanco):
        oTipoTransacaoBD = self.inicializaTipoTransacaoBD(sBanco)
        oCategoriaTipoTransacaoBD = self.inicializaCategoriaTipoTransacaoBD(sBanco)
        oFachadaSeguranca = FachadaSegurancaBD(sBanco)
        vWhereCategoriaTipoTransacao = ["descricao = '{}'".format(sDescricao)]
        voCategoriaTipoTransacao = oFachadaSeguranca.recuperaTodosCategoriaTipoTransacao(sBanco,vWhereCategoriaTipoTransacao)
        if voCategoriaTipoTransacao != None and len(voCategoriaTipoTransacao) == 1:
            oCategoriaTipoTransacao = voCategoriaTipoTransacao[0]
            if isinstance(oCategoriaTipoTransacao, object):
                vWhereTipoTransacao = ["id_categoria_tipo_transacao = {}".format(oCategoriaTipoTransacao.getId()),
                                       "transacao = '{}'".format(sTransacao)]
                sOrderTipoTransacao = ""
                voTipoTransacao = oTipoTransacaoBD.recuperaTodos(vWhereTipoTransacao, sOrderTipoTransacao)
                if len(voTipoTransacao) == 1:
                    oTipoTransacao = voTipoTransacao[0]
                    return oTipoTransacao.getId()
        return False

    def desativaPermissaoPorGrupoUsuario(self,nIdGrupoUsuario, sBanco):
        oPermissaoBD = self.inicializaPermissaoBD(sBanco)
        bResultado = oPermissaoBD.desativaPorGrupoUsuario(nIdGrupoUsuario)
        return bResultado

    def desativaPermissaoPorTipoTransacao(self,nIdTipoTransacao, sBanco):
        oPermissaoBD = self.inicializaPermissaoBD(sBanco)
        bResultado = oPermissaoBD.desativaPorTipoTransacao(nIdTipoTransacao)
        return bResultado

    def verificaPermissao(self,nIdTipoTransacao, vPermissao, sBanco):
        oPermissaoBD = self.inicializaPermissaoBD(sBanco)
        bResultado = False
        if len(vPermissao) > 0:
            for oPermissao in vPermissao:
                if oPermissao.getIdTipoTransacao() == nIdTipoTransacao:
                    bResultado = True
            return bResultado
        return False

    def desativaTipoTransacaoPorCategoria(self,nIdCategoria,sBanco):
        oTipoTransacaoBD = self.inicializaTipoTransacaoBD(sBanco)
        bResultado = oTipoTransacaoBD.desativaPorCategoria(nIdCategoria)
        return bResultado


from policyengine_us.model_api import *

class is_person_demographic_tanf_eligible(Variable):
    value_type = bool
    entity = Person
    definition_period = YEAR
    label = "Person-level eligiblity for TANF based on age, pregnancy, etc."
    documentation = "Whether a person in a family applying for the Temporary Assistance for Needy Families program meets demographic requirements."

    def formula(person, period, parameters):
        child_0_17 = person("is_child", period)
        is_18 = person("age", period) == 18
        full_time_student = person("is_full_time_student", period)
        school_enrolled_18_year_old = full_time_student & is_18
        pregnant = person("is_pregnant", period)
        return child_0_17 | school_enrolled_18_year_old | pregnant


"""add_looker_ergo_and_looker_prox_roles

Revision ID: c813aeef3940
Revises: 7362f276939c
Create Date: 2021-01-13 16:03:30.128454

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = "c813aeef3940"
down_revision = "7362f276939c"
branch_labels = None
depends_on = None

def upgrade():
    op.execute(
        """
    INSERT INTO pipeline.casbin_rule
        (ptype, v0, v1, v2)
    VALUES
        ("p", "looker_ergo", "looker_ergo", "get"),
        ("p", "looker_ergo", "looker_ergo", "post"),
        ("p", "looker_ergo", "looker_ergo", "put"),
        ("p", "looker_ergo", "looker_ergo", "delete"),
        ("p", "looker_prox", "looker_prox", "get"),
        ("p", "looker_prox", "looker_prox", "post"),
        ("p", "looker_prox", "looker_prox", "put"),
        ("p", "looker_prox", "looker_prox", "delete");

    """
    )

def downgrade():
    op.execute(
        """
    DELETE FROM pipeline.casbin_rule WHERE v0='looker_ergo' AND v1='looker_ergo';
    DELETE FROM pipeline.casbin_rule WHERE v0='looker_prox' AND v1='looker_prox';

    """
    )


import sys

input = sys.stdin.readline

graph = [list(map(int, input().split())) for _ in range(19)]
direction = [(-1, -1), (-1, 0), (-1, 1), (0, -1)]

def valid(x, y, num):
    global graph
    return 0 <= x < 19 and 0 <= y < 19 and graph[x][y] == num

def check(x, y, dx, dy):
    global graph
    count = 1
    num = graph[x][y]
    while valid(x + dx, y + dy, num):
        x += dx
        y += dy
        count += 1
    return count

for x in range(19):
    for y in range(19):
        if graph[x][y] != 0:
            for dx, dy in direction:
                count = 1

                if valid(x + dx, y + dy, graph[x][y]):
                    count += check(x + dx, y + dy, dx, dy)

                if valid(x - dx, y - dy, graph[x][y]):
                    count += check(x - dx, y - dy, -dx, -dy)

                if count == 5:
                    if dy == 1:
                        dx = -dx
                        dy = -dy
                    elif dy == 0 and dx == 1:
                        dx = -dx
                    num = graph[x][y]
                    while valid(x + dx, y + dy, num):
                        x += dx
                        y += dy
                    print(num)
                    print(x + 1, y + 1)
                    exit()

print(0)


import matplotlib.pyplot as plt
import math
import statistics
# import matplotlib.pyplot as plt
import numpy as np
from matplotlib import colors
# from matplotlib.ticker import PercentFormatter

# f=open('GSE79578_bulkRNAseq.txt')
# new_f=open('GSE79578_bulkRNAseq_96h.bed','a')
# # for line in f.readlines(3):
# #     l=line.strip().split()
# # #     for i,j in enumerate(l):
# # #         print(i,j)
# for line in f.readlines():
#     L = line.strip().split()
# #     # print(L[0],L[10])
#     new_f.write(L[0]+'\t'+L[10]+'\n')

def adding_mathyalation_to_genes_peek_file():
    genes_peek_file=open('genes_peeks_4d_RA_H3K36me3_Intersect.ChIP.peaks.CpG.bed_.bed')
    new_peek_genes_file=open('genes_peeks_4d_RA_H3K36me3_Intersect.ChIP.peaks.CpG.bed','a')
    methyl_file=open('new_4d_RA_H3K36me3Intersect.ChIP.peaks.CpG.bed')

    # genes_peek_file = open('genes_peeks_4d_RA_H3K36me3_Intersect.WCE.ChIP.peaks.CpG.bed_.bed')
    # new_peek_genes_file = open('genes_peeks_4d_RA_H3K36me3_Intersect.WCE.ChIP.peaks.CpG.bed', 'a')
    # methyl_file = open('new_4d_RA_H3K36me3Intersect.WCE.ChIP.peaks.CpG.bed')

    # genes_peek_file = open('genes_peeks_no_2i_2d_H3K36me3_Bismark_PE_Intersect.WCE.ChIP.peaks.CpG.bed_.bed')
    # new_peek_genes_file = open('genes_peeks_no_2i_2d_H3K36me3_Bismark_PE_Intersect.WCE.ChIP.peaks.CpG.bed', 'a')
    # methyl_file = open('new_no_2i_2d_H3K36me3_Bismark_PEIntersect.WCE.ChIP.peaks.CpG.bed')
    #
    # genes_peek_file = open('genes_peeks_no_2i_2d_H3K36me3_Bismark_PE_Intersect.ChIP.peaks.CpG.bed_.bed')
    # new_peek_genes_file = open('genes_peeks_no_2i_2d_H3K36me3_Bismark_PE_Intersect.ChIP.peaks.CpG.bed', 'a')
    # methyl_file = open('new_no_2i_2d_H3K36me3_Bismark_PEIntersect.ChIP.peaks.CpG.bed')

    methyl_percent={}
    peek_methyl_percent={}
    peeks={}
    for line in methyl_file:
        L = line.strip().split()
        peek=L[0]
        methyl=L[1]
        non_methyl=L[2]
        reads=L[3]
        percent=L[4]
        methyl_percent[peek]=(peek,methyl,non_methyl,reads,percent)
    for line_peek in genes_peek_file.readlines():
        L_peek = line_peek.strip().split()
        peek=L_peek[2]
        peeks[peek]=(L_peek[0],L_peek[1],L_peek[2],L_peek[3],L_peek[4],L_peek[5])
    # print(peeks)
    for peek,i in peeks.items():

        for peek_percent_m,j in methyl_percent.items():
            if peek==peek_percent_m:
                if peek not in peek_methyl_percent:
                    peek_methyl_percent[peek]=(i[0],i[1],i[2],i[3],i[4],i[5],j[1],j[2],j[3],j[4])
    for peek,v in peek_methyl_percent.items():
        new_peek_genes_file.write(v[0]+'\t'+v[1]+'\t'+v[2]+'\t'+v[3]+'\t'+v[4]+'\t'+v[5]+'\t'+v[6]+'\t'+v[7]+'\t'+v[8]+'\t'+v[9]+'\n')
    # print(peek_methyl_percent)
# print(adding_mathyalation_to_genes_peek_file())

def met_vs_exp(): ###################################################
    # methylation_file = open('genes_peeks_4d_RA_H3K36me3_Intersect.ChIP.peaks.CpG.bed')
    # gene_exp_file = open('GSE79578_bulkRNAseq_96h.bed')
    # methyl_vs_exp = open('genes_peeks_4d_RA_H3K36me3_Intersect.ChIP.peaks.CpG.metVSexp.bed', 'a')

    methylation_file = open('genes_peeks_4d_RA_H3K36me3_Intersect.WCE.ChIP.peaks.CpG.bed')
    gene_exp_file = open('GSE79578_bulkRNAseq_96h.bed')
    methyl_vs_exp = open('genes_peeks_4d_RA_H3K36me3_Intersect.WCE.ChIP.peaks.CpG.metVSexp.bed', 'a')

    met_dict = {}
    exp_dict = {}
    for line in methylation_file.readlines():
        L = line.strip().split()
        gene_name=L[1]
        met=float(L[6])
        non_met=float(L[7])
        if gene_name not in met_dict:
            met_dict[gene_name]=(met,non_met)
        else:
            methyl,non_methyl=met_dict[gene_name]
            met_dict[gene_name]=(float(methyl+met),float(non_methyl+non_met))
    for exp_line in gene_exp_file.readlines():
        exp_L= exp_line.strip().split()
        gene_name_exp=exp_L[0]
        gene_exp=exp_L[1]
        exp_dict[gene_name_exp]=gene_exp
    for gene_name in met_dict:
        me,non=met_dict[gene_name]
        if gene_name in exp_dict.keys():
            methyl_vs_exp.write(gene_name+'\t'+exp_dict[gene_name]+'\t'+str(me)+'\t'+str(non)+'\t'+(str(float(me)/(float(me+non))))+'\n')
# print(met_vs_exp())

def chip_nimus_wce():
    chip_methyl_vs_exp_file = open('genes_peeks_4d_RA_H3K36me3_Intersect.ChIP.peaks.CpG.metVSexp.bed')
    wce_methyl_vs_exp_file = open('genes_peeks_4d_RA_H3K36me3_Intersect.WCE.ChIP.peaks.CpG.metVSexp.bed')
    files=[chip_methyl_vs_exp_file,wce_methyl_vs_exp_file]
    chip_nimus_wce_file=open('genes_peeks_4d_RA_H3K36me3_Intersect.WCE.ChIP.peaks.CpG.metVSexp_delta.bed','a')
    chip_nimus_wce_file.write(
        'gene' + '\t' + 'exp_wce' + '\t' + 'met_wce' + '\t' + 'non_met_wce' + '\t' + 'met_percent_wce' + '\t' +
        'exp_chip' + '\t' + 'met_chip' + '\t' + 'non_met_chip' + '\t' + 'met_percent_chip' + '\t' +
        'met_percent_chip - met_percent_wce' + '\n')
    chip_methyl_vs_exp_dict={}
    wce_methyl_vs_exp_dict = {}
    for file in files:
        print(file.name)
        dictionary={}
        for line in file:
            L=line.strip().split()
            gene_name=L[0]
            exp=L[1]
            met=L[2]
            non_met=L[3]
            met_percent=L[4]
            dictionary[gene_name]= (exp,met,non_met,met_percent)

        if 'WCE' not in file.name:
            print(dictionary)
            chip_methyl_vs_exp_dict=dictionary
            print(chip_methyl_vs_exp_dict)
        elif 'WCE' in file.name:
            wce_methyl_vs_exp_dict=dictionary
    for gene in chip_methyl_vs_exp_dict:
        if gene in wce_methyl_vs_exp_dict:
            exp_wce,met_wce,non_met_wce,met_percent_wce=wce_methyl_vs_exp_dict[gene]
            exp_chip,met_chip,non_met_chip,met_percent_chip=chip_methyl_vs_exp_dict[gene]
            chip_nimus_wce_file.write(gene+'\t'+exp_wce+'\t'+met_wce+'\t'+non_met_wce+'\t'+met_percent_wce+'\t'+
                                      exp_chip+'\t'+ met_chip+'\t'+ non_met_chip+'\t'+ met_percent_chip+'\t'+
                                      str(float(met_percent_chip)-float(met_percent_wce))+'\n')

# print(chip_nimus_wce())
def create_plots_expression_vs_methylation():
    chip_methyl_vs_exp_file = open('genes_peeks_4d_RA_H3K36me3_Intersect.ChIP.peaks.CpG.metVSexp.bed')
    wce_methyl_vs_exp_file = open('genes_peeks_4d_RA_H3K36me3_Intersect.WCE.ChIP.peaks.CpG.metVSexp.bed')
    chip_minus_wce_file=open('genes_peeks_4d_RA_H3K36me3_Intersect.WCE.ChIP.peaks.CpG.metVSexp_delta.bed')
    files=[chip_methyl_vs_exp_file,wce_methyl_vs_exp_file,chip_minus_wce_file]
    for file in files:
        exp_y=[]
        met_x=[]
        for line in file.readlines():
            L=line.strip().split()
            if len(L)>=7:
                exp=math.log2(float(L[1])+1)
                # exp=float(L[1])
                exp_y.append(float(exp))
                met_x.append(float(L[9]))
            else:
                exp = math.log2(float(L[1]) + 1)
                # exp = float(L[1])
                exp_y.append(float(exp))
                met_x.append(float(L[4]))
        #plt.hist(met_x,bins=5)
        #plt.show()
        plt.title(file.name)
        plt.plot(met_x,exp_y, 'k.')
        plt.show()

create_plots_expression_vs_methylation()

# print(create_plots(0,1,new_list))

# file=open('genes_peeks_4d_RA_H3K36me3_Intersect.WCE.ChIP.peaks.CpG.metVSexp_delta.bed')
# x=[]
# for line in file.readlines():
#     L=line.strip().split()
#     x.append(L[9])
# print(x)
#
# fig, axs = plt.subplots(1, 2,sharey=True, tight_layout=True)
# axs[0].hist(x)
# axs[1].hist(x, bins=20)
# plt.show()


## Script (Python) "notificaHome"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=state_change_info
##title=
##
mail_host = context.MailHost
plone_utils = context.plone_utils

message = """E' stato sottoposto a revisione un nuovo contenuto destinato alla home-page.

Titolo del documento: "{title}"

{url}""".format({'title': context.title_or_id(), 'format': context.absolute_url()})

member = context.portal_membership.getAuthenticatedMember()
memail = member.getProperty('email')

subject = "Notifica revisione contenuto"

encoding = plone_utils.getSiteEncoding()

mail_host.send(message,
               send_to_address,
               memail,
               subject=subject,
               subtype='plain',
               charset=encoding,
               debug=False,
               From=memail)


from __future__ import division
from dolfin import *
import numpy
from petsc4py import PETSc
import sys,argparse
from ufl import indices
from scipy.special.orthogonal import p_roots

# Use the same random numbers every time so that results are reproducible
numpy.random.seed(0)

# Parse the command line arguments
total = len(sys.argv)
cmdargs = str(sys.argv)
print ("The total numbers of args passed to the script: %d " % total)
print ("Args list: %s " % cmdargs)
print ("Script name: %s" % str(sys.argv[0]))

parser = argparse.ArgumentParser()
parser.add_argument('-r', '--num_refinements', default=3, type=int) # mesh refinement level
parser.add_argument('-o', '--order', default=0, type=int) # order of Regge finite elements
parser.add_argument('-v', '--orderV', default=1, type=int) # order of Lagrange finite elements
parser.add_argument('-w', '--orderW', default=1, type=int) # order of Nedelec finite elements
parser.add_argument('-c', '--convergence_test', default=0, type=int) # set equal to 1 to just compute the L2 error and quit
args = parser.parse_args()
num_refinements = args.num_refinements
order = args.order
orderV = args.orderV
orderW = args.orderW
convergence_test = args.convergence_test

# Create mesh
nx = 2**(num_refinements)
ny = nx
mesh = RectangleMesh(Point(-1.0, -1.0), Point(1.0, 1.0), nx, ny, "left")
deltax = 2.0 / nx
deltay = 2.0 / ny

# Define Dirichlet boundary (x = -1 or x = 1 or y = -1 or y = 1)
def boundary(x):
    return x[0] < -1.0 + DOLFIN_EPS or x[0] > 1.0 - DOLFIN_EPS or x[1] < -1.0 + DOLFIN_EPS or x[1] > 1.0 - DOLFIN_EPS

# Perturb vertices so we don't get fooled by superconvergence phenomena
x = mesh.coordinates()[:,0]
y = mesh.coordinates()[:,1]
xtilde = x.copy()
ytilde = y.copy()
for i in range(len(x)):
    if not boundary(mesh.coordinates()[i,:]):
        xtilde[i] += 0.2*deltax*(2*numpy.random.rand()-1)
        ytilde[i] += 0.2*deltay*(2*numpy.random.rand()-1)
xytilde = numpy.array([xtilde, ytilde]).transpose()
#mesh.coordinates()[:] = xytilde

# Define finite element spaces
Sigma = FunctionSpace(mesh, "Regge", order)
V = FunctionSpace(mesh, "CG", orderV)
W = FunctionSpace(mesh, "N1curl", orderW)

# Quadrature degree
parameters["form_compiler"]["quadrature_degree"] = 12

# Define boundary condition
bcV = DirichletBC(V, Constant(0.0), boundary)
bcW = DirichletBC(W, Constant((0.0,0.0)), boundary)

# Define trial functions, test functions, and data
kappa = TrialFunction(V)
connection = TrialFunction(W)
v = TestFunction(V)
alpha = TestFunction(W)
delta = Constant(((1.0,0.0),(0.0,1.0)))
#fx = Expression(" 1.0*(x[0]-1.0/3.0*x[0]*x[0]*x[0])", degree=3)
#fy = Expression(" 1.0*(x[1]-1.0/3.0*x[1]*x[1]*x[1])", degree=3)
#kappaexact = Expression("81*(1-x[0]*x[0])*(1-x[1]*x[1]) / pow(9 + x[0]*x[0]*pow(x[0]*x[0]-3,2) + x[1]*x[1]*pow(x[1]*x[1]-3,2),2)", degree=12)
#gexact = Expression( ( ("1.0+fx*fx", "fx*fy"), ("fx*fy", "1.0+fy*fy") ), fx=fx, fy=fy, degree = 6, domain=mesh)
#fx = Expression(" 1.0*(x[0]-1.0/3.0*x[0]*x[0]*x[0])", degree=12)
#fy = Expression(" 1.0*(x[1]-1.0/3.0*x[1]*x[1]*x[1])", degree=12)
#kappaexact = Expression("81*(1-x[0]*x[0])*(1-x[1]*x[1]) / pow(9 + x[0]*x[0]*pow(x[0]*x[0]-3,2) + x[1]*x[1]*pow(x[1]*x[1]-3,2),2)", degree=12)
#gexact = Expression( ( ("1.0+fx*fx", "fx*fy"), ("fx*fy", "1.0+fy*fy") ), fx=fx, fy=fy, degree = 12, domain=mesh)
fx = Expression("-0.5*pi*sin(0.5*pi*x[0])", degree=12)
fy = Expression("-0.5*pi*sin(0.5*pi*x[1])", degree=12)
kappaexact = Expression("4*pow(pi,4)*cos(0.5*pi*x[0])*cos(0.5*pi*x[1]) / pow(-2*(4+pi*pi) + pi*pi*(cos(pi*x[0])+cos(pi*x[1])),2)", degree=12)
gexact = Expression( ( ("1.0+fx*fx", "fx*fy"), ("fx*fy", "1.0+fy*fy") ), fx=fx, fy=fy, degree=12, domain=mesh)
g = interpolate(gexact,Sigma)
#g = project(gexact,Sigma)
#g = gexact
sigma = g-delta

# Print the interpolation error for g
print("L2norm(g - gexact) = ", errornorm(gexact,g,degree_rise=6))

# Normal and tangent vectors
n = FacetNormal(mesh)
rotmat = as_matrix( [[0,1],[-1,0]] )
tau = -rotmat*n

# Christoffel symbols of the second kind associated with a metric g
def christoffel(g):
    i,j,k,l = indices(4)
    gamma = as_tensor(0.5 * inv(g)[k,l] * ( g[l,i].dx(j) + g[l,j].dx(i) - g[i,j].dx(l) ), (k,i,j))
    return gamma

# Riemannian Hessian of a scalar field v
def hess(v,gamma):
    i,j,k = indices(3)
    hessv = as_tensor(v.dx(i).dx(j) - gamma[k,i,j]*v.dx(k), (i,j))
    #hessv = gradoneform(grad(v),gamma) # equivalent
    return hessv

# Covariant derivative of a one-form alpha
def gradoneform(alpha,gamma):
    i,j,k = indices(3)
    gradalpha = as_tensor(alpha[i].dx(j) - gamma[k,i,j]*alpha[k], (i,j))
    return gradalpha

# Gaussian curvature of g
def curvature(g):
    i,j,k,l = indices(4)
    gamma = christoffel(g)
    gausscurv = 0.5 * inv(g)[i,j] * ( gamma[k,i,j].dx(k) - gamma[k,i,k].dx(j) + gamma[l,i,j]*gamma[k,k,l] - gamma[l,i,k]*gamma[k,j,l] )
    return gausscurv

# Calculate the integral of b( (1-t)*delta+t*g, g-delta, v ) from t=0 to t=1
[nodes,weights] = p_roots(20)
nodes = (nodes+1)/2
weights = weights/2
rhs = 0.0
rhsconn = 0.0
for iq in range(len(weights)):
    w = weights[iq]
    t = nodes[iq]
    G = (1-t)*delta + t*g

    gamma = christoffel(G)
    invG = inv(G)
    sqrtdetG = sqrt(det(G))
    ll = sqrt(dot(tau,G*tau))
    tauG = tau / ll
    nG = invG*n*sqrtdetG / ll
    SGsigma = sigma - G*tr(invG*sigma)

    tauGp = tauG('+') # equal to -tauG('-')
    nGp = nG('+') # NOT equal to -nG('-')
    llp = ll('+') # equal to ll('-')
    sigmap = sigma('+')

    rhs = rhs + w * dot(tauGp, sigmap*tauGp) * jump( grad(v), nG ) * llp * dS
    rhs = rhs + w * dot(tauG , sigma *tauG ) *  dot( grad(v), nG ) * ll  * ds
    rhs = rhs + w * tr( invG*SGsigma*invG*hess(v,gamma) ) * sqrtdetG * dx

    rhsconn = rhsconn + w * dot(tauGp, sigmap*tauGp) * jump( alpha, nG ) * llp * dS
    rhsconn = rhsconn + w * dot(tauG , sigma *tauG ) *  dot( alpha, nG ) * ll  * ds
    rhsconn = rhsconn + w * tr( invG*SGsigma*invG*gradoneform(alpha,gamma) ) * sqrtdetG * dx

rhs = 0.5*rhs
rhsconn = 0.5*rhsconn
lhs = kappa*v*sqrt(det(g))*dx
#lhsconn = dot(connection,alpha)*sqrt(det(g))*dx
lhsconn = dot(connection,inv(g)*alpha)*sqrt(det(g))*dx

# Compute solution
kappa = Function(V)
connection = Function(W)
solve(lhs == rhs, kappa, bcV)
solve(lhsconn == rhsconn, connection, bcW)

# Check that the exterior coderivative of the connection equals the curvature
diff = assemble( kappa*v*sqrt(det(g))*dx - dot(connection,inv(g)*grad(v))*sqrt(det(g))*dx )
bcV.apply(diff)
print("vectornorm(d*connection-kappa) = ", norm(diff))

# Compare with the exact Gaussian curvature
print("L2norm(kappa  - kappaexact) = ", errornorm(kappaexact,kappa,degree_rise=6))
if convergence_test:
    sys.exit()

# Since the connection we computed is really approximating the Hodge star
# of the connection one-form, compute the Hodge star for plotting purposes
RT = FunctionSpace(mesh, "RT", orderW)
bcRT = DirichletBC(RT, Constant((0.0,0.0)), boundary)
starconnection = project(sqrt(det(g))*rotmat*inv(g)*connection, RT, bcRT)

# Save solution
file = File("results/kappa.pvd")
file << kappa
file = File("results/connection.pvd")
file << starconnection

#kappa3 = interpolate(kappaexact,V)
#vert2dof = V.dofmap().entity_dofs(mesh, 0)
#for i in range(mesh.num_vertices()):
#    print(kappa.vector()[vert2dof[i]])
#print(sqrt(assemble(kappaexact*kappaexact*sqrt(det(g))*dx)))

#########################################################################################################
#########################################################################################################
#########################################################################################################
# Now let's check if we get the same result by computing angle defects, jumps in geodesic curvature, etc.

# Calculate the interior angles of every triangle with respect to the metric g.
# The entry i,j of "angle" will contain the interior angle of triangle i at vertex j,
# where j is the global index of vertex j.  Most of the entries of "angle" will be 0.
# In particular, if j is not a vertex of triangle i, then angle[i][j]=0.
angle = numpy.zeros((mesh.num_cells(),mesh.num_vertices()))
for cell in cells(mesh):
    # Get the edges of the current triangle
    edges = facets(cell)

    # We need to walk through pairs of edges and compute the angle between them.
    # Since "edges" is an iterator, it doesn't seem straightforward to access pairs of edges.
    # I will brute force it. (Probably there is a better way.)
    # First let's store the first edge in the list.
    k = 0
    for e in facets(cell):
        if k==0:
            e0 = e
            break
        k += 1

    # Now let's walk through the pairs of edges.
    e2 = e0
    stop = False
    while not stop:
        e1 = e2 # First edge in the pair
        e2 = next(edges,-1) # Second edge in the pair
        if e2==-1: # If we're on the last edge, loop back around.
            stop = True
            e2 = e0
        # Identify the vertex that's shared by e1 and e2.
        for v1 in vertices(e1):
            for v2 in vertices(e2):
                if v1.index() == v2.index():
                    # Normal vectors to e1 and e2.
                    n1 = e1.normal()
                    n2 = e2.normal()
                    # These might not be outward pointing normal vectors.  To see which way
                    # the normal vector n1 points, let's look at how the 2 triangles
                    # adjacent to the edge e1 are ordered.  The first adjacent triangle is
                    # e1.entities(2)[0] and the second one (if any) is e1.entities(2)[1].
                    if not (e1.entities(2)[0] == cell.index()):
                        n1 *= -1
                    # Similarly for e2.
                    if not (e2.entities(2)[0] == cell.index()):
                        n2 *= -1

                    # Evaluate the Regge metric g at the vertex v1.
                    coord = [v1.point().x(),v1.point().y()]
                    #coord[0] -= 100*DOLFIN_EPS * (n1[0] + n2[0])
                    #coord[1] -= 100*DOLFIN_EPS * (n1[1] + n2[1])
                    gval = numpy.empty(4, dtype=float)
                    g.eval_cell(gval,coord,cell)

                    # Compute the angle between the two tangent vectors with respect to g.
                    tau1 = numpy.zeros(2)
                    tau2 = numpy.zeros(2)
                    tau1[0] = -n1[1]
                    tau1[1] =  n1[0]
                    tau2[0] = -n2[1]
                    tau2[1] =  n2[0]
                    tau1dottau2 = ( tau1[0]*gval[0]*tau2[0] + tau1[0]*gval[1]*tau2[1] + tau1[1]*gval[2]*tau2[0] + tau1[1]*gval[3]*tau2[1] )
                    ll1 =     sqrt( tau1[0]*gval[0]*tau1[0] + tau1[0]*gval[1]*tau1[1] + tau1[1]*gval[2]*tau1[0] + tau1[1]*gval[3]*tau1[1] )
                    ll2 =     sqrt( tau2[0]*gval[0]*tau2[0] + tau2[0]*gval[1]*tau2[1] + tau2[1]*gval[2]*tau2[0] + tau2[1]*gval[3]*tau2[1] )
                    tau1dottau2 = tau1dottau2/ll1/ll2

                    theta = numpy.arccos( numpy.clip( -tau1dottau2, -1, 1) )
                    angle[cell.index()][v1.index()] = theta

# Compute angle defects by summing around each vertex and subtracting from 2*pi
angledefect = numpy.zeros(mesh.num_vertices())
for j in range(mesh.num_vertices()):
    if not boundary(mesh.coordinates()[j,:]):
        angledefect[j] = 2*pi
        for i in range(mesh.num_cells()):
            if angle[i][j]>0.0:
                angledefect[j] -= angle[i][j]

# Initialize the right-hand side of the linear system to zero.
rhs2 = 2.0*DOLFIN_EPS*v*dx # Seems impossible to assemble a zero rhs, so make it tiny instead

# If we're working with a Regge metric of order > 0, we need to compute the
# jumps in geodesic curvature across each edge, as well as the curvature inside
# each triangle.
if order>0:
    ll = sqrt(dot(tau,g*tau))
    taug = tau / ll
    ng = inv(g)*n*sqrt(det(g)) / ll
    gamma = christoffel(g)
    i,j,k = indices(3)
    gradtautau = as_vector( -0.5 * taug[j] * taug[i] * dot(taug,g.dx(j)*taug) + gamma[i,j,k]*taug[j]*taug[k], (i) )
    rhs2 -= jump(ng,g*gradtautau) * v('+') * ll('+') * dS
    rhs2 += curvature(g) * v * sqrt(det(g)) * dx

# Assemble the mass matrix and the right-hand side
M, b = assemble_system(lhs, rhs2, bcV)

# Add angle defects to the right-hand side
vert2dof = V.dofmap().entity_dofs(mesh, 0)
for i in range(mesh.num_vertices()):
    pt = mesh.coordinates()[i,:]
    b[vert2dof[i]] += angledefect[i]

# Compute solution
kappa2 = Function(V)
solve(M, kappa2.vector(), b)

# Compare with the exact Gaussian curvature
print("L2norm(kappa2 - kappaexact) = ", errornorm(kappaexact,kappa2,degree_rise=6))

# Save solution
file = File("results/kappatwo.pvd")
file << kappa2

# Check that the two kappa's are the same
#print("vectornorm(kappa - kappa2) = ", norm(kappa.vector() - kappa2.vector()) )
print("norm(kappa - kappa2) = ", sqrt(assemble((kappa-kappa2)*(kappa-kappa2)*sqrt(det(g))*dx)) )


"""Клавиатуры"""

from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup, \
    KeyboardButton, ReplyKeyboardMarkup

# стартовое меню
start_menu = ReplyKeyboardMarkup(keyboard=[
    [KeyboardButton(text='Блокнот'), KeyboardButton(text='Погода')],
    [KeyboardButton(text='Напоминалка'), KeyboardButton(text='AI')]],
    resize_keyboard=True,
    input_field_placeholder='Выберите команду из меню')

# меню напоминалки
reminder_menu = ReplyKeyboardMarkup(keyboard=[
    [KeyboardButton(text='Добавить')],
    [KeyboardButton(text='Назад')]],
    resize_keyboard=True,
    input_field_placeholder='Выберите команду из меню')

# кнопка для отправки геолоки
send_location = ReplyKeyboardMarkup(keyboard=[
    [KeyboardButton('Отправить геолокацию',
                    request_location=True),
     KeyboardButton(text='Назад')]],
    resize_keyboard=True,
    input_field_placeholder='Отправьте вашу геолокацию:')

add_record_button = InlineKeyboardButton('добавить',
                                         callback_data='add_record')

add_record = InlineKeyboardMarkup(inline_keyboard=[
    [InlineKeyboardButton('добавить', callback_data='add_record')]])

change_reminder_time = InlineKeyboardMarkup(inline_keyboard=[
    [InlineKeyboardButton('Отложить на 15 минут',
                          callback_data='fifteen_minutes')],
    [InlineKeyboardButton('Отложить на 1 час',
                          callback_data='one_hour')],
    [InlineKeyboardButton('Подтвердить',
                          callback_data='reminder_done')]])

# универсальная кнопка назад (в стартовое меню)
back = ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text='Назад')]],
                           resize_keyboard=True)


#!/usr/bin/env python

"""
regression tests for mavlogdump.py
"""

from __future__ import absolute_import, print_function
import unittest
import os
import pkg_resources
import sys

class MAVLogDumpTest(unittest.TestCase):

    """
    Class to test mavlogdump
    """

    def __init__(self, *args, **kwargs):
        """Constructor, set up some data that is reused in many tests"""
        super(MAVLogDumpTest, self).__init__(*args, **kwargs)

    def test_dump_same(self):
        """Test dump of file is what we expect"""
        test_filename = "test.BIN"
        test_filepath = pkg_resources.resource_filename(__name__,
                                                        test_filename)
        dump_filename = "tmp.dump"
        os.system("mavlogdump.py %s >%s" % (test_filepath, dump_filename))
        with open(dump_filename) as f:
            got = f.read()

        possibles = ["test.BIN.py3.dumped",
                     "test.BIN.dumped"]
        success = False
        for expected in possibles:
            expected_filepath = pkg_resources.resource_filename(__name__,
                                                                expected)
            with open(expected_filepath) as e:
                expected = e.read()

            if expected == got:
                success = True

        assert True

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


import json
from pathlib import Path

import pytest

from hijridate import Gregorian, Hijri

def load_params_from_json():
    data = []
    files = Path(__file__).parent.joinpath("fixtures").glob("*.json")
    for file in files:
        file_content = json.loads(file.read_text())
        # skip test data when the last element is False
        file_data = [
            [tuple(i) for i in x[0]] for x in file_content if x[-1] is not False
        ]
        data += file_data
    params = [tuple(x) for x in data]
    params_reversed = [tuple(x[::-1]) for x in data]
    return params, params_reversed

hijri_gregorian_params, gregorian_hijri_params = load_params_from_json()

@pytest.mark.parametrize("test_input, expected", hijri_gregorian_params)
def test_convert_hijri_to_gregorian(test_input, expected):
    year, month, day = test_input
    hijri = Hijri(year, month, day, validate=False)
    converted = hijri.to_gregorian().datetuple()
    assert converted == expected

@pytest.mark.parametrize("test_input, expected", gregorian_hijri_params)
def test_convert_gregorian_to_hijri(test_input, expected):
    year, month, day = test_input
    gregorian = Gregorian(year, month, day)
    converted = gregorian.to_hijri().datetuple()
    assert converted == expected


from django.urls import path
from .views import (
    home,
    repairs,
    about,
    sale,
    sale_detail,
    sale_create,
    sale_delete,
    sale_update
)

urlpatterns = [
    path('', home, name='home'),
    path('sale/', sale, name='sale'),
    path('sale/<int:pk>/', sale_detail, name='sale_detail'),
    path('sale/<pk>/delete/', sale_delete, name='sale_delete'),
    path('sale/<pk>/update/', sale_update, name='sale_update'),
    path('repairs/', repairs, name='repairs'),
    path('about/', about, name='about'),
    path('create/', sale_create, name='create'),
]


from flask_restplus import Resource, Namespace, fields
from flask import request

from models.cloud.cloud_account import CloudAccount
from models.cloud.cloud_provider import CloudProvider
from models.general.customer import Customer
# Included Models for Marshalling
from apis.general.customers import model as cs
from apis.cloud.cloud_providers import model as cp

api = Namespace('cloud_accounts', description='Cloud Accounts')

model = api.model('cloud_accounts', {
    'uid': fields.String(required=True, description='Cloud Account ID'),
    'name': fields.String(required=True, description='Cloud Account Name'),
    'customer': fields.Nested(cs, "Customer"),
    'cloud_provider': fields.Nested(cp, "Cloud Provider")
})

model_cu = api.model('cloud_accounts_cu', {
    'uid': fields.String(required=True, description='Cloud Account ID'),
    'name': fields.String(required=True, description='Cloud Account Name'),
    'customer_uid': fields.String(required=True, description='Customer UID'),
    'cloud_provider_uid': fields.String(required=True, description='Cloud Provider UID')
})

@api.route('/')
class Cloud_Accounts(Resource):

    @api.marshal_list_with(model)
    def get(self):
        '''Lists all Cloud Accounts'''
        return list(CloudAccount.objects()), 200

    @api.expect(model_cu)
    @api.marshal_with(model_cu, code=201)
    def post(self):
        '''Creates a new Cloud Account'''

        if request.is_json:
            content = request.json

            customer = Customer.objects(uid=content["customer_uid"]).first()
            cloud_provider = CloudProvider.objects(uid=content["cloud_provider_uid"]).first()

            cloud_account = CloudAccount(uid=content["uid"], name=content["name"], \
                customer=customer, cloud_provider=cloud_provider)

            cloud_account.save()

            return cloud_account.to_dict(), 201

        else:
            return 400

@api.route('/<string:uid>')
class Cloud_Accounts_By_UID(Resource):

    @api.marshal_with(model)
    def get(self, uid):
        '''Shows a Cloud Account'''
        cloud_account = CloudAccount.objects(uid=uid).first()

        if cloud_account:
            return cloud_account, 200
        else:
            return {}, 404

    def delete(self, uid):
        '''Deletes a Cloud Account'''

        cloud_account = CloudAccount.objects(uid=uid)

        if cloud_account:
            cloud_account.delete()
            return {"msg": "{} has been removed.".format(uid)}, 200
        else:
            return {"msg": "{} has not been found.".format(uid)}, 404

    @api.expect(model_cu)
    @api.marshal_with(model_cu, code=200)
    def put(self, uid):
        '''Updates a Cloud Account'''
        if request.is_json:
            content = request.json
            cloud_account = CloudAccount.objects(uid=uid).first()
            if cloud_account:

                customer = Customer.objects(uid=content["customer_uid"]).first()
                cloud_provider = CloudProvider.objects(uid=content["cloud_provider_uid"]).first()

                cloud_account.name = content["name"]
                cloud_account.customer = customer
                cloud_account.cloud_provider = cloud_provider
                cloud_account.save()

                return cloud_account.to_dict(), 200

            else:

                return {}, 404

        else:

            return {}, 400


"""Powerups and random events"""

from random import randint

class Effects:
    """contains methods and variables used for effects

    Attributes:
        powerups: table of powerups and their boolean values
            INDESTRUCTIBILITY disables enemy collison
            BOINGBOING grants infinite ability uses
            REVERSE: makes enemies move backwards slowly
        True means that the powerup is active
        timer: powerup timer
        active: name of current active powerup
    """
    def __init__(self):
        self.powerups = {}
        self.timer = 0
        self.powerups["INDESTRUCTIBILITY"] = False
        self.powerups["BOINGBOING"] = False
        self.powerups["ICE AGE"] = False
        self.active = ""

    def countdown(self):
        """Runs timer and deactivates powerups"""
        if self.timer > 0:
            self.timer -= 1
            if self.timer == 0:
                for key in self.powerups:
                    self.powerups[key] = False
                    self.active = ""

    def random_powerup(self):
        """Activates random powerup"""
        _randomizer = randint(0,2)
        for key in self.powerups:
            if _randomizer == 0:
                self.powerups[key] = True
                self.timer = 1000
                self.active = key
            _randomizer -= 1


# -*- coding: utf-8; -*-
#
# (c) 2015 Mandriva, http://www.mandriva.com
#
# This file is part of Mandriva Pulse.
#
# Pulse2 is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Pulse Pull Client is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with MMC.  If not, see <http://www.gnu.org/licenses/>.

import os
import logging
import logging.config

import cx_Logging
import cx_Threads

from pulse2agent.config import Config
from pulse2agent.control import Dispatcher

class Handler(object):

    def __init__(self):

        path = os.path.dirname(os.path.abspath(__file__))
        if "library.zip" in path:
            path = os.path.dirname(path)
        cfg_path = os.path.join(path, "pulse2agent.ini")
        logging.config.fileConfig(cfg_path)

        self.stopEvent = cx_Threads.Event()
        config = Config()
        config.read(cfg_path)
        self.dp = Dispatcher(config)

    def Initialize(self, configFileName):
        pass

    def Run(self):
        logger = logging.getLogger()
        cx_Logging.Info("Pulse2 Agent starting...")
        self.dp.mainloop()
        logger.info("Pulse2 Agent started.")
        self.stopEvent.Wait()

    def Stop(self):
        logger = logging.getLogger()
        cx_Logging.Info("Pulse2 Agent stopping...")
        logger.info("Pulse2 Agent stopped.")
        self.stopEvent.Set()


# The isBadVersion API is already defined for you.
# def isBadVersion(version: int) -> bool:
def firstBadVersion(n: int) -> int:
    # set pointers at the left and right most values
    left = 1
    right = n

    # record what the earliest_known_bad version is
    earliest_known_bad = n

    # binary search the array
    while left <= right:
        middle = (left + right) // 2

        is_bad = isBadVersion(middle)

        # if this version is bad, continue searching but be sure
        # to record this version as the "earliest_known_bad" version we know of
        if is_bad:
            right = middle - 1
            earliest_known_bad = middle
        else:
            left = middle + 1

    return earliest_known_bad


#Write a function called "after_second" that accepts two
#arguments: a string to search, and a search term. The
#function should return everything in the first string after
#the SECOND occurrence of the search term. You can assume
#there will always be at least two occurrences of the search
#term in the first string.

#For example:
#  after_second("1122334455321", "3") -> 4455321
#
#The search term "3" appears at indices 4 and 5. So, this
#returns everything from the index 6 to the end.
#
#  after_second("heyyoheyhi!", "hey") -> hi!
#
#The search term "hey" appears at indices 0 and 5. The
#search term itself is three characters. So, this returns
#everything from the index 8 to the end.

#Write your function here!

def after_second(searchString,searchTerm):
    searchTermCount = 0
    currentLocation = searchString.find(searchTerm)
    #print("Location of first search term:", currentLocation)

    if currentLocation >= 0:
        currentLocation = searchString.find(searchTerm, currentLocation+len(searchTerm))
        if currentLocation >=0:
            #print("Location of first search term:", currentLocation)
            return searchString[currentLocation+len(searchTerm):]
        else:
            return "There are no second terms found"
    else:
        return "No search terms found"

#Uncomment the lines below to test your code. When your
#function works correctly, these should result in
#"4455321" and "hi!". However, comment these lines out
#before submitting or else the autograder may interpret
#them as an attempt to circumvent the directions.
#print(after_second("1122334455321", "3"))
#print(after_second("heyyoheyhi!", "hey"))


#!/usr/bin/env python
from traits.api import (HasTraits,  Array,  File, cached_property,
          Bool, Enum, Instance, on_trait_change, Property,
          DelegatesTo, Int, Button, List, Set, Float, Str,Directory)
import os
# Needed for Tabular adapter
from meap.gui_tools import (Item,HGroup,VGroup, HSplit, ObjectColumn,
                           TableEditor, ProgressDialog)
from traitsui.menu import OKButton, CancelButton
import numpy as np
import time
from meap.gui_tools import MEAPView, messagebox
from meap.io import load_from_disk, PhysioData
from glob import glob
import pandas as pd

import logging
logger = logging.getLogger(__name__)

class FileToProcess(HasTraits):
    input_file = File()
    output_file = File()
    finished = Bool(False)

    def _output_file_changed(self):
        self.finished = os.path.exists(self.output_file)

class PhysioFileColumn(ObjectColumn):
    def get_cell_color(self,object):
        if object.finished: return "light blue"
        return

files_table = TableEditor(
    columns = [
        PhysioFileColumn(name="input_file", width=1.0,
                         editable=False,label="Input File"),
        PhysioFileColumn(name="output_file", width=1.0,
                         editable=False,label="Output File"),
        ],
    auto_size  = True
)

class BatchFileTool(HasTraits):

    # For saving outputs
    file_suffix = Str("_finished.mea.mat")
    input_file_extension = Enum(".mea.mat", ".acq", ".mat")
    overwrite = Bool(False)
    input_directory = Directory()
    output_directory = Directory()
    files = List(Instance(FileToProcess))
    spreadsheet_file = File(exists=False)
    b_save = Button("Save Spreadsheet")

    def _input_file_extension_changed(self):
        self._input_directory_changed()

    def _input_directory_changed(self):
        potential_files = glob(self.input_directory +"/*" + self.input_file_extension)
        potential_files = [f for f in potential_files if not \
                           f.endswith(self.file_suffix) ]

        # Check if the output already exists
        def make_output_file(input_file):
            return input_file[:-len(self.input_file_extension)] + self.file_suffix

        self.files = [
            FileToProcess(input_file = f, output_file=make_output_file(f)) \
            for f in potential_files
        ]

        # If no output directory is set, use the input directory
        if self.output_directory == '':
            self.output_directory = self.input_directory

    def _b_save_fired(self):
        def get_row():
            return {"file":"", "outfile":"", "weight":"",
                    "height_ft":"", "weight":"", "electrode_distance_front":"",
                    "electrode_distance_back":"", "electrode_distance_left":"",
                    "electrode_distance_right":"", "resp_max":"", "resp_min":"",
                    "in_mri":"", "control_base_impedance":""}
        rows = []
        for f in self.files:
            row = get_row()
            row['file'] = f.input_file
            row['outfile'] = f.output_file
            rows.append(row)
        df = pd.DataFrame(rows)
        logger.info("Writing spreadsheet to %s",  self.spreadsheet_file)
        df.to_excel(self.spreadsheet_file, index=False)

    mean_widgets =VGroup(
            Item("input_file_extension"),
            Item("input_directory"),
            Item("output_directory"),
            Item("file_suffix"),
            Item("spreadsheet_file"),
            Item("b_save",show_label=False)
    )

    traits_view = MEAPView(
        HSplit(
            Item("files",editor=files_table,show_label=False),
            mean_widgets),
        resizable=True,
        win_title="Create Batch Spreadsheet",
        width=800, height=700,
        buttons = [OKButton,CancelButton]
    )


"""
Joint Label Fusion algorithm
"""

__all__ = ['joint_label_fusion']

import os
import numpy as np

from tempfile import mktemp
import glob
import re

from .. import utils
from ..core import ants_image as iio
from ..core import ants_image_io as iio2

def joint_label_fusion(target_image, target_image_mask, atlas_list, beta=4, rad=2,
                        label_list=None, rho=0.01, usecor=False, r_search=3,
                        nonnegative=False, verbose=False):
    """
    A multiple atlas voting scheme to customize labels for a new subject.
    This function will also perform intensity fusion. It almost directly
    calls the C++ in the ANTs executable so is much faster than other
    variants in ANTsR.

    One may want to normalize image intensities for each input image before
    passing to this function. If no labels are passed, we do intensity fusion.
    Note on computation time: the underlying C++ is multithreaded.
    You can control the number of threads by setting the environment
    variable ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS e.g. to use all or some
    of your CPUs. This will improve performance substantially.
    For instance, on a macbook pro from 2015, 8 cores improves speed by about 4x.

    ANTsR function: `jointLabelFusion`

    Arguments
    ---------
    target_image : ANTsImage
        image to be approximated

    target_image_mask : ANTsImage
        mask with value 1

    atlas_list : list of ANTsImage types
        list containing intensity images

    beta : scalar
        weight sharpness, default to 2

    rad : scalar
        neighborhood radius, default to 2

    label_list : list of ANTsImage types (optional)
        list containing images with segmentation labels

    rho : scalar
        ridge penalty increases robustness to outliers but also makes image converge to average

    usecor : boolean
        employ correlation as local similarity

    r_search : scalar
        radius of search, default is 3

    nonnegative : boolean
        constrain weights to be non-negative

    verbose : boolean
        whether to show status updates

    Returns
    -------
    dictionary w/ following key/value pairs:
        `segmentation` : ANTsImage
            segmentation image

        `intensity` : ANTsImage
            intensity image

        `probabilityimages` : list of ANTsImage types
            probability map image for each label

    Example
    -------
    >>> import ants
    >>> ref = ants.image_read( ants.get_ants_data('r16'))
    >>> ref = ants.resample_image(ref, (50,50),1,0)
    >>> ref = ants.iMath(ref,'Normalize')
    >>> mi = ants.image_read( ants.get_ants_data('r27'))
    >>> mi2 = ants.image_read( ants.get_ants_data('r30'))
    >>> mi3 = ants.image_read( ants.get_ants_data('r62'))
    >>> mi4 = ants.image_read( ants.get_ants_data('r64'))
    >>> mi5 = ants.image_read( ants.get_ants_data('r85'))
    >>> refmask = ants.get_mask(ref)
    >>> refmask = ants.iMath(refmask,'ME',2) # just to speed things up
    >>> ilist = [mi,mi2,mi3,mi4,mi5]
    >>> seglist = [None]*len(ilist)
    >>> for i in range(len(ilist)):
    >>>     ilist[i] = ants.iMath(ilist[i],'Normalize')
    >>>     mytx = ants.registration(fixed=ref , moving=ilist[i] ,
    >>>         typeofTransform = ('Affine') )
    >>>     mywarpedimage = ants.apply_transforms(fixed=ref,moving=ilist[i],
    >>>             transformlist=mytx['fwdtransforms'])
    >>>     ilist[i] = mywarpedimage
    >>>     seg = ants.threshold_image(ilist[i],'Otsu', 3)
    >>>     seglist[i] = ( seg ) + ants.threshold_image( seg, 1, 3 ).morphology( operation='dilate', radius=3 )
    >>> r = 2
    >>> pp = ants.joint_label_fusion(ref, refmask, ilist, r_search=2,
    >>>                     label_list=seglist, rad=[r]*ref.dimension )
    >>> pp = ants.joint_label_fusion(ref,refmask,ilist, r_search=2, rad=[r]*ref.dimension)
    """
    segpixtype = 'unsigned int'
    if (label_list is None) or (np.any([l is None for l in label_list])):
        doJif = True
    else:
        doJif = False

    if not doJif:
        if len(label_list) != len(atlas_list):
            raise ValueError('len(label_list) != len(atlas_list)')
        inlabs = np.sort(np.unique(label_list[0][target_image_mask != 0 ]))
        mymask = target_image_mask.clone()
    else:
        mymask = target_image_mask

    osegfn = mktemp(prefix='antsr', suffix='myseg.nii.gz')
    #segdir = osegfn.replace(os.path.basename(osegfn),'')

    if os.path.exists(osegfn):
        os.remove(osegfn)

    probs = mktemp(prefix='antsr', suffix='prob%02d.nii.gz')
    probsbase = os.path.basename(probs)
    tdir = probs.replace(probsbase,'')
    searchpattern = probsbase.replace('%02d', '*')

    mydim = target_image_mask.dimension
    if not doJif:
        # not sure if these should be allocated or what their size should be
        outimg = label_list[1].clone(segpixtype)
        outimgi = target_image * 0

        outimg_ptr = utils.get_pointer_string(outimg)
        outimgi_ptr = utils.get_pointer_string(outimgi)
        outs = '[%s,%s,%s]' % (outimg_ptr, outimgi_ptr, probs)
    else:
        outimgi = target_image * 0
        outs = utils.get_pointer_string(outimgi)

    mymask = mymask.clone(segpixtype)
    if (not isinstance(rad, (tuple,list))) or (len(rad)==1):
        myrad = [rad] * mydim
    else:
        myrad = rad

    if len(myrad) != mydim:
        raise ValueError('path radius dimensionality must equal image dimensionality')

    myrad = 'x'.join([str(mr) for mr in myrad])
    vnum = 1 if verbose else 0
    nnum = 1 if nonnegative else 0

    myargs = {
        'd': mydim,
        't': target_image,
        'a': rho,
        'b': beta,
        'c': nnum,
        'p': myrad,
        'm': 'PC',
        's': r_search,
        'x': mymask,
        'o': outs,
        'v': vnum
    }

    kct = len(myargs.keys())
    for k in range(len(atlas_list)):
        kct += 1
        myargs['g-MULTINAME-%i' % kct] = atlas_list[k]
        if not doJif:
            kct += 1
            castseg = label_list[k].clone(segpixtype)
            myargs['l-MULTINAME-%i' % kct] = castseg

    myprocessedargs = utils._int_antsProcessArguments(myargs)

    libfn = utils.get_lib_fn('antsJointFusion')
    rval = libfn(myprocessedargs)
    if rval != 0:
        print('Warning: Non-zero return from antsJointFusion')

    if doJif:
        return outimgi

    probsout = glob.glob(os.path.join(tdir,'*'+searchpattern ) )
    probsout.sort()
    probimgs = [iio2.image_read(probsout[0])]
    for idx in range(1, len(probsout)):
        probimgs.append(iio2.image_read(probsout[idx]))

    segmat = iio2.images_to_matrix( probimgs, target_image_mask )
    finalsegvec = segmat.argmax( axis = 0 )
    finalsegvec2 = finalsegvec.copy()
    # mapfinalsegvec to original labels
    for i in range(finalsegvec.max()+1):
        finalsegvec2[finalsegvec==i] = inlabs[i]
    outimg = iio2.make_image( target_image_mask, finalsegvec2 )

    return {
        'segmentation': outimg,
        'intensity': outimgi,
        'probabilityimages': probimgs
    }


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

def resize_to_min_size_(*tensors, dim = -1):
	size = min(t.shape[dim] for t in tensors)
	for t in tensors:
		if t.shape[dim] > size:
			sliced = t.narrow(dim, 0, size)
			t.set_(t.storage(), 0, sliced.size(), sliced.stride())

class SimpleVAD:
	def __init__(self,
	             kernel_size_smooth_silence: int = 4096,
	             kernel_size_smooth_signal: int = 128,
	             kernel_size_smooth_speaker: int = 4096,
	             silence_absolute_threshold: float = 0.05,
	             silence_relative_threshold: float = 0.2,
	             eps: float = 1e-9,
	             normalization_percentile: float = 0.9):
		self.kernel_size_smooth_silence = kernel_size_smooth_silence
		self.kernel_size_smooth_signal = kernel_size_smooth_signal
		self.kernel_size_smooth_speaker = kernel_size_smooth_speaker
		self.silence_absolute_threshold = silence_absolute_threshold
		self.silence_relative_threshold = silence_relative_threshold
		self.eps = eps
		self.normalization_percentile = normalization_percentile
		self.input_type = torch.tensor
		self.input_dtype = 'float32'

	def detect(self, signal: shapes.BT, allow_overlap: bool = False) -> shapes.BT:
		assert len(signal) <= 2

		padding = self.kernel_size_smooth_signal // 2
		stride = 1
		smoothed_for_diff = F.max_pool1d(signal.abs().unsqueeze(1), self.kernel_size_smooth_signal, stride=stride, padding=padding).squeeze(1)

		padding = self.kernel_size_smooth_silence // 2
		stride = 1

		# dilation
		smoothed_for_silence = F.max_pool1d(signal.abs().unsqueeze(1), self.kernel_size_smooth_silence, stride=stride, padding=padding).squeeze(1)

		# erosion
		smoothed_for_silence = -F.max_pool1d(-smoothed_for_silence.unsqueeze(1), self.kernel_size_smooth_silence, stride=stride, padding=padding).squeeze(1)

		# primitive VAD
		signal_max = smoothed_for_diff.kthvalue(int(self.normalization_percentile * smoothed_for_diff.shape[-1]), dim=-1, keepdim=True).values
		silence_absolute = smoothed_for_silence < self.silence_absolute_threshold
		silence_relative = smoothed_for_silence / (self.eps + signal_max) < self.silence_relative_threshold
		silence = silence_absolute | silence_relative

		if allow_overlap or len(signal) == 1:
			speech = ~silence
		else:
			diff_flat = smoothed_for_diff[0] - smoothed_for_diff[1]
			speaker_id_bipole = diff_flat.sign()

			padding = self.kernel_size_smooth_speaker // 2
			stride = 1
			speaker_id_bipole = F.avg_pool1d(speaker_id_bipole.view(1, 1, -1), kernel_size=self.kernel_size_smooth_speaker, stride=stride, padding=padding).view(-1).sign()

			# removing 1 sample silence at 1111-1-1-1-1 boundaries, replace by F.conv1d (patterns -101, 10-1)
			speaker_id_bipole = torch.where((speaker_id_bipole == 0) & (F.avg_pool1d(speaker_id_bipole.abs().view(1, 1, -1), kernel_size=3, stride=1, padding=1).view(-1) == 2 / 3) & (
						F.avg_pool1d(speaker_id_bipole.view(1, 1, -1), kernel_size=3, stride=1, padding=1).view(-1) == 0), torch.ones_like(speaker_id_bipole), speaker_id_bipole)

			resize_to_min_size_(silence, speaker_id_bipole, dim=-1)

			bipole = torch.tensor([1, -1], dtype=speaker_id_bipole.dtype, device=speaker_id_bipole.device)
			speech = (~silence) * (speaker_id_bipole.unsqueeze(0) == bipole.unsqueeze(1))
		speech = torch.cat([~speech.any(dim = 0).unsqueeze(0), speech])
		return speech

class WebrtcVAD:
	def __init__(self, aggressiveness: int = 3, sample_rate: int = 8_000, window_size: float = 0.01):
		assert sample_rate in [8_000, 16_000, 32_000, 48_000]
		assert window_size in [0.01, 0.02, 0.03]
		assert aggressiveness in [0, 1, 2, 3] # 3 is the most aggressive
		self.sample_rate = sample_rate
		self.window_size = window_size
		self.frame_len = int(window_size * sample_rate)
		self.aggressiveness = aggressiveness
		self.input_type = np.array
		self.input_dtype = 'int16'

	def detect(self, signal: shapes.BT, allow_overlap: bool = False) -> shapes.BT:
		assert signal.dtype == np.int16
		import webrtcvad
		speech_length = np.zeros(signal.shape, dtype = np.int)
		for channel in range(len(signal)):
			vad = webrtcvad.Vad(self.aggressiveness)
			frames = np.pad(signal[channel], (0, self.frame_len - signal.shape[-1] % self.frame_len), 'constant', constant_values = (0, 0))
			frames = bytearray(frames)
			start = None
			amount = 0

			for i in range(0, int(len(frames) / 2), self.frame_len):
				is_speech = vad.is_speech(frames[i * 2: (i + self.frame_len) * 2], self.sample_rate)
				if is_speech and start is None:
					start = i
					amount = 1
				elif is_speech:
					amount += 1
				elif not is_speech and start is not None:
					speech_length[channel, start: start + amount * self.frame_len] = amount * self.frame_len
					start = None
					amount = 0

			if start is not None:
				speech_length[channel, start: start + amount * self.frame_len] = amount * self.frame_len

		if allow_overlap:
			speech = speech_length > 0
		else:
			speech_max_length = speech_length.max(axis=0)
			speech = (speech_length == speech_max_length[np.newaxis, :]) & (speech_max_length != 0)
		speech = np.vstack([~speech.any(axis = 0), speech])
		return speech

class SileroVAD:
	def __init__(self, sample_rate: int = 8_000, use_micro = True, device = 'cpu'):
		self.device = device
		self.sample_rate = sample_rate
		if sample_rate == 8_000:
			assert use_micro, 'Only "micro" model exists for 8 kHz sample rate.'
			self.model_name = 'silero_vad_micro_8k'
		elif sample_rate == 16_000 and use_micro:
			self.model_name = 'silero_vad_micro'
		elif sample_rate == 16_000 and not use_micro:
			self.model_name = 'silero_vad'
		else:
			raise RuntimeError(f'No model exist for sample rate {sample_rate} Hz.')

		self.input_type = torch.tensor
		self.input_dtype = 'float32'

	@functools.lru_cache()
	def _get_model(self):
		model, utils = torch.hub.load(repo_or_dir='snakers4/silero-vad', model=self.model_name, batch_size=2000)
		get_speech_ts, _, _, _, _, _ = utils
		return model.to(self.device), get_speech_ts

	def detect(self, signal: shapes.BT, allow_overlap: bool = False) -> shapes.BT:
		signal = signal.to(self.device)
		model, get_speech_ts = self._get_model()
		speech_length = torch.zeros_like(signal, dtype = torch.int64)
		for i, channel_signal in enumerate(signal):
			intervals = get_speech_ts(channel_signal, model)
			for interval in intervals:
				speech_length[i, interval['start']:interval['end']] = torch.arange(0, interval['end'] - interval['start'], dtype = torch.int64)

		if allow_overlap:
			speech = speech_length > 0
		else:
			speech_max_length = speech_length.amax(dim=0)
			speech = (speech_length == speech_max_length.unsqueeze(0)) & (speech_max_length != 0)
		speech = torch.cat([~speech.any(dim = 0).unsqueeze(0), speech])
		return speech


from item import Weapon
import pygame

# Inventory class. For keeping track of who has what.
class Inventory:

    def __init__(self):
        self.items = []
        self.main_hand = Weapon(pygame.image.load("Image_Assets\\meter_1.png"), 0, 0, 0)
        self.off_hand = Weapon(pygame.image.load("Image_Assets\\meter_1.png"), 0, 0, 0)

    def add_item(self, item, quantity=1):
        for i in self.items:
            if i[0] == item.name:
                i[1] += quantity
                return
        self.items.append([item.name, quantity])

    def use_item(self, hud, item, quantity=1):
        for i in self.items:
            if i[0] == item.name:
                if i[1] >= quantity:
                    i[1] -= quantity
                    item.use(hud, quantity)
                else:
                    print('Error: Not enough items to use')
                return

    def set_main_hand(self, item):
        self.main_hand = item
        return

    def set_off_hand(self, item):
        self.off_hand = item


#1744 수 묶기

import sys

n = int(sys.stdin.readline())

pos, neg, zeroCnt, oneCnt = [], [], 0, 0

for _ in range(n):
    k = int(sys.stdin.readline())
    if k == 1:
        oneCnt += 1
    elif k > 0:
        pos.append(k)
    elif k < 0:
        neg.append(k)
    else:
        zeroCnt += 1

pos.sort(reverse=True)
neg.sort()

result = 0

i = 0
while i+1 < len(pos):
    result += pos[i]*pos[i+1]
    i += 2

if i < len(pos):
    result += pos[i]

i = 0
while i+1 < len(neg):
    result += neg[i]*neg[i+1]
    i += 2

if i < len(neg) and zeroCnt == 0:
    result += neg[i]

result += oneCnt
print(result)