import jinja2
import os
import webapp2
import logging
import time
from google.appengine.api import memcache
from google.appengine.ext import db

jinja_environment = jinja2.Environment(
    loader = jinja2.FileSystemLoader(os.path.dirname(__file__)),
    autoescape = True)

class Blog(db.Model):
    subject = db.StringProperty(required = True)
    content = db.TextProperty(required = True)
    created = db.DateTimeProperty(auto_now_add = True)

ALL_BLOGS_CACHE_KEY = 'all_blogs'
LAST_QUERIED_CACHE_KEY = 'last_queried'

class ProblemSet3(webapp2.RequestHandler):
    template = jinja_environment.get_template('ProblemSet3.html')
    def get(self):
        blogs = memcache.get(ALL_BLOGS_CACHE_KEY)
        last_queried = memcache.get(LAST_QUERIED_CACHE_KEY)
        if blogs is None:
            logging.error('DB QUERY')
            blogs = db.GqlQuery('SELECT * FROM Blog ORDER BY created DESC')
            blogs = list(blogs)
            memcache.set(ALL_BLOGS_CACHE_KEY, blogs)
            last_queried = time.time()
            memcache.set(LAST_QUERIED_CACHE_KEY, last_queried)
        template_values = {
            'blogs': blogs,
            'time_past': str(int(time.time() - float(last_queried)))
            }
        self.response.out.write(self.template.render(template_values))

class ProblemSet3_NewPost(webapp2.RequestHandler):
    template = jinja_environment.get_template('ProblemSet3_NewPost.html')
    def get(self):
        self.response.out.write(self.template.render())
    def post(self):
        blog_subject = self.request.get('subject')
        blog_content = self.request.get('content')
        if blog_subject and blog_content:
            blog = Blog(subject = blog_subject, content = blog_content)
            blog.put()
            blog_id = str(blog.key().id())
            memcache.set(ALL_BLOGS_CACHE_KEY, None)
            self.redirect('/ps3/' + blog_id)
        else:
            template_values = {
                'subject': blog_subject,
                'content': blog_content,
                'error': 'Both subject and content are required.',
                }
            self.response.out.write(self.template.render(template_values))

class ProblemSet3_Post(webapp2.RequestHandler):
    template = jinja_environment.get_template('ProblemSet3_Post.html')
    def get(self, blog_id):
        blog_cache_key = 'permalink_' + blog_id
        last_queried_cache_key = 'last_queried_' + blog_id
        blog = memcache.get(blog_cache_key)
        if blog is None:
            blog = Blog.get_by_id(int(blog_id))
            memcache.set(blog_cache_key, blog)
            last_queried = time.time()
            memcache.set(last_queried_cache_key, last_queried)
        else:
            last_queried = memcache.get(last_queried_cache_key)
        template_values = {
            'subject': blog.subject,
            'created': blog.created,
            'content': blog.content,
            'time_past': str(int(time.time() - float(last_queried)))
            }
        self.response.out.write(self.template.render(template_values))


'''
Finding the greatest common divisor,
eg :
input:
1000000 5
output:
5
'''

a, b = [int(i) for i in input().split()]
lis = list()
for i in range(1,a):
    if a%i == 0 and b%i == 0:
        lis.append(i)
print(lis[-1])


"""面试题36. 二叉搜索树与双向链表（中序遍历） 左中右

"""
class Solution:
    def treeToDoublyList(self, root: 'Node') -> 'Node':

        # 打印中序遍历
        def dfs(cur):
            if not cur:
                return
            dfs(cur.left)  # 递归左子树
            if self.pre:
                self.pre.right, cur.left = cur, self.pre
            else:
                self.head = cur
            self.pre = cur
            # print(root.val)  # 根
            dfs(cur.right)  # 右

        if not root:
            return
        self.pre = None
        dfs(root)
        # 将尾节点和头节点连接起来
        self.pre.right, self.head.left = self.head, self.pre
        return self.head

剑指offer/36_二叉搜索树与双向链表.py

36_二叉搜索树与双向链表.py


from typing import Any, Awaitable, Callable, Dict

from aiogram.dispatcher.middlewares.base import BaseMiddleware

from ..protocols.telegram_user_event import TelegramUserEvent
from ..utils.dispatcher import Dispatcher

class ServicesDIMiddleware(BaseMiddleware):
    def __init__(self, dispatcher: Dispatcher):
        self.dispatcher = dispatcher

    async def __call__(
        self,
        handler: Callable[[TelegramUserEvent, Dict[str, Any]], Awaitable[Any]],
        event: TelegramUserEvent,
        data: Dict[str, Any],
    ) -> Any:
        data.update(self.dispatcher.services._services)
        return await handler(event, data)


import backtrader as bt
import message as message
import datetime

'''双均线'''
class SmaCross(bt.Strategy):
    # 定义参数
    params = dict(
        fast_period=10,  # 快速移动平均期数
        slow_period = 60,)  # 慢速移动平均期数

    def __init__(self):
        # 定义快速移动平均线指标
        self.fastMA = bt.indicators.SMA(period=self.params.fast_period)

        # 定义慢速移动平均线指标
        self.slowMA = bt.indicators.SMA(period=self.params.slow_period)

        # 定义移动均线交叉信号指标
        self.crossover = bt.ind.CrossOver(self.fastMA, self.slowMA)

        self.order = None    # 设置订单引用，用于取消以往发出的尚未执行的订单

        self.message_able = False
        self.message = "";

    def next(self): # 每个新bar结束时触发调用一次，相当于其他框架的 on_bar()方法

        self.cancel(self.order) # 取消以往未执行订单

        # if not self.position:  # 还没有仓位，才可以买
        #     if self.crossover > 0:  # 金叉
        #         # self.order = self.buy(size=100) # 创建市价买单，该单会在次日开盘以开盘价成交
        #         self.order = self.order_target_percent(target=0.8)
        #
        #
        # # 已有仓位，才可以卖
        # elif self.crossover < 0:  # 死叉
        #     # self.order = self.sell() # 创建市价卖单，该单会在次日开盘以开盘价成交
        #     self.order = self.order_target_value(target=0)

        # print(self.data0.datetime.date(0))
        # print(self.fastMA.get(), self.slowMA.get())

        # current_day
        if self.crossover < 0 and self.position:  # 死叉且有仓位
            self.order = self.order_target_value(target=0)
            self.message = "全部卖出"
            self.message_process()

        # 金叉且没有仓位
        if self.crossover > 0 and not self.position:
            self.order = self.order_target_percent(target=0.8)
            self.message = "全仓买入"
            self.message_process()

    def message_process(self):
        trade_day = self.data0.datetime.date(0)
        cur_date = datetime.datetime.now().date()
        # cur_date = datetime.datetime(2021, 11, 16).date()
        pre_date = cur_date + datetime.timedelta(days=-1)

        cur_time = datetime.datetime.now().time()
        time_16 = datetime.time(16, 0)
        time_9 = datetime.time(9, 30)

        compare_date = cur_date
        if cur_time > time_16 :
            compare_date = cur_date
        if cur_time < time_9:
            compare_date = pre_date

        # 提醒信息
        if trade_day == compare_date:
            print(cur_date, self.message)
            if self.message_able:
                message.send_message(self.message)


from typing import Dict, List, TextIO, Optional, Set, Tuple

from overrides import overrides
import torch
from torch.nn.modules import Linear, Dropout
from torch.autograd import Variable
import torch.nn.functional as F

from allennlp.common import Params
from allennlp.common.checks import ConfigurationError
from allennlp.data import Vocabulary
from allennlp.modules import Seq2SeqEncoder, TimeDistributed, TextFieldEmbedder
from allennlp.modules.token_embedders import Embedding
from allennlp.models.model import Model
from allennlp.nn import InitializerApplicator, RegularizerApplicator
from allennlp.nn.util import get_text_field_mask, sequence_cross_entropy_with_logits
from allennlp.nn.util import get_lengths_from_binary_sequence_mask, viterbi_decode
from allennlp.nn.util import batched_index_select
from allennlp.training.metrics import SpanBasedF1Measure

from qasrl.modules.sentence_encoder import SentenceEncoder
from qasrl.modules.slot_sequence_generator import SlotSequenceGenerator
from qasrl.metrics.question_metric import QuestionMetric

@Model.register("qasrl_question")
class QuestionModel(Model):
    def __init__(self, vocab: Vocabulary,
                 sentence_encoder: SentenceEncoder,
                 question_generator: SlotSequenceGenerator,
                 initializer: InitializerApplicator = InitializerApplicator(),
                 regularizer: Optional[RegularizerApplicator] = None):
        super(QuestionModel, self).__init__(vocab, regularizer)
        self._sentence_encoder = sentence_encoder
        self._question_generator = question_generator
        if self._sentence_encoder.get_output_dim() != self._question_generator.get_input_dim():
            raise ConfigurationError(
                ("Input dimension of question generator (%s) must be " % self._question_generator.get_input_dim()) + \
                ("equal to the output dimension of the sentence encoder (%s)." % self._sentence_encoder.get_output_dim()))
        self.metric = QuestionMetric(vocab, self._question_generator.get_slot_names())

    def get_slot_names(self):
        return self._question_generator.get_slot_names()

    @overrides
    def forward(self,
                text: Dict[str, torch.LongTensor],
                predicate_indicator: torch.LongTensor,
                predicate_index: torch.LongTensor,
                **kwargs):
        # slot_name -> Shape: batch_size, 1
        gold_slot_labels = self._get_gold_slot_labels(kwargs)
        if gold_slot_labels is None:
            raise ConfigurationError("QuestionModel requires gold labels for teacher forcing when running forward. "
                                     "You may wish to run beam_decode instead.")
        # Shape: batch_size, num_tokens, self._sentence_encoder.get_output_dim()
        encoded_text, text_mask = self._sentence_encoder(text, predicate_indicator)
        # Shape: batch_size, self._sentence_encoder.get_output_dim()
        pred_rep = batched_index_select(encoded_text, predicate_index).squeeze(1)
        # slot_name -> Shape: batch_size, slot_name_vocab_size
        slot_logits = self._question_generator(pred_rep, **gold_slot_labels)

        batch_size, _ = pred_rep.size()

        # Shape: <scalar>
        slot_nlls, neg_log_likelihood = self._get_cross_entropy(slot_logits, gold_slot_labels)
        self.metric(slot_logits, gold_slot_labels, torch.ones([batch_size]), slot_nlls, neg_log_likelihood)
        return {**slot_logits, "loss": neg_log_likelihood}

    def beam_decode(self,
                    text: Dict[str, torch.LongTensor],
                    predicate_indicator: torch.LongTensor,
                    predicate_index: torch.LongTensor,
                    max_beam_size: int,
                    min_beam_probability: float,
                    clause_mode: bool = False):
        # Shape: batch_size, num_tokens, self._sentence_encoder.get_output_dim()
        encoded_text, text_mask = self._sentence_encoder(text, predicate_indicator)
        # Shape: batch_size, self._sentence_encoder.get_output_dim()
        pred_rep = batched_index_select(encoded_text, predicate_index).squeeze(1)
        return self._question_generator.beam_decode(pred_rep, max_beam_size, min_beam_probability, clause_mode)

    def get_metrics(self, reset: bool = False):
        return self.metric.get_metric(reset=reset)

    def _get_cross_entropy(self, slot_logits, gold_slot_labels):
        slot_xes = {}
        xe = None
        for slot_name in self.get_slot_names():
            slot_xe = F.cross_entropy(slot_logits[slot_name], gold_slot_labels[slot_name].squeeze(-1), reduction = "sum")
            slot_xes[slot_name] = slot_xe
            if xe is None:
                xe = slot_xe
            else:
                xe = xe + slot_xe
        return slot_xes, xe

    def _get_gold_slot_labels(self, instance_slot_labels_dict):
        # each of gold_slot_labels[slot_name] is of
        # Shape: batch_size
        gold_slot_labels = {}
        for slot_name in self.get_slot_names():
            if slot_name in instance_slot_labels_dict and instance_slot_labels_dict[slot_name] is not None:
                gold_slot_labels[slot_name] = instance_slot_labels_dict[slot_name].unsqueeze(-1)
        for slot_name in self.get_slot_names():
            if slot_name not in instance_slot_labels_dict or instance_slot_labels_dict[slot_name] is None:
                gold_slot_labels = None
        return gold_slot_labels


"""
Iris flower data set

https://en.wikipedia.org/wiki/Iris_flower_data_set
"""

from sklearn import tree
from sklearn.datasets import load_iris

iris_dataset = load_iris()
_classifier = tree.DecisionTreeClassifier()

# print the list of labels available for this dataset
print(list(iris_dataset.target_names))

classifier = _classifier.fit(
  iris_dataset.data,
  iris_dataset.target
)

examples = [
  [5.1, 3.5, 1.4, 0.2],
  [5.1, 3.5, 1.4, 0.2],
  [5.1, 3.5, 1.4, 0.2],
  [5.1, 3.5, 1.4, 0.2],
  [5.1, 3.5, 1.4, 1.5],
  [6.5, 3.0, 5.8, 2.2]
]
prediction = classifier.predict(examples)
print(prediction)
# the indices match the labels in `iris_dataset.target_names`


from .base import RendererBase

class TextRenderer(RendererBase):
    def __init__(self, only_results=True):
        self._only_results = only_results

    def render(self, dataset, epoch, cluster_ids, centroids):
        if self._only_results and epoch != RendererBase.FINAL:
            return

        print('Epoch {}'.format(epoch))
        print('Clusters ids = {}'.format(cluster_ids))
        print('Centroids = {}'.format(centroids))


from bs4 import BeautifulSoup
import re
import json
import numpy as np

def handle_file(file_name):
    items = list()
    with open(file_name, encoding='utf-8') as file:
        text = ''
        for row in file.readlines():
            text += row

        site = BeautifulSoup(text, 'html.parser')
        products = site.find_all('div', attrs={'class': 'product-item'})

        for product in products:
            item = dict()
            item['id'] = product.a['data-id']
            item['link'] = product.find_all('a')[1]['href']
            item['img_url'] = product.find_all('img')[0]['src']
            item['title'] = product.find_all('span')[0].get_text().strip()
            item['price'] = int(product.price.get_text().replace('₽', '').replace(' ', '').strip())
            item['bonus'] = int(product.strong.get_text().replace('+ начислим ', '').replace(' бонусов','').strip())
            props = product.ul.find_all('li')
            for prop in props:
                item[prop['type']] = prop.get_text().strip()
            items.append(item)

            # print(item)

    return items

items = []

for i in range(1, 45):
    file_name = f"zip_var_27_2/{i}.html"
    items += handle_file(file_name)

items = sorted(items, key=lambda x: x['id'], reverse=True)

with open('result_filtered_id.json', 'w', encoding='utf-8') as f:
    f.write(json.dumps(items))

filt_items = list()
for item in items:
    if(item['bonus'] >= 4000):
        filt_items.append(item)

with open('result_filtered_bonus.json', 'w', encoding='utf-8') as f:
    f.write(json.dumps(filt_items))

prices = list()

for item in items:
    prices.append(int(item['price']))

result_num = {}

result_num['max'] = str(np.max(prices))
result_num['min'] = str(np.min(prices))
result_num['avg'] = str(np.average(prices))
result_num['sum'] = str(np.sum(prices))
result_num['std'] = str(np.std(prices))

result_text = {}

for item in items:
    elem = item.get('matrix')
    if(elem != None):
        if(elem in result_text):
            result_text[elem] += 1
        else:
            result_text[elem] = 1

result_num['text'] = result_text
with open('result_math.json', 'w', encoding='utf-8') as f:
    json.dump(result_num, f, ensure_ascii=False)

handle_file("zip_var_27_2/27.html")


from cv2 import *
import numpy as np
from PIL import Image
import numpy
from matplotlib import pyplot as plt
from resizeimage import resizeimage

utezi = [1, 2, 4, 8, 16, 32, 64, 128]#za bite npr 00000101 pomnozis z 1 in z 4
uniformni = [0, 1, 2, 3, 4, 6, 7, 8, 12, 14, 15, 16, 24, 28, 30, 31, 32, 48, 56, 60, 62, 63, 64, 96, 112, 120, 124, 126, 127, 128, 129, 131, 135, 143, 159, 191, 192, 193, 195, 199, 207, 223, 224, 225, 227, 231, 239, 240, 241, 243, 247, 248, 249, 251, 252, 253, 254, 255]
UNI = []
histogramuniformni = []
LBPuniform = []
q=False
print(len(uniformni))

for a in range(0, 256): # priredis vrednosti 59 v UNI polje
    for x in range(0, len(uniformni)):
        if uniformni[x] == a:
            UNI.append(a)
            q = True
            break

    if q != True:
        UNI.append(59)
    else:
        q = False

print(UNI)

img = cv2.imread("na.jpg")

grayImg = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
LBPosnovna = grayImg.copy()
LBPusmerjenih = grayImg.copy()

height, width, channels = img.shape

def izracunajLBP():
    global grayImg, LBPosnovna

    for y in range(1, height):
        for x in range(1, width):
            if(y < height-1 and x < width-1):

                sredina = grayImg[y, x]
                zgorajLevo = grayImg[y-1, x-1]
                zgoraj = grayImg[y-1, x]
                zgorajDesno = grayImg[y-1, x+1]
                levo= grayImg[y, x-1]
                desno = grayImg[y, x+1]
                spodajLevo = grayImg[y+1, x-1]
                spodaj= grayImg[y+1, x]
                spodajDesno= grayImg[y+1, x+1]

                byte = []

                for i in [zgorajLevo, zgoraj, zgorajDesno, levo, desno, spodajLevo, spodaj, spodajDesno]:
                    if i >= sredina:
                        byte.append(1)
                    else:
                        byte.append(0)

                rezultat = 0

                for i in range(0, 8):
                    rezultat += utezi[i]*byte[i]

                LBPosnovna[y, x] = rezultat

def izracunajLBPuniform():
    global LBPosnovna, grayImg, UNI, histogramuniformni, LBPuniform
    Hst = [0] * 256

    LBPuniform = LBPosnovna.copy()

    for y in range(0, height):
        for x in range(0, width):
                Hst[UNI[LBPosnovna[y, x]]]+=1
                LBPuniform[y,x] = UNI[LBPosnovna[y,x]]

    for x in range(0, len(Hst)):
        if Hst[x] != 0:
            histogramuniformni.append(Hst[x])

def izracunajLBPusmerjenihGrad(d):
    global grayImg, LBPusmerjenih

    for y in range(1, height):
        for x in range(1, width):
            if (y < height - 1 and x < width - 1):

                zgorajLevo = grayImg[y - 1, x - 1]
                zgoraj = grayImg[y - 1, x]
                zgorajDesno = grayImg[y - 1, x + 1]
                levo = grayImg[y, x - 1]
                desno = grayImg[y, x + 1]
                spodajLevo = grayImg[y + 1, x - 1]
                spodaj = grayImg[y + 1, x]
                spodajDesno = grayImg[y + 1, x + 1]

                byte = []
                polja = [zgorajLevo, zgoraj, zgorajDesno, levo, desno, spodajLevo, spodaj, spodajDesno]

                stevec = 0

                for i in polja:
                    primerjaj = stevec+d

                    #print(primerjaj)
                    if primerjaj > 7:
                        primerjaj = (primerjaj - 7) - 1
                        #print("ta je index potem:")
                        #print(primerjaj)

                    if i >= polja[primerjaj]:
                        byte.append(1)
                    else:
                        byte.append(0)
                    stevec += 1

                rezultat = 0

                for i in range(0, 8):
                    rezultat += utezi[i] * byte[i]

                LBPusmerjenih[y, x] = rezultat

def pridobiKote(x, y):
    if x == 0:
        x=1
    kot = np.round(np.arctan2(y, x) * (180/np.pi))

    return kot

pridobiKote = np.vectorize(pridobiKote)

def gradientX(G, h, w):
    Gradient = G.copy()

    for x in range(h):
        for y in range(w):
            if (x == h-1 or y == w-1):
                Gradient[x][y] = 0
            else:
                Gradient[x][y] = abs(int(G[x][y -1]*(-1)) + int(G[x][y+1])) #[-1,0,1] pomnozis pa sestejes

    return Gradient

def gradientY(G, h, w):
    Gradient = G.copy()

    for x in range(h):
        for y in range(w):
            if (x == h-1 or y == w-1):
                Gradient[x][y] = 0
            else:
                Gradient[x][y] = abs(int(G[x-1][y] * (-1)) + int(G[x+1][y]))  # [[0,-1,0],[0,0,0],[0,1,0]] pomnozis pa sestejes

    return Gradient

def HOG(bins, cellsize, regionsize):
    global grayImg
    widthR = width
    heightR = height

    while(True): #izracunam da je sirina slike deljiva z cellsize
        if widthR % cellsize == 0:
            break;
        else:
            widthR+=1

    while (True):
        if heightR % cellsize == 0:
            break;
        else:
            heightR += 1

    print(heightR,widthR)

    imgResized = cv2.resize(grayImg, (widthR, heightR))

    Gx = np.asarray(imgResized).copy()
    Gy = np.asarray(imgResized).copy()

    Gx = gradientX(Gx, heightR, widthR)
    Gy = gradientY(Gy, heightR, widthR)

    Gradient = np.round(np.sqrt(np.multiply(Gx, Gx) + np.multiply(Gy, Gy)))

    A = pridobiKote(Gx, Gy)

    razmakBina = 180/bins

    '''for Y in range(heightR):
        for X in range(widthR):
            if A[Y][X] > 80:
                print(A[Y][X])
    '''
    stevec = 0
    koncneVrenosti = []

    for regijaY in range(0, heightR-cellsize, cellsize):
        for regijaX in range(0, widthR-cellsize, cellsize):
            stevec+=1
            Hist = [[0.0] * bins for i in range(regionsize * regionsize)]
            index1Hisotgrama = 0
            vsotaVrednosti = 0

            zactekRegijeY = regijaY
            zactekRegijeX = regijaX

            konecRegijeX = regijaX+ (cellsize * regionsize)
            konecRegijeY = regijaY+ (cellsize * regionsize)

            for celY in range(zactekRegijeY, konecRegijeY, cellsize):
                for celX in range(zactekRegijeX, konecRegijeX, cellsize):

                    zacetekCeliceY = celY
                    zacetekCeliceX = celX

                    konecCeliceY = celY + cellsize
                    konecCeliceX = celX + cellsize

                    for Y in range(zacetekCeliceY, konecCeliceY):
                        for X in range(zacetekCeliceX, konecCeliceX):
                            kot = A[Y, X]
                            gradient = Gradient[Y, X]

                            if (kot > razmakBina):
                                index = np.ceil((kot / razmakBina))
                                ostanek1 = index - (kot / razmakBina)
                                trenutni = (1 - ostanek1) * gradient
                                prejsni = ostanek1 * gradient
                            else:
                                index = np.ceil((kot / razmakBina))
                                ostanek1 = (kot / razmakBina)
                                prejsni = (1 - ostanek1) * gradient
                                trenutni = ostanek1 * gradient

                            Hist[index1Hisotgrama][int(index)] += trenutni
                            Hist[index1Hisotgrama][int(index - 1)] += prejsni

                    index1Hisotgrama += 1

            for histogram in range(0, regionsize * regionsize):
                for steviloHistggrama in range(0, bins):
                    vsotaVrednosti += np.multiply(Hist[histogram][steviloHistggrama],Hist[histogram][steviloHistggrama])

                    koncneVrenosti.append(Hist[histogram][steviloHistggrama])
            print(Hist)
            L = np.sqrt(vsotaVrednosti)

            print(L)

    print(koncneVrenosti)

    print(len(koncneVrenosti))
    print(stevec)

izracunajLBP()
izracunajLBPuniform()
izracunajLBPusmerjenihGrad(2)

HOG(9, 8, 2)

cv2.imshow("LBP osnovna", LBPosnovna)
cv2.imshow("LBP unfirom", LBPuniform)
cv2.imshow("LBP usmerjenih", LBPusmerjenih)

histogram = cv2.calcHist([LBPosnovna],[0],None,[256],[0,256])
sum = histogram.cumsum()#komulativno sesteje vse vrednosti histograma
normaliziranHistogram = (sum * histogram.max()) / sum.max()

plt.plot(normaliziranHistogram, color = 'g')
plt.hist(LBPosnovna.flatten(),256,[0,256])#speremnis 256 v 59 za uniform
plt.title("LBP osnovno")
plt.show()

cv2.waitKey(0)
cv2.destroyAllWindows()


### Pounds to Kilograms Converter
### by Andrew Kramer
#

"""

This program asks the user to enter a weight in pounds, converts the weight to kilograms, and displays the result.

"""
### PSEUDOCODE
"""

Define the main function:

- Prompt user to enter pounds
- Input pounds
- Convert pounds into kilograms with the following equation
- Multiply pounds by 0.45359237 ( POUNDS_TO_KILOGRAMS )
- Display result with entered pounds and calculated kilograms

"""

def main():

    POUNDS_TO_KILOGRAMS = 0.45359237                          # conversion formula constant

    x_Pounds = float(input('Enter the pounds: '))              # user is prompted to input pounds
    x_Kilograms = (x_Pounds) * POUNDS_TO_KILOGRAMS            # x_Kilograms variable established with conversion formula

    print(f'{x_Pounds} pounds is {x_Kilograms:.3f} kilograms') # display calculated result

main()


#!/usr/bin/env python3

r"""
This file contains functions which are useful for processing BMC dumps.
"""

import imp
import os
import sys

import bmc_ssh_utils as bsu
import gen_misc as gm
import gen_print as gp
import gen_robot_keyword as grk
from robot.libraries.BuiltIn import BuiltIn

base_path = (
    os.path.dirname(os.path.dirname(imp.find_module("gen_robot_print")[1]))
    + os.sep
)
sys.path.append(base_path + "data/")
import variables as var  # NOQA

def get_dump_dict(quiet=None):
    r"""
    Get dump information and return as an ordered dictionary where the keys
    are the dump IDs and the values are the full path names of the dumps.

    Example robot program call:

    ${dump_dict}=  Get Dump Dict
    Rprint Vars  dump_dict

    Example output:

    dump_dict:
      [1]:
      /var/lib/phosphor-debug-collector/dumps/1/obmcdump_1_1508255216.tar.xz
      [2]:
      /var/lib/phosphor-debug-collector/dumps/2/obmcdump_2_1508255245.tar.xz
      [3]:
      /var/lib/phosphor-debug-collector/dumps/3/obmcdump_3_1508255267.tar.xz
      [4]:
      /var/lib/phosphor-debug-collector/dumps/4/obmcdump_4_1508255283.tar.xz

    Description of argument(s):
    quiet                           If quiet is set to 1, this function will
                                    NOT write status messages to stdout.
    """

    quiet = int(gp.get_var_value(quiet, 1))
    cmd_buf = "find /var/lib/phosphor-debug-collector/ -maxdepth 4 -type f"
    output, stderr, rc = bsu.bmc_execute_command(cmd_buf, quiet=quiet)

    BuiltIn().log_to_console(output)
    return output.split("\n")

def valid_dump(dump_id, dump_dict=None, quiet=None):
    r"""
    Verify that dump_id is a valid.  If it is not valid, issue robot failure
    message.

    A dump is valid if the indicated dump_id refers to an existing dump with a
    valid associated dump file.

    Description of argument(s):
    dump_id                         A dump ID (e.g. "1", "2", etc.)
    dump_dict                       A dump dictionary such as the one returned
                                    by get_dump_dict.  If this value is None,
                                    this function will call get_dump_dict on
                                    the caller's behalf.
    quiet                           If quiet is set to 1, this function will
                                    NOT write status messages to stdout.
    """

    if dump_dict is None:
        dump_dict = get_dump_dict(quiet=quiet)

    if dump_id not in dump_dict:
        message = (
            "The specified dump ID was not found among the existing"
            + " dumps:\n"
        )
        message += gp.sprint_var(dump_id)
        message += gp.sprint_var(dump_dict)
        BuiltIn().fail(gp.sprint_error(message))

    if not dump_dict[dump_id].endswith("tar.xz"):
        message = (
            'There is no "tar.xz" file associated with the given'
            + " dump_id:\n"
        )
        message += gp.sprint_var(dump_id)
        dump_file_path = dump_dict[dump_id]
        message += gp.sprint_var(dump_file_path)
        BuiltIn().fail(gp.sprint_error(message))

def scp_dumps(targ_dir_path, targ_file_prefix="", dump_dict=None, quiet=None):
    r"""
    SCP all dumps from the BMC to the indicated directory on the local system
    and return a list of the new files.

    Description of argument(s):
    targ_dir_path                   The path of the directory to receive the
                                    dump files.
    targ_file_prefix                Prefix which will be prepended to each
                                    target file's name.
    dump_dict                       A dump dictionary such as the one returned
                                    by get_dump_dict.  If this value is None,
                                    this function will call get_dump_dict on
                                    the caller's behalf.
    quiet                           If quiet is set to 1, this function will
                                    NOT write status messages to stdout.
    """

    targ_dir_path = gm.add_trailing_slash(targ_dir_path)

    if dump_dict is None:
        dump_list = get_dump_dict(quiet=quiet)

    status, ret_values = grk.run_key("Open Connection for SCP", quiet=quiet)

    dump_file_list = []
    for file_path in dump_list:
        targ_file_path = (
            targ_dir_path + targ_file_prefix + os.path.basename(file_path)
        )
        status, ret_values = grk.run_key(
            "scp.Get File  " + file_path + "  " + targ_file_path, quiet=quiet
        )
        dump_file_list.append(targ_file_path)

    return dump_file_list


import arcade
import random

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

SPRITE_SCALING_COIN = 2
SPRITE_SCALING_PLAYER = 0.2
COIN_COUNT = 50

coin = arcade.Sprite("coin_01.png", SPRITE_SCALING_COIN)

class MyGame(arcade.Window):
    """ Main application class. """

    def __init__(self, width, height):
        super().__init__(width, height)

        arcade.set_background_color(arcade.color.AMAZON)

    def setup(self):
        """ Set up the game and initialize the variables. """

        # Create the sprite lists
        self.player_list = arcade.SpriteList()
        self.coin_list = arcade.SpriteList()

        # Score
        self.score = 0

        # Set up the player
        # Character image from kenney.nl
        self.player_sprite = arcade.Sprite("character.png", SPRITE_SCALING_PLAYER)
        self.player_sprite.center_x = 50 # Starting position
        self.player_sprite.center_y = 50
        self.player_list.append(self.player_sprite)

        # Create the coins
        for i in range(COIN_COUNT):

            # Create the coin instance
            # Coin image from kenney.nl
            coin = arcade.Sprite("coin_01.png", SPRITE_SCALING_COIN)

            coin.height = 200
            coin.width = 200

            # Position the coin
            # coin.center_x = random.randrange(1, SCREEN_WIDTH / 2)
            # coin.center_y = random.randrange(1, SCREEN_HEIGHT / 2)

            # Add the coin to the lists
            self.coin_list.append(coin)

    def on_draw(self):
        """ Render the screen. """
        arcade.start_render()
        # Your drawing code goes here
        self.coin_list.draw()
        self.player_list.draw()

    def update(self, delta_time):
        """ All the logic to move, and the game logic goes here. """
        pass

def main():
    game = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT)
    game.setup()
    arcade.run()

if __name__ == "__main__":
    main()


import json
import logging
from datetime import datetime

import redis
from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.postgres.search import SearchVector
from django.db.models import Q
from django.db.models.functions import Length
from django.http import JsonResponse, HttpResponseForbidden
from django.shortcuts import get_object_or_404
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from django_ratelimit.decorators import ratelimit
from .forms import CustomUserCreationForm, CustomAuthenticationForm

from .forms import StartConversationForm
from .models import Conversation, CustomUser

logger = logging.getLogger(__name__)

# ---------------------------- Register ----------------------------

@csrf_exempt
@ratelimit(key='ip', rate='5/h', method='POST', block=True)
def register(request):
    if request.method == 'POST':
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            logger.info(f"User '{user.email}' registered successfully.")
            return redirect('chat:conversations_list')
        else:
            logger.error("Form submission is not valid. Errors:")
            for field, errors in form.errors.items():
                for error in errors:
                    logger.error(f"{field}: {error}")
    else:
        form = CustomUserCreationForm()

    return render(request, 'users/authentication/register.html', {'form': form})

# ---------------------------- Login ----------------------------

@csrf_exempt
@ratelimit(key='ip', rate='10/m', method='POST', block=True)
def user_login(request):
    if request.method == 'POST':
        form = CustomAuthenticationForm(data=request.POST)
        if form.is_valid():
            user = form.get_user()
            login(request, user)
            logger.info(f"User '{user.email}' logged in successfully.")
            return redirect('chat:conversations_list')
        else:
            logger.error("Invalid login credentials. Errors:")
            for field, errors in form.errors.items():
                for error in errors:
                    logger.error(f"{field}: {error}")
            return render(request, 'users/authentication/login.html', {'form': form})
    else:
        form = CustomAuthenticationForm()

    return render(request, 'users/authentication/login.html', {'form': form})

# ---------------------------- Logout ----------------------------

def user_logout(request):
    logout(request)
    logger.info("User logged out.")
    return redirect('chat:login')

# ---------------------------- Conversation List ----------------------------

@login_required
@csrf_exempt
@ratelimit(key='user', rate='10/h', method='GET', block=True)
def conversations_list(request):
    try:
        conversations = Conversation.objects.filter(Q(user1=request.user) | Q(user2=request.user))

        conversation_data = []
        for conversation in conversations:
            if conversation.user1 == request.user:
                participant = conversation.user2
            else:
                participant = conversation.user1
            conversation_data.append({
                'id': conversation.id,
                'participant': participant,
            })
        logger.info(f"User '{request.user.email}' fetched conversation list successfully.")

    except Exception as e:
        conversation_data = []
        logger.error(f"An error occurred while fetching conversation list: {str(e)}")

    return render(request, 'chat/conversation/conversations_list.html', {'conversations': conversation_data})

# ---------------------------- Fetch messages from Redis ----------------------------

def fetch_messages_from_redis(conversation):
    try:
        redis_client = redis.StrictRedis(host="localhost", port=6379, db=0)
        conversation_key = f"conversation_{conversation.id}"
        message_strings = redis_client.lrange(conversation_key, 0, -1)
        messages = []
        for message_string in message_strings:
            message_data = json.loads(message_string.decode("utf-8"))
            message_data['formatted_timestamp'] = datetime.strptime(message_data['timestamp'],
                                                                    "%Y-%m-%d %H:%M:%S.%f").strftime("%m/%d/%Y %H:%M")
            messages.append(message_data)
        logger.info(f"Fetched messages for conversation {conversation.id}.")

    except redis.ConnectionError as e:
        messages = []
        logger.error(f"Redis connection error: {str(e)}")

    except Exception as e:
        messages = []
        logger.error(f"An error occurred while fetching messages from Redis: {str(e)}")

    finally:
        if 'redis_client' in locals():
            redis_client.close()

    return messages

# ---------------------------- Conversation View ----------------------------

@login_required
@csrf_exempt
@ratelimit(key='user', rate='5/m', method='GET', block=True)
def conversation_view(request, conversation_id):
    conversation = get_object_or_404(Conversation, id=conversation_id)

    if request.user not in [conversation.user1, conversation.user2]:
        return HttpResponseForbidden("You do not have permission to access this conversation.")

    participant = conversation.user2 if conversation.user1 == request.user else conversation.user1

    messages = fetch_messages_from_redis(conversation)

    return render(request, 'chat/conversation/conversation_view.html', {
        'conversation': conversation,
        'participant': participant,
        'messages': messages,
        'conversation_id': conversation_id,
    })

# ---------------------------- Start New Conversation ----------------------------

@login_required
@csrf_exempt
def start_conversation(request):
    if request.method == 'POST':
        form = StartConversationForm(request.POST)
        if form.is_valid():
            participants = form.cleaned_data['participants']
            existing_conversation = Conversation.objects.filter(
                Q(user1=request.user, user2=participants) | Q(user1=participants, user2=request.user)
            )

            if existing_conversation.exists():
                return redirect('chat:view_conversation', conversation_id=existing_conversation.first().id)
            else:
                conversation = Conversation.objects.create(user1=request.user, user2=participants)
                logger.info(f"Started a new conversation {conversation.id}.")
                return redirect('chat:view_conversation', conversation_id=conversation.id)
    else:
        form = StartConversationForm()

    return render(request, 'chat/conversation/conversation_start.html', {'form': form})

# ---------------------------- Search users by email ----------------------------

@login_required
@csrf_exempt
def search_users(request):
    try:
        if 'q' in request.GET:
            search_term = request.GET['q'].strip()
            if search_term:
                search_query = Q(email__icontains=search_term)
                users = CustomUser.objects.filter(search_query).exclude(id=request.user.id)[:10]
                user_data = [{'id': user.id, 'email': user.email} for user in users]
                return JsonResponse(user_data, safe=False)
        return JsonResponse([], safe=False)
    except Exception as e:
        return JsonResponse({'error': 'An error occurred while processing the request'}, status=500)


# def is used as normal
def incr():

    # create an initial value, i
    i = 1

    # while loop
    while True:

        # the value to return at each call
        yield i

        # the operation to perform on i at each call
        i += 1

inc = incr()

for i in inc:
	if i > 50:
		break
	else:
		print(i)


from random import *

class MemoryCell:
	def __init__(self, adr, cont):
		self.content = cont
		self.adress = adr

class Square:
	def __init__(self):
		self.label = ""
		self.adress0 = ""
		self.adress1 = None
		self.content = None

class Memory:
	def __init__(self, number):
		self.cells = []
		for i in range(number):
			c = MemoryCell(format(i,"08b"),randint(200000,9999999))
			self.cells.append(c)

class CacheMemory:
	def __init__(self,number):
		self.squares = []
		for i in range(number):
			self.squares.append(Square())


#base tensorflow, openmm

import numpy as np
import mdtraj as md
import matplotlib.pyplot as plt
# import tensorflow as tf
import os

import torch
import torch.optim as optim
from torch.autograd import Variable

def SGD(diff_vec, eigenvecs, Print = False, PrintRound = 1000, Iter = 100000):
        """
        do SGD for given diff_vec and eigenvectors to find to optimal collective motion

        :param diff_vec: the differential vector of two conformations, shape N
        :param eigenvecs: the tICs that are used to compose the OCM, shape N * m
        :param Print: whether to print loss during fitting
        :param PrintRound: the interval of each two print
        :param Iter: iterations of the SGD
        :return vec_combine: the normalized OCM we get based on given tICs
        :return alpha: the weight on each tICs to compose the OCM
        :return loss: the final loss, aka the cosine distance of the diffvec and the OCM
        """
        N = eigenvecs.shape[1]
        diff_vec_var = Variable(torch.DoubleTensor(diff_vec), requires_grad = False)
        diff_vec_var = diff_vec_var / torch.linalg.norm(diff_vec_var)
        eigenvec_var = Variable(torch.DoubleTensor(eigenvecs), requires_grad = False)
        alpha_var = Variable(torch.rand(N, 1, dtype = torch.double), requires_grad = True)

        optimizer = optim.Adam([alpha_var], lr=10, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=False)

        for i in range(Iter):
            optimizer.zero_grad()
            vec_combine = torch.matmul(eigenvec_var, alpha_var)
            loss = -torch.matmul(vec_combine.T, diff_vec_var) / torch.linalg.norm(vec_combine)
            if i % PrintRound == 0 and Print:
                print(loss.data)
            loss.backward()
            optimizer.step()
        alpha_var = alpha_var / torch.linalg.norm(vec_combine)
        alpha = alpha_var.detach().numpy()
        vec_combine = eigenvecs.dot(alpha)
        np.savetxt('./OCM.txt', vec_combine)
        print("loss=",loss.data.detach().numpy()[0])
        return vec_combine, alpha, loss.data.detach().numpy()[0]

'''
def SGD():
	data = np.loadtxt('./tICs.txt')
	f_pc1 = np.loadtxt('./PC1.txt')
	l = []
	f_tic = data[0:1500]
	n = len(f_tic)

	config = tf.ConfigProto()
	config.gpu_options.allow_growth = True
	config.allow_soft_placement = True
	config.log_device_placement = False
	sess = tf.Session(config=config)

	w0 = tf.Variable(tf.expand_dims(np.random.randn(n),0))
	tic = tf.constant(f_tic)
	pc1 = tf.expand_dims(f_pc1,0)
	vec = tf.matmul(w0,tic)

	LOSS = -(tf.reduce_sum(tf.multiply(vec,pc1))/tf.sqrt(tf.reduce_sum(tf.multiply(vec,vec))))

	X = tf.placeholder(tf.float32, shape=[None,None])
	#X2 = tf.placeholder(tf.float32,shape=[None])
	Y = tf.placeholder(tf.float32, shape=[None])
	tf.summary.scalar('loss_linear', LOSS)

	#Minimize
	learning_rate = tf.train.exponential_decay(0.2, 100000, 25000, 0.9, staircase=True)
	optimizer = tf.train.GradientDescentOptimizer(learning_rate)
	train = optimizer.minimize(LOSS)
	merged = tf.summary.merge_all()

	sess.run(tf.global_variables_initializer())
	#write=tf.summary.FileWriter('log',sess.graph)

	for step in range(100001):
	    loss_val, merg, W_val,_ = sess.run([LOSS,merged,w0,train],
	                                         feed_dict={X:f_tic,
	                                                    Y:f_pc1})

	l.append([n,loss_val, W_val])
	LOSS = loss_val
	assert LOSS < 0, 'Illegal combined vector with obtuse angle'
	weighted_tics = np.dot(W_val, f_tic)
	np.savetxt('./OCM.txt', weighted_tics)
'''

def proj(parm):
    data = np.loadtxt('./eq.txt')
    OCM = np.loadtxt('./OCM.txt')
    data = data - data[0]
    proj = np.dot(data, OCM)

    gap_low = np.percentile(proj, 5)
    gap_high = np.percentile(proj, 95)
    print(gap_low)
    print(gap_high)
    print(gap_high-gap_low)

    plt.scatter(range(len(data)), proj, s=10)
    plt.axhline(gap_high)
    plt.axhline(gap_low)
    plt.xlabel('frame')
    plt.ylabel('projection')
    plt.savefig('./proj_eq.png')
    plt.close()

    proj = proj.tolist()
    print(max(proj))
    print(min(proj))
    print(proj.index(max(proj)))
    print(proj.index(min(proj)))
    max_index = proj.index(max(proj))+1

    _load = md.load('./eq.dcd', top=parm)
    #_load.autoimage()
    _load.image_molecules()
    _load[max_index].save_amberrst7('./restart.rst7')

    return max(proj)-min(proj)
    #return gap_high-gap_low

parm1 = 'fixed.close.prmtop'
parm2 = 'fixed.open.prmtop'

'''
os.chdir('./close/')
SGD()
close_p = proj(parm=parm1)
print('projection of close:', close_p)
os.chdir('../open/')
SGD()
open_p = proj(parm=parm2)
print('projection of open', open_p)
'''

os.chdir('./close/')
diff_vec = np.loadtxt('./PC1.txt')
eigenvecs = np.loadtxt('./tICs.txt').T
SGD(diff_vec, eigenvecs)
close_p = proj(parm=parm1)
print('projection of close:', close_p)
os.chdir('../open/')
diff_vec = np.loadtxt('./PC1.txt')
eigenvecs = np.loadtxt('./tICs.txt').T
SGD(diff_vec, eigenvecs)
open_p = proj(parm=parm2)
print('projection of open', open_p)

os.chdir('../')
close_r  = md.load('./close/eq.rst7', top=parm1)
close_load_ca = md.load('./close/eq.rst7', top=parm1, atom_indices=close_r.topology.select('protein and name CA'))

open_r = md.load('./open/eq.rst7', top=parm2)
open_load_ca = md.load('./open/eq.rst7', top=parm2, atom_indices=open_r.topology.select('protein and name CA'))
close_load_ca.superpose(reference=open_load_ca, atom_indices=close_load_ca.topology.select('(resid 15 to 23 or resid 249 to 279 or resid 289 to 292 or resid 501 to 518 or resid 528 to 541 or resid 549 to 553) and name CA'))

RMSD = md.rmsd(close_load_ca, open_load_ca, 0)*10   #unit in Angstrom
print('RMSD: ',RMSD)

scale_s = 0.05*RMSD**2
scale_l = 0.09*RMSD**2
ss_close = 0.1*RMSD**2*close_p
ss_open = 0.1*RMSD**2*open_p
print('scaling factor: ', scale_s, scale_l)
print('step size: ', ss_close, ss_open)

import sampling
from sampling import run_bias
from sampling import run_eq

os.chdir('./close/')
run_bias(parm=parm1, crd='./restart.rst7', OCM_file='./OCM.txt', scaling=float(scale_s), ss=ss_close)

os.chdir('../open/')
run_bias(parm=parm2, crd='./restart.rst7', OCM_file='./OCM.txt', scaling=float(scale_s), ss=ss_open)

def load_bias1(parm, ss):
	ref = md.load('restart.rst7', top=parm)
	ca = ref.topology.select('protein and name CA')
	ref = md.load('restart.rst7', top=parm, atom_indices=ca)
	load = md.load('bias.dcd', top=parm, atom_indices=ca)
	load.superpose(reference=ref, atom_indices=ref.topology.select('(resid 15 to 23 or resid 249 to 279 or resid 289 to 292 or resid 501 to 518 or resid 528 to 541 or resid 549 to 553) and name CA'))
	data = load.xyz
	x,y,z = data.shape
	data = data.reshape(x, y*z)

	vec = np.loadtxt('./OCM.txt')
	xyz = ref.xyz[0].reshape(len(ca)*3,)
	target = xyz + ss*vec
	print(target.shape)
	data = data - target
	data = np.sqrt(np.dot(data, np.transpose(data)))
	dis = [data[i,i] for i in range(len(data))]
	sel = dis.index(min(dis))
	print('bias select: ', sel)

	_load = md.load('bias.dcd', top=parm)
	_load[sel].save_amberrst7('./bias_select.rst7')

'''
def load_bias2(parm, ss):
	ref = md.load('restart.rst7', top=parm)
	ca = ref.topology.select('protein and name CA')
	ref = md.load('restart.rst7', top=parm, atom_indices=ca)
	load = md.load('bias.dcd', top=parm, atom_indices=ca)
	load.superpose(reference=ref)
	data = load.xyz
	x,y,z = data.shape
	data = data.reshape(x, y*z)

	vec = np.loadtxt('./OCM.txt')
	xyz = ref.xyz[0].reshape(len(ca)*3,)
	data = data[:,i] - data[0,i]
	proj = np.dot(data, vec)

	dis = proj.tolist()
	sel = dis.index(min(dis))

	_load = md.load('bias.dcd', top=parm)
	_load[sel].save_amberrst7('./bias_select.rst7')
'''

def load_bias3(parm):
	_load = md.load('bias.dcd', top=parm)
	_load[-1].save_amberrst7('./bias_select.rst7')

os.chdir('../close/')
#_load = md.load('bias.dcd', top=parm1)
#_load[-1].save_amberrst7('./bias_select.rst7')
#load_bias1(parm=parm1, ss=close_p)
load_bias3(parm=parm1)

os.chdir('../open/')
#_load = md.load('bias.dcd', top=parm2)
#_load[-1].save_amberrst7('./bias_select.rst7')
#load_bias1(parm=parm2, ss=open_p)
load_bias3(parm=parm2)


from project.libs.response import ItemResp, ItemsResp
from project.libs.validators.request import validate_request
from project.product.entities import Category

from . import schemas
from .interfaces import ICategoryRepo, ICategoryUseCase
from .requests import (
    CreateCategoryRequest,
    DeleteCategoryRequest,
    FindCategoriesRequest,
    GetCategoryByIdRequest,
    UpdateCategoryRequest,
)

class CategoryUseCase(ICategoryUseCase):
    def __init__(self, repo: ICategoryRepo):
        self.repo = repo

    @validate_request(schema=schemas.FindCategoriesSchema)
    def find(self, req: FindCategoriesRequest) -> ItemsResp:
        return self.repo.find(req.search)

    @validate_request(schema=schemas.CreateCategorySchema)
    def create(self, req: CreateCategoryRequest):

        category = Category(
            name=req.name,
        )

        return self.repo.create(category)

    @validate_request(schema=schemas.UpdateCategorySchema)
    def update(self, req: UpdateCategoryRequest) -> ItemResp:

        resp = self.repo.get_by_id(
            id=req.id,
        )
        if not resp.ok:
            return resp

        category = resp.item
        category.name = req.name

        return self.repo.update(category)

    @validate_request(schema=schemas.GetCategoryByIdSchema)
    def get_by_id(self, req: GetCategoryByIdRequest) -> ItemResp:
        return self.repo.get_by_id(req.id)

    @validate_request(schema=schemas.GetCategoryByIdSchema)
    def delete(self, req: DeleteCategoryRequest) -> ItemResp:
        return self.repo.get_by_id(req.id)


from sys import argv
from math import sqrt

if __name__=='__main__':

    file_name = argv[1]
    fp = open(file_name,'r')
    for line in fp:
        matList= line.strip('\n').split(' ')
        l = len(matList)
        n = int(sqrt(l))
        romat = [' '.join([matList[j] for j in range(i,-1,-n)]) for i in range(l-n,l)]
        print(' '.join(romat))

'''
Matrix Rotation

Challenge Description:

You are given a 2D N×N matrix. Each element of the matrix is a letter: from ‘a’ to ‘z’. Your task is to rotate the matrix 90° clockwise:

a b c        g d a
d e f  =>    h e b
g h i        i f c

Input sample:

The first argument is a file that contains 2D N×N matrices, presented in a serialized form (starting from the upper-left element), one matrix per line. The elements of a matrix are separated by spaces.

For example:
a b c d
a b c d e f g h i j k l m n o p
a b c d e f g h i

Output sample:

Print to stdout matrices rotated 90° clockwise in a serialized form (same as in the input sample).

For example:
c a d b
m i e a n j f b o k g c p l h d
g d a h e b i f c
Constraints:

    The N size of the matrix can be from 1 to 10
    The number of test cases is 100
'''


"""
Point source fitting module.
Dependencies: pixell, enlib.pointsrcs, numpy, scipy
"""

from __future__ import print_function
from pixell import enmap,pointsrcs
import numpy as np
from scipy.stats import chi2
from scipy.interpolate import interp1d
try: from enlib import bench
except: pass

class Pfit(object):
    def __init__(self,shape,wcs,dec=None,ra=None,rbeam=None,div=None,ps=None,beam=None,iau=False,
                 n2d=None,totp2d=None,invert=False):
        Ny,Nx = shape[-2:]
        self.shape = shape
        self.wcs = wcs
        #assert Ny==N
        self.Ny = Ny
        self.Nx = Nx
        ncomp = 1 if len(shape)==2 else shape[0]
        assert ncomp==1 or ncomp==3
        self.ncomp = ncomp
        if totp2d is None:
            modlmap = enmap.modlmap(shape,wcs)
            if ps.ndim==1: ps = ps.reshape((1,1,ps.size))
            nells = ps.shape[-1]
            ps = ps[:ncomp,:ncomp,:]
            self.ells = np.arange(nells)
            cmb2d = np.zeros((ncomp,ncomp,Ny,Nx))
            for i in range(ncomp):
                for j in range(i,ncomp):
                    cmb2d[i,j] = cmb2d[j,i] = interp(self.ells,ps[i,j])(modlmap)
            beam = np.asarray(beam)
            if beam.ndim==0: beam2d = gauss_beam(modlmap,beam)
            elif beam.ndim==1:
                nells = beam.size
                self.ells = np.arange(nells)
                beam2d = maps.interp(self.ells,beam)(modlmap)
            elif beam.ndim==2: beam2d = beam
            self.ccov = stamp_pixcov_from_theory(Ny,Nx,
                                            enmap.enmap(cmb2d,wcs),
                                            n2d_IQU=0. if n2d is None else n2d,
                                            beam2d=beam2d,iau=iau,
                                            return_pow=False)
            if n2d is None:
                if div.ndim == 2: div = div[None,...]
                dncomp = div.shape[0]
                ncov = np.zeros((ncomp,ncomp,Ny*Nx,Ny*Nx))
                if dncomp==1:
                    # assuming div is inverse variance in intensity
                    # so Q and U should have x 1/2
                    ncovI = np.diag(1./div.reshape(-1))
                    ncov[0,0] = ncovI
                    if ncomp>1: ncov[1,1] = ncov[2,2] = ncovI*2.
                elif dncomp==3:
                    assert ncomp==dncomp
                    for i in range(dncomp): ncov[i,i] = 1./div[i].reshape(-1)
                else:
                    raise ValueError
                self.ccov += ncov
        else:
            self.ccov = fcov_to_rcorr(shape,wcs,totp2d,N)
        # --- Make sure that the pcov is in the right order vector(I,Q,U) ---
        # It is currently in (ncomp,ncomp,n,n) order
        # We transpose it to (ncomp,n,ncomp,n) order
        # so that when it is reshaped into a 2D array,
        # a row/column will correspond to an (I,Q,U) vector
        self.ccov = np.transpose(self.ccov,(0,2,1,3))
        self.ccov = self.ccov.reshape((ncomp*Ny*Nx,ncomp*Ny*Nx))
        if invert:
            from enlib import utils
            self.Cinv = np.linalg.inv(self.ccov)
            self.solver = lambda a,b: np.dot(self.Cinv ,b)
        else:
            self.Cinv = None
            self.solver = lambda a,b: Solver(self.ccov,u=None).solve(b)
        if dec is not None: self.update_template(dec,ra,rbeam)

    def update_template(self,dec,ra,rbeam):
        shape = self.shape
        wcs = self.wcs
        ncomp = self.ncomp
        Ny = self.Ny
        Nx = self.Nx
        self.template = pointsrcs.sim_srcs(shape[-2:], wcs, np.array(((dec,ra,1.),)), rbeam)
        self.funcs = []
        for i in range(ncomp):
            tzeros = np.zeros((ncomp*Ny*Nx,))
            tzeros[i*ncomp*Ny*Nx:(i+1)*ncomp*Ny*Nx] = self.template.reshape(-1)
            self.funcs.append(lambda x: tzeros.copy())

    def fit(self,imap=None,dec=None,ra=None,rbeam=None):
        if dec is not None: self.update_template(dec,ra,rbeam)
        ncomp = self.ncomp
        Ny = self.Ny
        Nx = self.Nx
        if imap is None:
            imap = self.imap
            Cy = self.Cy
        else:
            self.imap = imap
            C = self.ccov
            y = imap.reshape(-1)[:,None]
            Cy = self.solver(C,y)
            self.Cy = Cy
        pflux,cov,chisquare,_ = fit_linear_model(self.ells,imap.reshape(-1),self.ccov,funcs=self.funcs,dofs=None,Cinv=self.Cinv,Cy=Cy,solver=self.solver)
        pflux = pflux.reshape((ncomp,))
        cov = cov.reshape((ncomp,ncomp))
        fit = np.zeros((ncomp,Ny,Nx))
        for i in range(ncomp): fit[i] = self.template.copy()*pflux[i]
        return pflux,cov,fit,chisquare.reshape(-1)[0]

def ptsrc_fit(imap,dec,ra,rbeam,div=None,ps=None,beam=None,iau=False,
              n2d=None,totp2d=None):
    """Fit a point source to a square stamp.

    Args:
        imap: an ndmap of shape (ncomp,N,N) or (N,N) containing the
        point source. ncomp can be 1 (assumed intensity) or 3 (assumed
        I,Q,U).
        div: an ndmap of shape (ncomp,N,N) or (N,N) containing the
        inverse variance in each pixel.
        ra: Right ascension of point source in radians.
        dec: Declination of point source in radians.
        ps: CMB T,E,B power spectrum. Allowed shapes are (nells,) and
        (ncomp,ncomp,nells), starting at ell=0, in compatible units
        as the map.
        beam: The beam in the map specified either as a float (interpreted
        as FWHM in arcminutes) or as an (nells,) array containing the
        beam transfer function starting at ell=0 or (N,N)  array containing
        the 2D beam transfer function. This Fourier beam is
        used in the CMB power.
        rbeam: The beam in the map specified as either a float or
        [{r,val},npoint] array  containing the radial beam function.
        This beam is used in the point source template.
        n2d: Specify the I,Q,U noise (ncomp,ncomp,N,N) 2D power spectrum
        and ignore div.
        totp2d: Specify the total (ncomp,ncomp,N,N) 2D power spectrum
        of I,Q,U and ignore div, n2d, ps and beam.

    Returns:
        pflux: (ncomp,) specifying best fit peak flux
        var: (ncomp,ncomp,) specifying peak flux covarince.
        Warning: this number depends
        purely either on totp2d or on ps and div, and does not account for
        other sources of noise present in the map.
        fit: ndmap containing the best fit point source template.

    """
    shape,wcs = imap.shape, imap.wcs
    pfitter = Pfit(shape=shape,wcs=wcs,dec=dec,ra=ra,rbeam=rbeam,div=div,ps=ps,beam=beam,iau=iau,
              n2d=n2d,totp2d=totp2d)
    return pfitter.fit(imap)

"""
=============
HELPERS
=============
"""

# duplicated from orphics.maps
def gauss_beam(ell,fwhm):
    tht_fwhm = np.deg2rad(fwhm / 60.)
    return np.exp(-(tht_fwhm**2.)*(ell**2.) / (16.*np.log(2.)))

# duplicated from orphics.maps
def interp(x,y,bounds_error=False,fill_value=0.,**kwargs):
    return interp1d(x,y,bounds_error=bounds_error,fill_value=fill_value,**kwargs)

# duplicated from orphics.maps and orphics.pixcov
def rotate_pol_power(shape,wcs,cov,iau=False,inverse=False):
    """Rotate a 2D power spectrum from TQU to TEB (inverse=False) or
    back (inverse=True). cov is a (3,3,Ny,Nx) 2D power spectrum.
    WARNING: This function is duplicated from orphics.maps to make
    this module independent. Ideally, it should be implemented in
    enlib.enmap.
    """
    rot = np.zeros((3,3,cov.shape[-2],cov.shape[-1]))
    rot[0,0,:,:] = 1
    prot = enmap.queb_rotmat(enmap.lmap(shape,wcs), inverse=inverse, iau=iau)
    rot[1:,1:,:,:] = prot
    Rt = np.transpose(rot, (1,0,2,3))
    tmp = np.einsum("ab...,bc...->ac...",rot,cov)
    rp2d = np.einsum("ab...,bc...->ac...",tmp,Rt)
    return rp2d

# duplicated from orphics.pixcov
def stamp_pixcov_from_theory(Ny,Nx,cmb2d_TEB,n2d_IQU=0.,beam2d=1.,iau=False,return_pow=False):
    """Return the pixel covariance for a stamp N pixels across given the 2D IQU CMB power spectrum,
    2D beam template and 2D IQU noise power spectrum.
    """
    n2d = n2d_IQU
    cmb2d = cmb2d_TEB
    assert cmb2d.ndim==4
    ncomp = cmb2d.shape[0]
    assert cmb2d.shape[1]==ncomp
    assert ncomp==3 or ncomp==1

    wcs = cmb2d.wcs
    shape = cmb2d.shape[-2:]

    if ncomp==3: cmb2d = rotate_pol_power(shape,wcs,cmb2d,iau=iau,inverse=True)
    p2d = cmb2d*beam2d**2.+n2d
    if not(return_pow): return fcov_to_rcorr(shape,wcs,p2d,Ny,Nx)
    return fcov_to_rcorr(shape,wcs,p2d,Ny,Nx), cmb2d

# duplicated from orphics.pixcov
def fcov_to_rcorr(shape,wcs,p2d,Ny,Nx):
    """Convert a 2D PS into a pix-pix covariance
    """
    ncomp = p2d.shape[0]
    p2d *= np.prod(shape[-2:])/enmap.area(shape,wcs)
    ocorr = enmap.zeros((ncomp,ncomp,Ny*Nx,Ny*Nx),wcs)
    for i in range(ncomp):
        for j in range(i,ncomp):
            dcorr = ps2d_to_mat(p2d[i,j].copy(), Ny,Nx).reshape((Ny*Nx,Ny*Nx))
            ocorr[i,j] = dcorr.copy()
            if i!=j: ocorr[j,i] = dcorr.copy()
    return ocorr

# duplicated from orphics.stats
def fit_linear_model(x,y,ycov,funcs,dofs=None,deproject=True,Cinv=None,Cy=None,solver=None):
    """
    Given measurements with known uncertainties, this function fits those to a linear model:
    y = a0*funcs[0](x) + a1*funcs[1](x) + ...
    and returns the best fit coefficients a0,a1,... and their uncertainties as a covariance matrix
    """
    if solver is not None:
        s = solver
    else:
        s = solve if deproject else np.linalg.solve
    C = ycov
    y = y[:,None]
    A = np.zeros((y.size,len(funcs)))
    for i,func in enumerate(funcs):
        A[:,i] = func(x)
    CA = s(C,A) if Cinv is None else np.dot(Cinv,A)
    cov = np.linalg.inv(np.dot(A.T,CA))
    if Cy is None: Cy = s(C,y) if Cinv is None else np.dot(Cinv,y)
    b = np.dot(A.T,Cy)
    X = np.dot(cov,b)
    YAX = y - np.dot(A,X)
    CYAX = s(C,YAX) if Cinv is None else np.dot(Cinv,YAX)
    chisquare = np.dot(YAX.T,CYAX)
    dofs = len(x)-len(funcs)-1 if dofs is None else dofs
    pte = 1 - chi2.cdf(chisquare, dofs)
    return X,cov,chisquare/dofs,pte

# duplicated from orphics.stats
class Solver(object):
    """
    Calculate Cinv . x
    """
    def __init__(self,C,u=None):
        """
        C is an (NxN) covariance matrix
        u is an (Nxk) template matrix for rank-k deprojection
        """
        N = C.shape[0]
        if u is None: u = np.ones((N,1))
        Cinvu = np.linalg.solve(C,u)
        self.precalc = np.dot(Cinvu,np.linalg.solve(np.dot(u.T,Cinvu),u.T))
        self.C = C
    def solve(self,x):
        Cinvx = np.linalg.solve(self.C,x)
        correction = np.dot(self.precalc,Cinvx)
        return Cinvx - correction

# duplicated from orphics.stats
def solve(C,x,u=None):
    """
    Typically, you do not want to invert your covariance matrix C, but really just want
    Cinv . x , for some vector x.
    You can get that with np.linalg.solve(C,x).
    This function goes one step further and deprojects a common mode for the entire
    covariance matrix, which is often what is needed.
    """
    s = Solver(C,u=u)
    return s.solve(x)

### ENMAP HELPER FUNCTIONS AND CLASSES
# These have been copied from enlib.jointmap since that module
# requires compilation (but these functions don't). They are
# also duplicated in orphics.pixcov

def map_ifft(x): return enmap.ifft(x).real
def corrfun_thumb(corr, Ny,Nx):
    tmp = np.roll(np.roll(corr, Ny, -1)[...,:2*Ny], Nx, -2)[...,:2*Nx,:]
    return np.roll(np.roll(tmp, -Ny, -1), -Nx, -2)

def corr_to_mat(corr, Ny, Nx):
    res = enmap.zeros([Ny,Nx,Ny,Nx],dtype=corr.dtype)
    for i in range(Ny):
        tmp = np.roll(corr, i, 0)[:Ny,:]
        for j in range(Nx):
            res[i,j] = np.roll(tmp, j, 1)[:,:Nx]
    return res
def ps2d_to_mat(ps2d, Ny,Nx):
    corrfun = map_ifft(ps2d+0j)/(ps2d.shape[-2]*ps2d.shape[-1])**0.5
    thumb   = corrfun_thumb(corrfun, Ny,Nx)
    mat     = corr_to_mat(thumb, Ny,Nx)
    return mat


import sys
import os
import subprocess
from threading import Thread
import json
import sublime
import sublime_plugin
import time
import re
import ftplib
import platform
#Libreria para sftp desde Linux(Ubuntu)
from .src.Configuration import Configuration
from .src.Connection import Connection
from .src.ProgressBar import ProgressBarCommand as ProgressBar, ShowProgressBarCommand
from .src.extras import get_list_servers, sortFiles, createFile, readFile, Debug, getTmpName, getPath
import datetime
import shutil

def plugin_loaded():
	# Se crea el directorio del plugin
	user_path = os.path.join(sublime.packages_path(), 'User')
	Configuration.mysftp_path = os.path.join(user_path, 'MySFTP')
	if not os.path.exists(Configuration.mysftp_path): os.makedirs(Configuration.mysftp_path)

	# Se crea el directorio para los archivos temporales
	Configuration.tmp_path = os.path.join(Configuration.mysftp_path, 'tmp')
	if os.path.exists(Configuration.tmp_path):
		shutil.rmtree(Configuration.tmp_path)

	if not os.path.exists(Configuration.tmp_path): os.makedirs(Configuration.tmp_path)

	# Se crea directorio para los archivos de configuración de servidores
	Configuration.servers_path = os.path.join(Configuration.mysftp_path, 'servers')
	if not os.path.exists(Configuration.servers_path): os.makedirs(Configuration.servers_path)

	# Se crea directorio para psftp
	Configuration.psftp_path = os.path.join(Configuration.mysftp_path, 'psftp')
	if not os.path.exists(Configuration.psftp_path): os.makedirs(Configuration.psftp_path)

	Configuration.package_path = os.path.join(sublime.packages_path(), 'MySFTP')

	Debug.debug_file = os.path.join(Configuration.mysftp_path, '.debug')

	MySftp.settings = sublime.load_settings("MySFTP.sublime-settings")
	Debug.settings = MySftp.settings
	# create custome file settings
	if not os.path.exists(os.path.join(user_path, 'MySFTP.sublime-settings')):
		json_settings = {
			'debug_mode': MySftp.settings.get('debug_mode') or False,
			'debug_console': MySftp.settings.get('debug_console') or False,
			'check_if_write': MySftp.settings.get('check_if_write') or False
		}
		createFile(os.path.join(user_path, 'MySFTP.sublime-settings'), json.dumps(json_settings, indent='\t'))
	Debug.print("DEBUG_MODE: ", str(MySftp.settings.get('debug_mode')))
	Debug.print("DEBUG_CONSOLE: ", str(MySftp.settings.get('debug_console')))
	Debug.print("CHECK_IF_WRITE: ", str(MySftp.settings.get('check_if_write')))

	# Movemos los archivos de configuración servidores de la versión anterior al directorio servers
	for file in os.listdir( user_path ):
		full_name_file = os.path.join(user_path, file)
		if os.path.isfile(full_name_file):
			filename, file_extension = os.path.splitext(file)
			if file_extension != ".json":
				continue
			file_content = readFile( full_name_file )
			obj_match = re.findall(r"nick|type|host|remote_path|password|port|user", file_content)
			if obj_match != None and len(obj_match) == 7:
				shutil.move( full_name_file, os.path.join(Configuration.servers_path, file) )

	createFile(os.path.join(Configuration.mysftp_path, '.debug'))

class MySftp(sublime_plugin.TextCommand):
	listServers = []
	optionsFiles = ["> Cambiar de Servidor", "> Regresar", "> Editar","> Renombrar","> Cambiar Permisos","> Eliminar"]
	optionsFolders = ["> Cambiar de Servidor", "> Subir nivel","> Nuevo Archivo","> Nueva Carpeta","> Renombrar","> Cambiar Permisos","> Eliminar"]

	settings = None

	def run(self, edit):
		archivos = get_list_servers(Configuration.servers_path)
		self.view.window().run_command("show_servers", {"args" : archivos});

	@staticmethod
	def isWorking():
		try:
			if ShowProgressBarCommand.loading:
				raise Exception("threading isAlive")
		except Exception as e:
			sublime.message_dialog("Hay una operación en proceso, espere a que esta termine para continuar.")
			raise e

	@staticmethod
	def checkResponse(self, response, show_status = True):
		if not show_status:
			return True
		if response.find('Could not resolve hostname') != -1 or response.find('No route to host') != -1 or response.find('Network is unreachable') != -1 or response.find('Connection refused') != -1:
			ProgressBar.showError(self)
			ProgressBar.showMessage(self, 'Imposible conectar con el servidor, no se pudo resolver: {}.\n'.format(Configuration.host))
			return False
		elif response.find('Permission denied') != -1 or response.find('Could not create file') != -1:
			ProgressBar.showErrorPermissions(self)
			return False
		elif response.find('Usuario o password incorrectos') != -1 or response.find('Login incorrect') != -1:
			ProgressBar.showErrorCredentials(self)
			return False
		elif response.find('TimeOutExpired') != -1:
			ProgressBar.showErrorTimeOutExpired(self)
		elif response.find('o such file or directory') != -1:
			ProgressBar.showErrorNoSuchFileOrDirectory(self)
		elif response.find('PermissionError: [WinError 32]') != -1:
			ProgressBar.showError(self)
		elif response.find('No se puede establecer una conexión ya que el equipo de destino denegó expresamente') != -1:
			ProgressBar.showConnectionRefuse(self)
			return False
		else:
			ProgressBar.showSuccess(self)
		return True

class SyncFiles(sublime_plugin.WindowCommand):
	def run(self, comando):
		file = os.path.basename(self.window.active_view().file_name())

		if comando == "put_sftp":
			self.window.run_command("save");
			return

		Configuration.setConfig(os.path.join(Configuration.tmp_path, os.path.splitext(file)[0] + ".config"))
		if Configuration.flag_config != True:
			return

		if ProgressBar.createPanelOutput == False:
			ProgressBar.initConnection(self)
		self.window.run_command("get_sftp",{"file" : file, "flag" : True})

	def is_visible(self):
		return False if os.path.dirname(self.window.active_view().file_name()) != Configuration.tmp_path else True

class showServers(sublime_plugin.WindowCommand):
	def run(self, args):
		MySftp.isWorking();
		MySftp.listServers = args
		MySftp.listServers.insert(0, "Nuevo servidor.")
		quick_list = [option for option in MySftp.listServers]
		self.quick_list = quick_list
		self.window.show_quick_panel(quick_list,self.on_done,0)

	def on_done(self, index):
		if index == 0:
			self.window.run_command('new_server')
		elif index > 0:
			previous_config = Configuration( json.loads(Configuration.getJsonConfig()) )
			Configuration.setConfig(os.path.join(Configuration.servers_path, MySftp.listServers[index] + ".json"))
			if not Configuration.flag_config:
				return
			if previous_config.host == '' or previous_config.usuario == '' or previous_config.host != Configuration.host or previous_config.usuario != Configuration.usuario or previous_config.puerto != Configuration.puerto:
				ProgressBar.initConnection(self)

			t1 = Thread(target=self.listado)
			t1.start()

	def listado(self):
		self.window.run_command("show_ls");

class showLs(sublime_plugin.WindowCommand):

	list_files = None
	files_hiddens = None

	def run(self):
		MySftp.isWorking();
		ProgressBar.showList(self)
		t1 = Thread(target=self.requestListFiles)
		t1.start()

	def requestListFiles(self):
		response = showLs.getListFiles(self, True)
		if showLs.list_files != None and response != False:
			self.Options = ["Directorio: " + Configuration.currentPath] + MySftp.optionsFolders + showLs.list_files
			quick_list = [option for option in self.Options]
			self.quick_list = quick_list
			self.window.show_quick_panel(quick_list, lambda id : self.on_done(id), 0)

	def on_done(self, index):
		if index > 7:
			if showLs.list_files[index - 8][-1:] == '/':
				Configuration.currentPath = getPath(Configuration.currentPath, showLs.list_files[index - 8])
				self.window.run_command("show_ls");
			elif showLs.list_files[index - 8][-2:] == '->':
				# no such file or directory
				tmp_current_path = Configuration.currentPath
				Configuration.currentPath = getPath(Configuration.currentPath, showLs.list_files[index - 8][:-2])
				list_files_old = showLs.list_files
				salida = showLs.getListFiles(self)
				showLs.list_files = list_files_old
				if salida != False and salida.find("no such file or directory") != -1:
					Configuration.currentPath = tmp_current_path;
					self.Options = [ "Archivo: " + showLs.list_files[index - 8][:-2] ] + MySftp.optionsFiles
					quick_list = [option for option in self.Options]
					self.quick_list = quick_list
					self.window.show_quick_panel(quick_list, lambda id : self.file_selected(id, showLs.list_files[index - 8][:-2]), 0)
				else:
					Configuration.currentPath = tmp_current_pathn;
					Configuration.currentPath = getPath(Configuration.currentPath, showLs.list_files[index - 8][:-2])
					self.window.run_command("show_ls");
			else:
				self.Options = [ "Archivo: " + showLs.list_files[index - 8] ] + MySftp.optionsFiles
				quick_list = [option for option in self.Options]
				self.quick_list = quick_list
				self.window.show_quick_panel(quick_list, lambda id : self.file_selected(id, showLs.list_files[index - 8]), 0)
		elif index == 2: # Up Level
			Configuration.currentPath = getPath(Configuration.currentPath, '../')
			self.window.run_command("show_ls");
		else:
			commams_folders = [['my_sftp', {}], ['show_ls', {}], ['new_file_sftp', {}], ['new_dir_sftp', {}],
								['rename_sftp', {"path" : os.path.basename(Configuration.currentPath), 'is_folder': True}], ['chmod_sftp', {"path" : os.path.basename(Configuration.currentPath), 'is_file': False}],
								['remove_sftp', {"path" : os.path.basename(Configuration.currentPath), "is_file" : False}]]
			if index > 0:
				self.window.run_command( commams_folders[index - 1][0], commams_folders[index - 1][1] )

	def file_selected(self, index, file):
		commams_files = [['my_sftp', {}], ['show_ls', {}], ['get_sftp', {"file" : file}],
						['rename_sftp', {"path" : file}], ['chmod_sftp', {"path" : file}],
						['remove_sftp', {"path" : file, "is_file" : True}]]
		if index == 2:
			self.Options = ["Directorio: " + Configuration.currentPath] + MySftp.optionsFolders + showLs.list_files
			quick_list = [option for option in self.Options]
			self.quick_list = quick_list
			self.window.show_quick_panel(quick_list, lambda id : self.on_done(id), 0)
		if index != 2 and index > 0:
			self.window.run_command( commams_files[index - 1][0], commams_files[index - 1][1] )

	@staticmethod
	def getListFiles(self, show_status_connection = False):
		salida = Connection.ls()
		if show_status_connection:
			if MySftp.checkResponse(self, salida, show_status_connection) != True: return False
		lista = salida.strip("\n").split("\n")
		listas = sortFiles(lista)
		showLs.list_files = listas[0]
		showLs.files_hiddens = listas[1]
		return salida

class ChmodSftp(sublime_plugin.WindowCommand):

	def run(self, path, is_file = True):
		self.window.show_input_panel("Permisos:", "", lambda permisos: self.chmod(permisos, path, is_file), None, None)

	def chmod(self, permisos, path, is_file = True):
		if re.match("[1-7]{3}", permisos) != None:
			burbuja = Configuration.currentPath
			if not is_file:
				Configuration.currentPath = os.path.dirname(Configuration.currentPath)

			ProgressBar.showChmod(self, getPath(Configuration.currentPath, path))
			t1 = Thread(target=self.hilo, args=[permisos, path, burbuja])
			t1.start()
		else:
			sublime.message_dialog("La sintaxis para definir permisos no es valida.")

	def hilo(self, permisos, path, burbuja):
		salida = Connection.chmod(path, permisos)
		Configuration.currentPath = burbuja
		if MySftp.checkResponse(self, salida) != True:
			return

class removeSftp(sublime_plugin.TextCommand):

	def run(self, edit, path, is_file = True):
		burbuja = Configuration.currentPath
		if is_file == False:
			Configuration.currentPath = os.path.dirname(Configuration.currentPath)

		if path.find('.mysftp') == -1: # No lo encuentra
			ProgressBar.showDelete(self, getPath(Configuration.currentPath, path))

		t1 = Thread(target=self.hilo, args=[edit, path, is_file, burbuja])
		t1.start()

	def hilo(self, edit, path, is_file, burbuja):
		salida = Connection.rm(path, is_file)
		if path.find('.mysftp') == -1 and MySftp.checkResponse(self, salida) != True:
			Configuration.currentPath = burbuja
			return

class getSftp(sublime_plugin.TextCommand):

	def run(self, edit, file, flag = False):
		MySftp.isWorking();
		t1 = Thread(target=self.hilo, args=[edit, file, flag])
		t1.start()

	def hilo(self, edit, file, flag = False):
		ProgressBar.showDownload(self, getPath(Configuration.currentPath, file), file)

		if MySftp.settings.get('check_if_write') and "\n".join(showLs.files_hiddens).find( getTmpName(file) ) != -1: # Validamos que exista el archivo
			salida = Connection.get(getTmpName(file), os.path.join(Configuration.tmp_path, getTmpName(file)))
			if os.path.exists(os.path.join(Configuration.tmp_path, getTmpName(file))):
				nick_current_use = readFile(os.path.join(Configuration.tmp_path, getTmpName(file))).strip()
				os.remove(os.path.join(Configuration.tmp_path, getTmpName(file)))
				if nick_current_use != Configuration.nick:
					if not sublime.ok_cancel_dialog("El usuario " + nick_current_use + " esta usando actualmente el archivo, Deseas continuar con la descarga?."):
						Debug.print('Se manda a cancelar.')
						ProgressBar.showCancel(self)
						return

		if os.path.exists(os.path.join(Configuration.tmp_path, file)) and self.view.window().find_open_file(os.path.join(Configuration.tmp_path, file)) and flag == False:
			sublime.message_dialog("Ya existe un archivo con el mismo nombre, cierre primero para poder continuar editando otro archivo con el mismo nombre.")
			return

		salida = Connection.get(file, os.path.join(Configuration.tmp_path, file))
		time.sleep(0.02) # Esperamos que se termine de descargar el contenido
		if MySftp.checkResponse(self, salida) != True: return

		# Hay que poner los stops en los progressbar
		if os.path.exists(os.path.join(Configuration.tmp_path, file)):
			#ProgressBar.showSuccess(self)
			createFile(os.path.join(Configuration.tmp_path, os.path.splitext(file)[0] + ".path"), Configuration.currentPath)
			createFile(os.path.join(Configuration.tmp_path, os.path.splitext(file)[0] + ".config"), Configuration.getJsonConfig())
			vista = self.view.window().open_file(os.path.join(Configuration.tmp_path, file))
			t2 = Thread(target=self.hilo2, args=[file])
			t2.start()
		else:
			pass
			#ProgressBar.showError(self)

	def hilo2(self, file):
		createFile(os.path.join(Configuration.tmp_path, getTmpName(file)), Configuration.nick)
		salida = Connection.put(os.path.join(Configuration.tmp_path, getTmpName(file)), getTmpName(os.path.basename(file)))
		time.sleep(0.02)
		if os.path.exists(os.path.join(Configuration.tmp_path, getTmpName(file))):
			os.remove(os.path.join(Configuration.tmp_path, getTmpName(file)))

class MySftpEvent(sublime_plugin.EventListener):
	def on_post_save(self, view):
		ruta = view.file_name()
		if ruta != None and os.path.dirname(ruta) == Configuration.tmp_path:
			view.run_command("put_sftp", {"file" : view.file_name(), "flag" : False })
		else:
			Debug.print("este archivo no es valido para el package.")

	def on_close(self, view):
		ruta = view.file_name()
		if ruta != None and os.path.dirname(ruta) == Configuration.tmp_path and view.is_dirty() == False:
			view.run_command("remove_sftp", {"path" : getTmpName( os.path.basename(ruta) ), "is_file" : True})
			t1 = Thread(target=self.closeFile, args=[view, ruta])
			t1.start()

	def closeFile(self, view, ruta):
		if os.path.exists(ruta):
			os.remove(ruta)
		if os.path.exists( getTmpName(os.path.splitext(ruta)[0]) ):
			os.remove( getTmpName(os.path.splitext(ruta)[0]) )
		os.remove(os.path.splitext(ruta)[0] + ".path")
		os.remove(os.path.splitext(ruta)[0] + ".config")

class putSftp(sublime_plugin.TextCommand):

	def run(self, edit, file , flag):
		MySftp.isWorking();

		ruta = file.replace('.mysftp', "") if flag == True else file

		if os.path.dirname(ruta) != Configuration.tmp_path:
			return

		path_put = Configuration.currentPath
		old_path = Configuration.currentPath

		if flag == False:
			path_put = readFile(os.path.splitext(ruta)[0] + ".path")
			json_file = json.loads( readFile(os.path.splitext(ruta)[0] + ".config") )
			if Configuration.host == '' or Configuration.usuario == '' or Configuration.password == '' or Configuration.host != json_file[0]["host"] or Configuration.usuario != json_file[0]["user"] or Configuration.password != json_file[0]["password"]:
				Configuration.setConfig(os.path.splitext(ruta)[0] + ".config")
				if Configuration.flag_config != True:
					return
				ProgressBar.initConnection(self)
		Configuration.currentPath = path_put
		t1 = Thread(target=self.hilo1, args=[edit, ruta, flag, old_path])
		t1.start()

	def hilo1(self, edit, ruta, flag, old_path):
		if flag == False:
			ProgressBar.showUpload(self, os.path.basename(ruta), getPath(Configuration.currentPath, os.path.basename(ruta)))

		if MySftp.settings.get('check_if_write'):
			salida = Connection.get(getTmpName(ruta), os.path.join(Configuration.tmp_path, getTmpName(ruta)))
			if os.path.exists( os.path.join(Configuration.tmp_path, getTmpName(ruta)) ):#Validamos que exista el archivo
				nick_current_use = readFile(os.path.join(Configuration.tmp_path, getTmpName(ruta))).strip()
				if Configuration.nick != nick_current_use and flag == False:
					if not sublime.ok_cancel_dialog("El usuario " + nick_current_use + " esta usando actualmente el archivo, Deseas subir tus cambios?."):
						ProgressBar.showCancel(self)
						return

		createFile(os.path.join(Configuration.tmp_path, getTmpName(ruta)), Configuration.nick)

		if flag == False:
			t2 = Thread(target=self.hilo2, args=[edit, ruta, flag, old_path])
			t2.start()

	def hilo2(self, edit, ruta, flag, old_path):
		salida = Connection.put(ruta, os.path.basename(ruta))
		if 'nick_current_use' in locals():
			if Configuration.nick != nick_current_use:
				os.remove(os.path.join(Configuration.tmp_path, getTmpName(ruta)))
		if not flag:
			if MySftp.checkResponse(self, salida) != True: return

		t3 = Thread(target=self.hilo3, args=[edit, ruta, old_path])
		t3.start()

	def hilo3(self, edit, ruta, old_path):
		salida = Connection.put(os.path.join(Configuration.tmp_path, getTmpName(ruta)), getTmpName(ruta))
		Configuration.currentPath = old_path
		time.sleep(0.02)
		if os.path.exists(os.path.join(Configuration.tmp_path, getTmpName(ruta))):
			os.remove(os.path.join(Configuration.tmp_path, getTmpName(ruta)))

class newFileSftp(sublime_plugin.WindowCommand):
	def run(self):
		t1 = Thread(target=self.getListFiles)
		t1.start()
		time.sleep(0.16)
		self.window.show_input_panel("Nombre del archivo:", "", self.createFile, None, None)

	def createFile(self,name_file):
		# Validamos el nombre de archivo
		name_file = name_file.strip();
		if re.match("^[\w\-. ]+$", name_file):
			# Revisamos que no exista el archivo en remoto
			if name_file in showLs.list_files:
				sublime.message_dialog("Ya existe un archivo con el nombre: " + name_file + " en: " + Configuration.currentPath)
				return
			if os.path.isfile(os.path.join(Configuration.tmp_path, name_file)):
				sublime.message_dialog("Se encuentra editando un archivo con el mismo nombre, se recomienda cerrarlo primero.")
			else:
				local_file = os.path.join(Configuration.tmp_path, name_file)
				createFile(local_file)
				createFile(os.path.join(Configuration.tmp_path, os.path.splitext(name_file)[0] + ".path"), Configuration.currentPath)
				createFile(os.path.join(Configuration.tmp_path, os.path.splitext(name_file)[0] + ".config"), Configuration.getJsonConfig())
				ProgressBar.showMakeFile(self, getPath(Configuration.currentPath, name_file))
				t2 = Thread(target=self.hilo, args=[local_file])
				t2.start()
		else:
			sublime.message_dialog("Nombre de archivo no valido")

	def hilo(self, local_file):
		salida = Connection.put(local_file, os.path.basename(local_file))
		tmp_name = os.path.join(Configuration.tmp_path, getTmpName(os.path.basename(local_file)))
		createFile(tmp_name, Configuration.nick)
		Connection.put(tmp_name, os.path.basename(tmp_name))
		time.sleep(0.08)
		os.remove(tmp_name)
		if MySftp.checkResponse(self, salida) == True:
			self.window.open_file(local_file)

	def getListFiles(self):
		showLs.getListFiles(self)

class newDirSftp(sublime_plugin.WindowCommand):
	def run(self):
		t1 = Thread(target=self.getListFiles)
		t1.start()
		time.sleep(0.16)
		self.window.show_input_panel("Nombre del directorio:", "", self.createDir, None, None)

	def createDir(self, name_dir):
		name_dir = name_dir.strip();
		if re.match("^[\w\-. ]+$", name_dir):
			# Revisamos que no exista el archivo en remoto
			if (name_dir + '/') in showLs.list_files:
				sublime.message_dialog("Ya existe un directorio con el nombre: " + name_dir + " en: " + Configuration.currentPath)
				return
			t2 = Thread(target=self.hilo, args=[name_dir])
			t2.start()

	def hilo(self, name_dir):
		ProgressBar.showMakeDir(self, getPath(Configuration.currentPath, name_dir ))
		salida = Connection.mkdir(name_dir)
		if MySftp.checkResponse(self, salida) != True: return
		Configuration.currentPath = getPath(Configuration.currentPath, name_dir)
		self.window.run_command("show_ls");

	def getListFiles(self):
		showLs.getListFiles(self)

class ServerManager(sublime_plugin.WindowCommand):
	def run(self, action):
		MySftp.listServers = get_list_servers(Configuration.servers_path)
		quick_list = [option for option in MySftp.listServers]
		self.quick_list = quick_list
		self.window.show_quick_panel(quick_list,lambda id : self.on_done(id, action),0)

	def on_done(self, index, action):
		if index >= 0:
			if action == 'edit':
				self.window.open_file(os.path.join(Configuration.servers_path, MySftp.listServers[index] + ".json"))
			elif action == 'remove':
				os.remove(os.path.join(Configuration.servers_path, MySftp.listServers[index] + ".json"))

class NewServer(sublime_plugin.WindowCommand):
	def run(self):
		vista = self.window.new_file()
		vista.run_command('insert_snippet', {"name": "Packages/MySFTP/server.sublime-snippet" })
		vista.set_syntax_file("JSON.sublime-syntax")
		vista.set_name('server.json')
		vista.settings().set('default_dir', Configuration.servers_path)

class renameSftp(sublime_plugin.WindowCommand):
	def run(self, path, is_folder = False):
		self.window.show_input_panel("Nombre Nuevo:", path, lambda name:self.rename(path, name, is_folder), None, None)

	def rename(self, current_name, new_name, is_folder = False):
		ProgressBar.showRename(self, current_name, new_name)
		t1 = Thread(target=self.hilo, args=[current_name, new_name, is_folder])
		t1.start()

	def hilo(self, current_name, new_name, is_folder = False):
		burbuja = Configuration.currentPath
		if is_folder:
			Configuration.currentPath = os.path.dirname(Configuration.currentPath)

		salida = Connection.mv(current_name, new_name)

		if MySftp.checkResponse(self, salida) != True:
			if is_folder:
				Configuration.currentPath = burbuja
			return
		else:
			if is_folder:
				Configuration.currentPath = getPath(Configuration.currentPath, new_name)

class SideBar(sublime_plugin.WindowCommand):
	def run(self, paths = []):
		###self.window.run_command("progress_bar", {"msg" : "\nCargando "})
		ProgressBar.showDownload(self)
		t1 = Thread(target=self.testLoad)
		t1.start()

	def testLoad(self):
		# self.window.run_command("progress_bar", {"msg" : "", "start_loading": True, "stop_loading": False})
		time.sleep(2)
		# self.window.run_command("progress_bar", {"msg" : "success", "start_loading": False, "stop_loading": True})
		ProgressBar.showSuccess(self)

	def is_visible(self, paths = ''):
		return True

	def is_enabled(self, paths = ''):
		Debug.print("$path", paths)
		return True


from collections import Counter
import time

import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader

from transformers import BertModel, BertTokenizer

class BERTDataset(Dataset):
  def __init__(self, file_path, bert_name, delta=5):
    """
    Load the whole data file into memory
    for easier access during batching
    """
    self.delta = delta
    self.window_size = 2 * delta + 1
    self.create_vocab(file_path)
    # self.save_vocab("vocab")

    self.bert_tokenizer = BertTokenizer.from_pretrained(bert_name)
    self.bert_model = BertModel.from_pretrained(bert_name)
    self.bert_model.eval()

  def create_vocab(self, file_path):
    counts = Counter()
    self.data = []
    with open(file_path) as f:
      for line in f:
        words = line.split()
        if len(words) < self.window_size:
          continue
        self.data.append(words)
        counts.update(words)

    self.word2id = {"UNK":0}
    self.id2word = ["UNK"]
    self.word2freq = {"UNK":0}
    for i, (word, freq) in enumerate(counts.most_common()):
      if freq >= 5:
        self.word2id[word] = i+1
        self.id2word.append(word)
        self.word2freq[word] = freq

    print("Vocab size:", len(self.id2word))

  def save_vocab(self, file_path):
    with open(file_path, 'w') as f:
      for w in self.id2word:
        f.write(f"{w} {self.word2freq[w]}\n")

  def process(self, line):
    """
    Returns words and contexts from line

    Args
      line: list of words
    """
    # bert_model = BertModel.from_pretrained(self.bert_name)
    # bert_tokenizer = BertTokenizer.from_pretrained(self.bert_name)
    # bert_model.eval()
    word_to_token_map = []
    tokens = []
    for w in line:
      word_to_token_map.append(len(tokens))
      tokens += self.bert_tokenizer.tokenize(w)

    word_to_token_map.append(len(tokens))
    word_to_token_map = np.array(word_to_token_map)

    words = []
    context_tokens = []
    context_token_maps = []
    for i in range(len(line) - self.window_size + 1):
      words.append(self.word2id.get(line[i+self.delta], 0))
      context_token_maps.append(word_to_token_map[i:i+self.window_size] - word_to_token_map[i] + 1)
      context_tokens.append(tokens[word_to_token_map[i]:word_to_token_map[i+self.window_size]])

    max_len = max([len(c) for c in context_tokens])
    context_ids = []
    for ctokens in context_tokens:
      context_ids.append([self.bert_tokenizer.cls_token_id] \
                        + self.bert_tokenizer.convert_tokens_to_ids(ctokens) \
                        + [self.bert_tokenizer.sep_token_id] \
                        + [self.bert_tokenizer.pad_token_id] * (max_len - len(ctokens)))

    context_token_maps = context_token_maps

    with torch.no_grad():
      output_states, _ = self.bert_model(torch.tensor(context_ids))
    context_states = []
    for i, output_state in enumerate(output_states):
      context_states.append(output_state[context_token_maps[i]])
    context_states = torch.stack(context_states,dim=0)
    # print(output_states.size(), context_states.size())

    bert_embeds = context_states[:,self.delta,:]
    bert_context_embeds = torch.cat([context_states[:,:self.delta,:], context_states[:,self.delta+1:,:]], dim=1).view((len(context_tokens),-1))

    # print(context_tokens)
    # print(max_len)
    # print(bert_embeds[0].size())
    # print(bert_context_embeds[0].size())

    return words, bert_embeds, bert_context_embeds#, torch.stack(bert_embeds, dim=0), torch.stack(bert_context_embeds, dim=0)

  def __len__(self):
    return len(self.data)

  def __getitem__(self, idx):
    """
    Access a specific sample from the dataset
    """
    words, berts, contexts = self.process(self.data[idx])
    return {'word':words, 'bert':berts, 'context':contexts}

def combine_samples(batch):
  """
  Combines a list of samples returned from
  '__getitem__' of BERTDataset

  Args
    batch: list of samples in a batch

  Returns:
    a batch of contexts and embeddings for use in training
  """
  words = torch.tensor([w for sample in batch for w in sample['word']])
  berts = torch.cat([sample['bert'] for sample in batch], dim=0)
  contexts = torch.cat([sample['context'] for sample in batch], dim=0)
  return words, berts, contexts

if __name__ == "__main__":

  small_dataset = BERTDataset("/home/anik/Documents/f18/embeddings/data/west-wiki/small.txt", "bert-base-uncased")

  bert_loader = DataLoader(small_dataset, batch_size=2, shuffle=False,
                                        num_workers=0, collate_fn=combine_samples)

  start = time.time()
  c = 0
  for i, b in enumerate(bert_loader):
    # print(b[0].size(),'\n', b[1].size(), '\n', b[2].size())
    c+= len(b[0])
    if i % 2 == 0:
      t = time.time() - start
      print(f"{c:,} words in {t:0.2f} seconds at {c/t:,.2f} words/sec", end='\r')
    # break
  t = time.time() - start
  print(f"{c:,} words in {t:0.2f} seconds at {c/t:,.2f} words/sec")


####################################################
# for each element in the list, return its distance
# from the 'next less element' (NLE). If an
# element does not have a NLE, return -1.
#
# uses a monotonous stack
###################################################
from typing import List

class NextLessElement:
    def calculate(self, nums: List[int]) -> List[int]:
        if not nums:
            return []

        right, monostack = [-1] * len(nums), []

        for i in range(len(nums)):
            """ check if the element pointed by the stack top
                is greater than the current element.

                if YES, then the current element is NLE of the
                element pointed by stack. Remove element from
                the stack and set its NLE

                how it differs from PLE?
                ------------------------
                PLE -> PLE of current element is set in the loop

                NLE -> NLE of element pointed by the stack is set in the loop
            """
            while monostack and nums[monostack[-1]] > nums[i]:
                x = monostack.pop()
                right[x] = i

            """ append current index to the stack """
            monostack.append(i)

        """ calculate the distance of each element from its NLE """
        for i in range(len(right)):
            right[i] = right[i] - i if right[i] != -1 else right[i]

        return right


#encoding=utf-8
from selenium import  webdriver
import  time

driver=webdriver.Firefox()
web_url="https://www.baidu.com"
driver.get(web_url)
time.sleep(3)
driver.maximize_window()

el_set=driver.find_element_by_link_text("设置")
el_set.click()

#进入搜索设置并点击
el_search=driver.find_element_by_css_selector(".setpref")
el_search.click()

#定位保存设置按钮
el_save=driver.find_element_by_css_selector(".prefpanelgo")
el_save.click()
time.sleep(3)
#进入警告框中并且点击确定接受
# driver.switch_to.alert.accept()

#进入警告框中并直接关闭警告框
driver.switch_to.alert.dismiss()


import pandas as pd

from preprocessing.config_preproc import PreprocConfig as CFG_P
from training import helpers_flat_training as helpers_tr

lgb_params = {
    'objective': 'binary',
    'metric': "binary_logloss",
    'boosting': 'dart',
    'seed': CFG_P.seed + 2,
    'max_depth': 7,
    'num_leaves': 120,
    'learning_rate': 0.01,
    'colsample_bytree': 0.45,
    'bagging_freq': 10,
    'bagging_fraction': 0.50,
    'reg_alpha': 2,
    'reg_lambda': 2,
    'n_jobs': -1,
    'min_data_in_leaf': 40
}

lgb_kwargs = {
    'params' : lgb_params,
    'num_boost_round' : 10000,
    'callbacks' : [helpers_tr.get_lgb_dart_callback()],
}

feature_fnames = ['{}_diff_agg_features.parquet',
                  '{}_basic_agg_features.parquet',
                  '{}_diff_features.parquet']
tr_feature_files = [CFG_P.output_dir + f.format('train') for f in feature_fnames]
te_feature_files = [CFG_P.output_dir + f.format('test') for f in feature_fnames]

df_train = helpers_tr.load_flat_features(tr_feature_files)
p_2_cols = [c for c in df_train.columns if 'P_2_' in c]
print(df_train.shape)
df_train = df_train.drop(columns=p_2_cols)
print(df_train.shape)
df_train = pd.merge(df_train, pd.read_parquet(CFG_P.output_dir + 'train_labels_w_folds.parquet'),
                    on='customer_ID')

df_test = helpers_tr.load_flat_features(te_feature_files)
df_test = df_test.drop(columns=p_2_cols)

helpers_tr.train_save_flat_model(df_train, df_test,
                                 helpers_tr.get_lgb_dart_model, lgb_kwargs,
                                 helpers_tr.get_lgb_imp, 'lgbm_dart_no_P2')


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

from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.IsvMerchantInfo import IsvMerchantInfo
from alipay.aop.api.domain.ShopSummaryInfo import ShopSummaryInfo

class KoubeiMarketingToolIsvMerchantQueryResponse(AlipayResponse):

    def __init__(self):
        super(KoubeiMarketingToolIsvMerchantQueryResponse, self).__init__()
        self._merchant_infos = None
        self._shop_count = None
        self._shop_summary_infos = None

    @property
    def merchant_infos(self):
        return self._merchant_infos

    @merchant_infos.setter
    def merchant_infos(self, value):
        if isinstance(value, list):
            self._merchant_infos = list()
            for i in value:
                if isinstance(i, IsvMerchantInfo):
                    self._merchant_infos.append(i)
                else:
                    self._merchant_infos.append(IsvMerchantInfo.from_alipay_dict(i))
    @property
    def shop_count(self):
        return self._shop_count

    @shop_count.setter
    def shop_count(self, value):
        self._shop_count = value
    @property
    def shop_summary_infos(self):
        return self._shop_summary_infos

    @shop_summary_infos.setter
    def shop_summary_infos(self, value):
        if isinstance(value, list):
            self._shop_summary_infos = list()
            for i in value:
                if isinstance(i, ShopSummaryInfo):
                    self._shop_summary_infos.append(i)
                else:
                    self._shop_summary_infos.append(ShopSummaryInfo.from_alipay_dict(i))

    def parse_response_content(self, response_content):
        response = super(KoubeiMarketingToolIsvMerchantQueryResponse, self).parse_response_content(response_content)
        if 'merchant_infos' in response:
            self.merchant_infos = response['merchant_infos']
        if 'shop_count' in response:
            self.shop_count = response['shop_count']
        if 'shop_summary_infos' in response:
            self.shop_summary_infos = response['shop_summary_infos']


#!/usr/bin/python3
"""Start link class to table in database """
from sys import argv
from sqlalchemy.orm import sessionmaker
from model_state import State, Base
from model_city import City
from sqlalchemy import (create_engine)

if __name__ == "__main__":
    engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'.format(
            argv[1],
            argv[2],
            argv[3]
        ),
        pool_pre_ping=True)
    Base.metadata.create_all(engine)

    Session = sessionmaker(bind=engine)
    session = Session()
    for city in session.query(City).join(State).order_by(City.id).all():
        state = session.query(State).filter(State.id == city.state_id).first()
        print("{}: ({}) {}".format(state.name, city.id, city.name))
    session.close()


#!/usr/bin/python
from mi.client.utils import _
from mi.client.utils import magicstep
from mi.utils.miconfig import MiConfig
CF = MiConfig.get_instance()

from mi.server.utils import logger
dolog = logger.info

class MIStep_startsetup (magicstep.magicstep):
    def __init__(self, rootobj):
        magicstep.magicstep.__init__(self, rootobj, 'startsetup.xml', 'startsetup')

    def get_label(self):
        return _("Start to setup")

    def btnnext_clicked(self, widget, data):
        # We add a skip step name to current class,
        # and it will remove the step in magic.installer class
        self.fetch_values(self.rootobj.values,
                valuename_list = ['startsetup.skipXsetting'])
        skipx = self.get_data(self.values, 'startsetup.skipXsetting')
        if skipx == '1':
            self.skip_stepnames.append('Xwindow')
            CF.G.skipxsetting = 1
        else:
            CF.G.skipxsetting = 0
        return  1


def extractHilloh16WordpressCom(item):
	'''
	Parser for 'hilloh16.wordpress.com'
	'''

	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or "preview" in item['title'].lower():
		return None

	if item['tags'] == ['Uncategorized']:
		chp_prefixes = [
				('The Ugly Empress',  'The Ugly Empress',               'translated'),
			]

		for prefix, series, tl_type in chp_prefixes:
			if item['title'].lower().startswith(prefix.lower()):
				return buildReleaseMessageWithType(item, series, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)

	return False