from __future__ import absolute_import, division, print_function

from types import FunctionType, MethodType

try:
    from inspect import getfullargspec
except ImportError:  # Python 2.7
    from inspect import getargspec as getfullargspec

# from glue.config import link_function, link_helper

from glue.core.component_link import ComponentLink
from glue.core.link_helpers import LinkCollection
from glue.core.state_objects import State
from glue.external.echo import CallbackProperty, SelectionCallbackProperty, delay_callback
from glue.core.data_combo_helper import DataCollectionComboHelper, ComponentIDComboHelper

__all__ = ['LinkEditorState', 'EditableLinkFunctionState']

class LinkEditorState(State):

    data1 = SelectionCallbackProperty()
    data2 = SelectionCallbackProperty()
    current_link = SelectionCallbackProperty()
    link_type = SelectionCallbackProperty()
    restrict_to_suggested = CallbackProperty(False)

    def __init__(self, data_collection, suggested_links=None):

        super(LinkEditorState, self).__init__()

        self.data1_helper = DataCollectionComboHelper(self, 'data1', data_collection)
        self.data2_helper = DataCollectionComboHelper(self, 'data2', data_collection)

        # FIXME: We unregister the combo helpers straight away to avoid issues with
        # leftover references once the dialog is closed. This shouldn't happen
        # ideally so in future we should investigate how to avoid it.
        self.data1_helper.unregister(data_collection.hub)
        self.data2_helper.unregister(data_collection.hub)

        self.data_collection = data_collection

        # Convert links to editable states
        links = [EditableLinkFunctionState(link) for link in data_collection.external_links]

        # If supplied, also add suggested links and make sure we toggle the
        # suggestion flag on the link state so that we can handle suggestions
        # differently in the link viewer.
        if suggested_links is not None:
            for link in suggested_links:
                link_state = EditableLinkFunctionState(link)
                link_state.suggested = True
                links.append(link_state)

        self.links = links

        if len(data_collection) == 2:
            self.data1, self.data2 = self.data_collection
        else:
            self.data1 = self.data2 = None

        self._on_data_change()

        self.add_callback('data1', self._on_data1_change)
        self.add_callback('data2', self._on_data2_change)
        self.add_callback('restrict_to_suggested', self._on_data_change)

        LinkEditorState.current_link.set_display_func(self, self._display_link)

    @property
    def visible_links(self):

        if self.data1 is None or self.data2 is None:
            return []

        links = []
        for link in self.links:
            if link.suggested or not self.restrict_to_suggested:
                if ((link.data_in is self.data1 and link.data_out is self.data2) or
                        (link.data_in is self.data2 and link.data_out is self.data1)):
                    links.append(link)

        return links

    def _on_data1_change(self, *args):
        if self.data1 is self.data2 and self.data1 is not None:
            self.data2 = next(data for data in self.data_collection if data is not self.data1)
        else:
            self._on_data_change()

    def _on_data2_change(self, *args):
        if self.data2 is self.data1 and self.data2 is not None:
            self.data1 = next(data for data in self.data_collection if data is not self.data2)
        else:
            self._on_data_change()

    def _on_data_change(self, *args):

        links = self.visible_links
        with delay_callback(self, 'current_link'):
            LinkEditorState.current_link.set_choices(self, links)
            if len(links) > 0:
                self.current_link = links[0]

    def _display_link(self, link):
        if link.suggested:
            return str(link) + ' [Suggested]'
        else:
            return str(link)

    def new_link(self, function_or_helper):

        if hasattr(function_or_helper, 'function'):
            link = EditableLinkFunctionState(function_or_helper.function,
                                             data_in=self.data1, data_out=self.data2,
                                             output_names=function_or_helper.output_labels,
                                             description=function_or_helper.info,
                                             display=function_or_helper.function.__name__)
        else:
            link = EditableLinkFunctionState(function_or_helper.helper,
                                             data_in=self.data1, data_out=self.data2)

        self.links.append(link)
        with delay_callback(self, 'current_link'):
            self._on_data_change()
            self.current_link = link

    def remove_link(self):
        self.links.remove(self.current_link)
        self._on_data_change()

    def update_links_in_collection(self):
        links = [link_state.link for link_state in self.links]
        self.data_collection.set_links(links)

class EditableLinkFunctionState(State):

    function = CallbackProperty()
    data_in = CallbackProperty()
    data_out = CallbackProperty()
    description = CallbackProperty()
    display = CallbackProperty()
    suggested = CallbackProperty(False)

    def __new__(cls, function, data_in=None, data_out=None, cids_in=None,
                cid_out=None, input_names=None, output_names=None,
                display=None, description=None):

        if isinstance(function, ComponentLink):
            input_names = function.input_names
            output_names = [function.output_name]
        elif isinstance(function, LinkCollection):
            input_names = function.labels1
            output_names = function.labels2
            description = function.description
        elif type(function) is type and issubclass(function, LinkCollection):
            input_names = function.labels1
            output_names = function.labels2
            description = function.description

        class CustomizedStateClass(EditableLinkFunctionState):
            pass

        if input_names is None:
            input_names = getfullargspec(function)[0]

        if output_names is None:
            output_names = []

        setattr(CustomizedStateClass, 'input_names', input_names)
        setattr(CustomizedStateClass, 'output_names', output_names)

        for index, input_arg in enumerate(CustomizedStateClass.input_names):
            setattr(CustomizedStateClass, input_arg, SelectionCallbackProperty(default_index=index))

        for index, output_arg in enumerate(CustomizedStateClass.output_names):
            setattr(CustomizedStateClass, output_arg, SelectionCallbackProperty(default_index=index))

        return super(EditableLinkFunctionState, cls).__new__(CustomizedStateClass)

    def __init__(self, function, data_in=None, data_out=None, cids_in=None,
                 cids_out=None, input_names=None, output_names=None,
                 display=None, description=None):

        super(EditableLinkFunctionState, self).__init__()

        if isinstance(function, ComponentLink):
            self._function = function.get_using()
            self._inverse = function.get_inverse()
            self._helper_class = None
            cids_in = function.get_from_ids()
            cids_out = function.get_to_ids()
            data_in = cids_in[0].parent
            data_out = cids_out[0].parent
            self.display = self._function.__name__
            self.description = function.description
        elif isinstance(function, LinkCollection):
            self._function = None
            self._helper_class = function.__class__
            cids_in = function.cids1
            cids_out = function.cids2
            data_in = cids_in[0].parent

            # To be backward-compatible with cases where @link_helper doesn't
            # include output labels, we need to assume cids_out can be empty
            # in which case we look for the second dataset inside cids_in
            if len(cids_out) > 0:
                data_out = cids_out[0].parent
            else:
                for cid in cids_in[1:]:
                    if cid.parent is not data_in:
                        data_out = cid.parent
                        break
                else:
                    raise ValueError("Could not determine second dataset in link")

            self.display = function.display
            self.description = function.description
            self._mode = 'helper'
        elif type(function) is type and issubclass(function, LinkCollection):
            self._function = None
            self._helper_class = function
            self.display = function.display
            self.description = function.description
        elif isinstance(function, (FunctionType, MethodType)):
            self._function = function
            self._inverse = None
            self._helper_class = None
            self.inverse = None
            self.display = display
            self.description = description
        else:
            raise TypeError("Unexpected type for 'function': {0}".format(type(function)))

        self.data_in = data_in
        self.data_out = data_out

        for name in self.input_names:
            helper = ComponentIDComboHelper(self, name,
                                            pixel_coord=True, world_coord=True)
            helper.append_data(data_in)
            helper.append_data(data_out)

            setattr(self, '_' + name + '_helper', helper)

        for name in self.output_names:
            helper = ComponentIDComboHelper(self, name,
                                            pixel_coord=True, world_coord=True)
            helper.append_data(data_out)
            helper.append_data(data_in)
            setattr(self, '_' + name + '_helper', helper)

        if cids_in is not None:
            for name, cid in zip(self.input_names, cids_in):
                setattr(self, name, cid)

        if cids_out is not None:
            for name, cid in zip(self.output_names, cids_out):
                setattr(self, name, cid)

    def __str__(self):
        return self.display

    @property
    def link(self):
        """
        Return a `glue.core.component_link.ComponentLink` object.
        """
        if self._function is not None:
            cids_in = [getattr(self, name) for name in self.input_names]
            cid_out = getattr(self, self.output_names[0])
            return ComponentLink(cids_in, cid_out,
                                 using=self._function, inverse=self._inverse)
        else:
            cids_in = [getattr(self, name) for name in self.input_names]
            cids_out = [getattr(self, name) for name in self.output_names]
            return self._helper_class(cids1=cids_in, cids2=cids_out,
                                      data1=self.data_in, data2=self.data_out)


import matplotlib as mpl
import matplotlib.pyplot as plt
import csv
import numpy as np
from pylab import *
from matplotlib.font_manager import FontProperties

x=[]
y=[]
n=[]
i=0

with open ('Teaching.csv','rt') as csvfile:
	plots= csv.reader(csvfile,delimiter=',')
	for row in plots:
			#print i,row
			#i=i+1

		#n.append(row[0])
		x.append(float(row[0]))
		y.append(float(row[1]))

fig, ax=plt.subplots()
ax.scatter(x,y, label='Ranking')
ax.set_xlim(xmin=0)
ax.set_ylim(ymax=120)
ax.set_ylim(ymin=0)

#m, b = np.polyfit(x, y, 1)

plt.plot(x, y, '.')
#l1=plt.plot(x, m*np.array(x) + b, '-')
plt.xlabel('Overall Score', fontsize=18)
plt.ylabel('Teaching Score', fontsize=18)
#setp(l1,linewidth=2)
plt.title ('THE 2015-16', fontsize=18)
plt.plot([0, 500], [0, 500], 'r', lw=2)
ax.spines['bottom'].set_linewidth(2.0)
ax.spines['left'].set_linewidth(2.0)
ax.spines['top'].set_linewidth(2.0)
ax.spines['right'].set_linewidth(2.0)
plt.show()

Comparative analysis/Overall vs Metric (THE,QS 2015-16)/THE/Rankcompare.py


# pattern.py
import numpy as np
import pandas as pd
from my_tools import *  # 必要的部分工具

# 格局类
class pattern:
    def __init__(self, xml_dom):
        '''
        构造函数
        :param xml_dom: 保存着格局的xml的dom对象
        '''
        # 获取dom对象的根节点
        root = xml_dom.documentElement
        # 获取xml中的commonInformation标签
        common_information_label = root.getElementsByTagName('commonInformation')[0]
        # 获得格局的id（虽然主程序中没用到）
        self.ID = common_information_label.getAttribute('ID')
        # 声明一下格局里面的点的集合
        self.positions = []
        # 声明一下格局的初始点
        self.init_position = None
        # 声明一下格局的所有终点
        self.ending_positions = []
        # 获得xml中的所有position标签与behavior标签
        temporary_position_labels = root.getElementsByTagName('position')
        temporary_behavior_labels = root.getElementsByTagName('behavior')
        # 初始化保存behavior的集合
        self.behaviors = []
        # 对于每一个behavior标签
        for i in temporary_behavior_labels:
            # 获取标签中的bID、before、after、success_rate、weight、属性作为字典
            temporary_behavior = {"bID": i.getAttribute('bID'), "before": i.getAttribute('before'),
                                  "after": i.getAttribute('after'),
                                  "success_rate": float(i.getAttribute('successRate')),
                                  "weight": float(i.getAttribute('weight'))}
            # 添加到行为集合中
            self.behaviors.append(temporary_behavior)
        # 对于所有position标签
        for i in temporary_position_labels:
            # 取出标签中的pID属性、name属性、type属性、weight属性作为字典存起来
            next_position = []
            for j in self.behaviors:
                if j['before'] == i.getAttribute('pID'):
                    n_p = {"pID": j['after'], "success_rate": j['success_rate'], "weight": j['weight']}
                    next_position.append(n_p)
            temporary_position = {"pID": i.getAttribute('pID'), "name": i.getAttribute('name'),
                                  "type": i.getAttribute('type'),
                                  "weight": float(i.getAttribute('weight')), "next_position": next_position}
            # 加到集合里面去
            self.positions.append(temporary_position)
            # 如果当前的点的类型是ending即终点，再把这个点的id加到终点集合里面
            if temporary_position['type'] == "ending":
                self.ending_positions.append(temporary_position["pID"])
            # 如果类型是start，把这个点的id赋值为格局的初始点
            elif temporary_position['type'] == "start":
                self.init_position = temporary_position["pID"]
        # 初始化一下格局上能有的所有行为

        # 拿一下所有position的ID
        temporary_position_labels = []
        for i in self.positions:
            temporary_position_labels.append(i['pID'])
        # 拿一下所有behavior的ID
        temporary_behavior_labels = []
        for i in self.behaviors:
            temporary_behavior_labels.append((i['before'], i['after']))
        # 算一下所有点的拓扑排序的序列
        self.topo_sort_sequence = topoSort(temporary_position_labels.copy(), temporary_behavior_labels)
        # Floyd算法需要的连接矩阵
        self.position_link_matrix = pd.DataFrame(index=temporary_position_labels, columns=temporary_position_labels,
                                                 dtype=np.float)
        self.position_link_matrix[:][:] = np.inf
        # Floyd算法扩展的路径矩阵初始化
        self.position_link_path = pd.DataFrame(index=temporary_position_labels, columns=temporary_position_labels)
        # 初始化邻接矩阵，首先声明边与点的权重差
        temporary_b_p_weight_difference = float(0)
        for b in self.behaviors:
            for p in self.positions:
                if p['pID'] == b['after']:
                    temporary_b_p_weight_difference = b['weight'] - p['weight']
                    break
            self.position_link_matrix[b['before']][b['after']] = temporary_b_p_weight_difference
            self.position_link_path[b['before']][b['after']] = b['before']
        floyd_with_path(self.position_link_matrix, self.position_link_path)

"""因修改底层代码，无需此函数辅助"""
# def is_in_between(the_pattern, start, target):
#     """
#     计算target的拓扑序列是否在start与start的所有后继position之间
#     :param the_pattern:
#     :param start: 起始点ID
#     :param target: 目标点ID
#     :return:
#     """
#     # 对于所有的position
#     for i in the_pattern.positions:
#         # 定位到start代表的position
#         if start == i['pID']:
#             # 对于start的所有后继position
#             for j in i['next_position']:
#                 # 如果发现有一个后继节点的拓扑序列要比target小，表明target不是与start平级的position
#                 if the_pattern.topo_sort_sequence.index(j['pID']) > the_pattern.topo_sort_sequence.index(target):
#                     continue
#                 else:
#                     return False
#             return True

"""新的函数已经准备好，而且效果更佳"""
# def points_distance(the_pattern, start, target):
#     """
#     计算两个点之间的距离,该距离是不带权意义的距离，智能从拓扑序列的前列向后找，利用了类似最短路径算法
#     :param the_pattern:
#     :param start: 开始的位置
#     :param target: 目标位置
#     :return: start与point之间的距离（无权重）,如果start不能到达target，返回None
#              祖传代码，切勿乱改
#     """
#     # 如果target的拓扑序列大于start则代表没有路径
#     if the_pattern.topo_sort_sequence.index(start) > the_pattern.topo_sort_sequence.index(target):
#         return None
#     # is in between表示的意思是，target的拓扑序列在start与所有start的后继节点的中间，
#     # 这种情况下，不存在路径能够从start到达target
#     if is_in_between(the_pattern, start, target):
#         return None
#
#     know = [False] * len(the_pattern.topo_sort_sequence)  # 该点是否已经遍历的标志位
#     distance = [inf] * len(the_pattern.topo_sort_sequence)  # 存储距离
#     pre_p = ['-1'] * len(the_pattern.topo_sort_sequence)  # 存储计算的当前距离的上一个点
#     # 初始化程序中保存当前点的变量
#     now = the_pattern.topo_sort_sequence.index(start)
#     old_now = None
#     distance[now] = 0  # 初始点与初始点的距离设置为0
#     # 格局的最短路径算法实现
#
#     for i in the_pattern.positions:
#         if the_pattern.topo_sort_sequence[now] == i['pID']:
#             for j in i['next_position']:
#                 distance[the_pattern.topo_sort_sequence.index(j['pID'])] = 1
#                 pre_p[the_pattern.topo_sort_sequence.index(j['pID'])] = the_pattern.topo_sort_sequence[now]
#     know[now] = True
#
#     while old_now != now:
#         unknown = []
#         tempd = distance.copy()
#         for i in range(len(the_pattern.topo_sort_sequence)):
#             if know[i] == False:
#                 unknown.append(i)  # 此处找出来了unknown的列表
#         for i in range(len(the_pattern.topo_sort_sequence)):
#             if i not in unknown:
#                 tempd[i] = inf
#         old_now = now
#         now = tempd.index(min(tempd))
#
#         for i in the_pattern.positions:
#             if the_pattern.topo_sort_sequence[now] == i['pID']:
#                 for j in i['next_position']:
#                     if distance[the_pattern.topo_sort_sequence.index(j['pID'])] > distance[now] + 1:
#                         distance[the_pattern.topo_sort_sequence.index(j['pID'])] = distance[now] + 1
#                         pre_p[the_pattern.topo_sort_sequence.index(j['pID'])] = the_pattern.topo_sort_sequence[now]
#
#         know[now] = True
#     if not know[the_pattern.topo_sort_sequence.index(target)]:
#         return None
#     path = []
#     tp = target
#     while tp != '-1':
#         path.append(tp)
#         tp = pre_p[the_pattern.topo_sort_sequence.index(tp)]
#     return distance[the_pattern.topo_sort_sequence.index(target)], list(reversed(path))
#
# 新的函数效果更佳
# def get_best_way(the_pattern, start, target):
#     """
#     获得起始点与目标点的最佳路径，是带权（权核可能为负）有向无环图的最短路径算法实现。
#     :param target: an ID of a position on pattern
#     :param start: an ID of a position on pattern
#     :return: a path of lowest cost to target and the cost or None if no path from start to target
#              如果start不能到达target，返回None
#              祖传代码，切勿乱改
#     """
#     # 首先判断start的拓扑序列是否大于target，如果大于则表示不可达，直接return None
#     if the_pattern.topo_sort_sequence.index(start) > the_pattern.topo_sort_sequence.index(target):
#         return None
#     # 如果target的拓扑序列小于start，但是start的所有后继点的拓扑序列都大于target，表明从start到target没有路径
#     if is_in_between(the_pattern, start, target):
#         return None
#     know = [False] * len(the_pattern.topo_sort_sequence)
#     distance = [inf] * len(the_pattern.topo_sort_sequence)  # 存储当前距离
#     pre_p = ['-1'] * len(the_pattern.topo_sort_sequence)  # 存储计算的当前距离的上一个点
#     now = the_pattern.topo_sort_sequence.index(start)
#     old_now = None
#     distance[now] = 0  # 代表自己
#     for i in the_pattern.positions:
#         if the_pattern.topo_sort_sequence[now] == i['pID']:
#             for j in i['next_position']:
#                 distance[the_pattern.topo_sort_sequence.index(j['pID'])] = round(i['weight'] - j['weight'], 5)
#                 pre_p[the_pattern.topo_sort_sequence.index(j['pID'])] = the_pattern.topo_sort_sequence[now]
#     know[now] = True
#     # 当now不再更新，说明找不到更短的路径后
#     while old_now != now:
#         unknown = []
#         tempd = distance.copy()
#         for i in range(len(the_pattern.topo_sort_sequence)):
#             if know[i] == False:
#                 unknown.append(i)  # 此处找出来了还有哪些点没有遍历到
#         for i in range(len(the_pattern.topo_sort_sequence)):
#             if i not in unknown:
#                 tempd[i] = inf
#         old_now = now
#         now = tempd.index(min(tempd))
#         for i in the_pattern.positions:
#             if the_pattern.topo_sort_sequence[now] == i['pID']:
#                 for j in i['next_position']:
#                     if distance[the_pattern.topo_sort_sequence.index(j['pID'])] > distance[now] + i['weight'] - j[
#                         'weight']:
#                         distance[the_pattern.topo_sort_sequence.index(j['pID'])] = distance[now] + i['weight'] - j[
#                             'weight']
#                         pre_p[the_pattern.topo_sort_sequence.index(j['pID'])] = the_pattern.topo_sort_sequence[now]
#         know[now] = True
#     if not know[the_pattern.topo_sort_sequence.index(target)]:
#         return None
#     path = []
#     tp = target
#     while tp != '-1':
#         path.append(tp)
#         tp = pre_p[the_pattern.topo_sort_sequence.index(tp)]
#     return distance[the_pattern.topo_sort_sequence.index(target)], list(reversed(path))
def points_distance(the_pattern, start, target):
    """

    :param the_pattern:
    :param start:
    :param target:
    :return: 路径的深度与路径的内容
    """
    if the_pattern.position_link_path[start][target] is np.nan:
        return None
    path = [target]
    mid_position = the_pattern.position_link_path[start][target]
    while mid_position != start:
        path.append(mid_position)
        mid_position = the_pattern.position_link_path[start][mid_position]
    path.append(start)
    return len(path) - 1, list(reversed(path))

def get_best_way(the_pattern, start, target):
    """
    获得起始点与目标点的最佳路径，是带权（权核可能为负）有向无环图的最短路径算法实现。
    :param target: an ID of a position on pattern
    :param start: an ID of a position on pattern
    :return: a path of lowest cost to target and the cost or None if no path from start to target
             如果start不能到达target，返回None
             祖传代码，切勿乱改
    """
    w = the_pattern.position_link_matrix[start][target]
    if w == np.inf:
        return None
    path = [target]
    mid_position = the_pattern.position_link_path[start][target]
    while mid_position != start:
        path.append(mid_position)
        mid_position = the_pattern.position_link_path[start][mid_position]
    path.append(start)
    return w, list(reversed(path))

if __name__ == '__main__':
    a = pattern(xml_dom=read_xml("pattern1.xml"))
    # print('start')
    print(get_best_way(a, 'p24', 'p22'))
    print(points_distance(a, 'p24', 'p22'))


''' jinja filters
formatters of sorts
'''
from application import app

@app.template_filter('dictionary_value')
def dictionary_value(dictionary, key):
    ''' returns the value of dictionary[key]
    usage in jinja template:
        temp: {{ data|dictionary_value('temp') }}
    '''
    if key in dictionary:
        return dictionary[key]
    else:
        return None

@app.template_filter('abbreviate')
def abbreviate(word, length, remove='end'):
    ''' turns long phrases into something like 'asdf123..'
    the 'remove' parameter determines which part of the string to drop
    usage in jinja template:
        call ID: {{ response.call_sid }}
        call ID: {{ response.call_sid|abbreviate(7, remove='start') }}
    yields something like:
        call ID: SIDabcdefgh1234
        call ID: ..fgh1234
    '''
    if not word:
        return word

    try:
        word = unicode(word.encode('utf-8'), 'utf8')
    except:
        # fails on bson objectIds
        word = str(word)

    if len(word) <= length:
        return word

    if remove == 'start':
        # drop the beginning of the word
        return '..' + word[len(word)-length:]
    else:
        # drop the end
        return word[0:length] + '..'

@app.template_filter('_format_datetime')
def _format_datetime(dt, formatting='medium'):
    ''' jinja filter for displaying datetimes
    added the unfortunate try/except block to catch incoming 'None' values..
    usage in the jinja template:
        publication date: {{ article.pub_date|_format_datetime('full') }}
    '''
    try:
        if formatting == 'full':
            return dt.strftime('%A %B %d, %Y at %H:%M:%S')
        if formatting == 'medium':
            return dt.strftime('%B %d, %Y at %H:%M:%S')
        if formatting == 'full-day':
            return dt.strftime('%A %B %d, %Y')
        if formatting == 'short-date-with-time':
            return dt.strftime('%d/%m/%y %H:%M:%S')
        if formatting == 'full-date':
            return dt.strftime('%A, %Y/%m/%d %I:%M %p')
        if formatting == 'day-month-year':
            return dt.strftime('%B %d, %Y')
        if formatting == 'hours-minutes-seconds':
            return dt.strftime('%H:%M:%S')
        if formatting == 'time-with-period':
            return dt.strftime('%I:%M %p')
    except:
        return dt


#!/usr/bin/python3
from accessoryFunctions.accessoryFunctions import make_path, MetadataObject, printtime
from accessoryFunctions.metadataprinter import MetadataPrinter
from spadespipeline.typingclasses import Resistance, Virulence
from sixteenS.sixteens_full import SixteenS as SixteensFull
from MLSTsippr.mlst import GeneSippr as MLSTSippr
from customsippr.customsippr import CustomGenes
from sipprverse_reporter.reports import Reports
from sipprCommon.objectprep import Objectprep
from sipprCommon.sippingmethods import Sippr
from serosippr.serosippr import SeroSippr
import MASHsippr.mash as mash
from argparse import ArgumentParser
import multiprocessing
import subprocess
import time
import os

__author__ = 'adamkoziol'

class Sipprverse(object):

    def main(self):
        """
        Run the necessary methods in the correct order
        """
        printtime('Starting {} analysis pipeline'.format(self.analysistype), self.starttime)
        # Create the objects to be used in the analyses
        objects = Objectprep(self)
        objects.objectprep()
        self.runmetadata = objects.samples
        self.threads = int(self.cpus / len(self.runmetadata.samples)) if self.cpus / len(self.runmetadata.samples) > 1 \
            else 1
        if self.genesippr:
            # Run the genesippr analyses
            self.analysistype = 'genesippr'
            self.targetpath = os.path.join(self.reffilepath, self.analysistype)
            Sippr(self, 0.90)
            # Create the reports
            self.reports = Reports(self)
            Reports.reporter(self.reports)
        if self.sixteens:
            # Run the 16S analyses
            SixteensFull(self, self.commit, self.starttime, self.homepath, 'sixteens_full', 0.985)
        if self.rmlst:
            MLSTSippr(self, self.commit, self.starttime, self.homepath, 'rMLST', 1.0, True)
        if self.resistance:
            # ResFinding
            res = Resistance(self, self.commit, self.starttime, self.homepath, 'resfinder', 0.70, False, True)
            res.main()
        if self.virulence:
            vir = Virulence(self, self.commit, self.starttime, self.homepath, 'virulence', 0.95, False, True)
            vir.reporter()
        if self.closestreference:
            self.pipeline = True
            mash.Mash(self, 'mash')
        if self.gdcs:
            # Run the GDCS analysis
            self.analysistype = 'GDCS'
            self.targetpath = os.path.join(self.reffilepath, self.analysistype)
            Sippr(self, 0.95)
            # Create the reports
            Reports.gdcsreporter(self.reports)
        if self.mlst:
            self.genus_specific()
            MLSTSippr(self, self.commit, self.starttime, self.homepath, 'MLST', 1.0, True)
        # Optionally perform serotyping
        if self.serotype:
            self.genus_specific()
            SeroSippr(self, self.commit, self.starttime, self.homepath, 'serosippr', 0.90, True)
        if self.user_genes:
            custom = CustomGenes(self)
            custom.main()
        # Print the metadata
        printer = MetadataPrinter(self)
        printer.printmetadata()

    def genus_specific(self):
        """
        For genus-specific targets, MLST and serotyping, determine if the closest refseq genus is known - i.e. if 16S
        analyses have been performed. Perform the analyses if required
        """
        # Initialise a variable to store whether the necessary analyses have already been performed
        closestrefseqgenus = False
        for sample in self.runmetadata.samples:
            if sample.general.bestassemblyfile != 'NA':
                try:
                    closestrefseqgenus = sample.general.closestrefseqgenus
                except KeyError:
                    pass
        # Perform the 16S analyses as required
        if not closestrefseqgenus:
            printtime('Must perform 16S analyses', self.starttime)
            # Run the 16S analyses
            SixteensFull(self, self.commit, self.starttime, self.homepath, 'sixteens_full', 0.985)

    def __init__(self, args, pipelinecommit, startingtime, scriptpath):
        """
        :param args: command line arguments
        :param pipelinecommit: pipeline commit or version
        :param startingtime: time the script was started
        :param scriptpath: home path of the script
        """
        # Initialise variables
        self.commit = str(pipelinecommit)
        self.starttime = startingtime
        self.homepath = scriptpath
        self.args = args
        # Define variables based on supplied arguments
        self.path = os.path.join(args.outputpath)
        assert os.path.isdir(self.path), u'Supplied path is not a valid directory {0!r:s}'.format(self.path)
        self.sequencepath = os.path.join(args.sequencepath)
        self.seqpath = self.sequencepath
        self.targetpath = os.path.join(args.referencefilepath)
        # ref file path is used to work with submodule code with a different naming scheme
        self.reffilepath = self.targetpath
        self.reportpath = os.path.join(self.path, 'reports')
        make_path(self.reportpath)
        assert os.path.isdir(self.targetpath), u'Target path is not a valid directory {0!r:s}' \
            .format(self.targetpath)
        # Set the custom cutoff value
        self.cutoff = args.customcutoffs
        # Use the argument for the number of threads to use, or default to the number of cpus in the system
        self.cpus = int(args.numthreads if args.numthreads else multiprocessing.cpu_count())
        self.closestreference = args.closestreference
        self.gdcs = args.gdcs
        self.genesippr = args.genesippr
        self.mlst = args.mlst
        self.resistance = args.resistance
        self.rmlst = args.rmlst
        self.serotype = args.serotype
        self.sixteens = args.sixteens
        self.virulence = args.virulence
        self.averagedepth = args.averagedepth
        try:
            self.user_genes = os.path.join(args.user_genes)
            assert os.path.isfile(self.user_genes), 'Cannot find user-supplied target file: {targets}. Please ' \
                                                    'double-check name and path of file'\
                .format(targets=self.user_genes)
        except TypeError:
            self.user_genes = args.user_genes
        # Set all the analyses to True if the full_suite option was selected
        if args.full_suite:
            self.closestreference = True
            self.gdcs = True
            self.genesippr = True
            self.mlst = True
            self.resistance = True
            self.rmlst = True
            self.serotype = True
            self.sixteens = True
            self.virulence = True
        self.reports = str()
        self.threads = int()
        self.runmetadata = MetadataObject()
        self.taxonomy = {'Escherichia': 'coli', 'Listeria': 'monocytogenes', 'Salmonella': 'enterica'}
        self.analysistype = 'GeneSippr'
        self.pipeline = False
        self.logfile = os.path.join(self.path, 'log')

if __name__ == '__main__':
    # Get the current commit of the pipeline from git
    # Extract the path of the current script from the full path + file name
    homepath = os.path.split(os.path.abspath(__file__))[0]
    # Find the commit of the script by running a command to change to the directory containing the script and run
    # a git command to return the short version of the commit hash
    commit = subprocess.Popen('cd {} && git rev-parse --short HEAD'.format(homepath),
                              shell=True, stdout=subprocess.PIPE).communicate()[0].rstrip()
    # Parser for arguments
    parser = ArgumentParser(description='Performs GeneSipping on folder of FASTQ files')
    parser.add_argument('-o', '--outputpath',
                        required=True,
                        help='Path to directory in which report folder is to be created')
    parser.add_argument('-s', '--sequencepath',
                        required=True,
                        help='Path of .fastq(.gz) files to process.')
    parser.add_argument('-r', '--referencefilepath',
                        required=True,
                        help='Provide the location of the folder containing reference database')
    parser.add_argument('-a', '--averagedepth',
                        default=2,
                        help='Cutoff value for mapping depth to use when parsing BAM files.')
    parser.add_argument('-n', '--numthreads',
                        help='Number of threads. Default is the number of cores in the system')
    parser.add_argument('-c', '--customcutoffs',
                        default=0.90,
                        help='Custom cutoff values')
    parser.add_argument('-F', '--full_suite',
                        action='store_true',
                        default=False,
                        help='Perform all the built-in GeneSippr analyses (AMR, GDCS, Genesippr, MASH, MLST, '
                             'rMLST, Serotype, SixteenS, and Virulence')
    parser.add_argument('-A', '--resistance',
                        action='store_true',
                        default=False,
                        help='Perform AMR analysis on samples')
    parser.add_argument('-C', '--closestreference',
                        action='store_true',
                        default=False,
                        help='Determine closest RefSeq match with mash')
    parser.add_argument('-G', '--genesippr',
                        action='store_true',
                        default=False,
                        help='Perform GeneSippr analysis on samples')
    parser.add_argument('-M', '--mlst',
                        action='store_true',
                        default=False,
                        help='Perform MLST analysis on samples')
    parser.add_argument('-Q', '--gdcs',
                        action='store_true',
                        default=False,
                        help='Perform GDCS Quality analysis on samples')
    parser.add_argument('-R', '--rmlst',
                        action='store_true',
                        default=False,
                        help='Perform rMLST analysis on samples')
    parser.add_argument('-S', '--serotype',
                        action='store_true',
                        default=False,
                        help='Perform serotype analysis on samples determined to be Escherichia')
    parser.add_argument('-U', '--user_genes',
                        default=False,
                        help='Name and path of user provided (multi-)FASTA file of genes to run against samples')
    parser.add_argument('-V', '--virulence',
                        action='store_true',
                        default=False,
                        help='Perform virulence analysis on samples')
    parser.add_argument('-X', '--sixteens',
                        action='store_true',
                        default=False,
                        help='Perform 16S typing of samples')
    # Get the arguments into an object
    arguments = parser.parse_args()

    # Define the start time
    start = time.time()

    # Run the script
    sippr = Sipprverse(arguments, commit, start, homepath)
    sippr.main()

    # Print a bold, green exit statement
    print('\033[92m' + '\033[1m' + "\nElapsed Time: %0.2f seconds" % (time.time() - start) + '\033[0m')


from pyowm import OWM
import datetime

owm = OWM("166dc9f8a386105b21687e8f50bad441")
mgr = owm.weather_manager()
language = "ru"

def get_weather(city):

    observation = mgr.weather_at_place(city)
    w = observation.weather
    data = w.temperature('celsius')
    time = datetime.datetime.now()

    if data['temp'] < 10:
        advice = "Сейчас очень холодно, одевайтесь по теплее! "
    elif data['temp'] < 15:
        advice = "На улице холодно, можете одется легко! "
    else:
        advice="на улице тепло"
    temperatur = data['temp']
    text = f"Температура:{temperatur}\n Время: {time}\n Совет: {advice}"
    return text


from scipy import stats
from sklearn.metrics import mean_squared_error
import numpy as np

def pearson(y, pred):
    pear = stats.pearsonr(y, pred)
    pear_value = pear[0]
    pear_p_val = pear[1]
    print("Pearson correlation is {} and related p_value is {}".format(pear_value, pear_p_val))
    return pear_value

def spearman(y, pred):
    spear = stats.spearmanr(y, pred)
    spear_value = spear[0]
    spear_p_val = spear[1]
    print("Spearman correlation is {} and related p_value is {}".format(spear_value, spear_p_val))
    return spear_value

def mse(y, pred):
    err = mean_squared_error(y, pred)
    print("Mean squared error is {}".format(err))
    return err

def squared_error(y,pred):
    errs = []
    for i in range(y.shape[0]):
        err = (y[i]-pred[i]) * (y[i]-pred[i])
        errs.append(err)
    return np.asarray(errs)


import sys
class Solution:
    """
    @param A: an array
    @return: the maximum value of F(0), F(1), ..., F(n-1)
    """
    def maxRotateFunction(self, A):
        # Write your code here
        n = len(A)
        f = [0] * 2
        total = 0
        sum = 0
        for i in range(n):
            total += i * A[i]
            sum += A[i]
        f[0] = total

        maxi = f[0]

        for i in range(1, n):
            f[i % 2] = f[(i - 1) % 2] + sum - n * A[-i]
            maxi = max(maxi, f[i % 2])
        return maxi


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2016-07-04 10:00:24
# @Author  : HungChi
# @Site    :
# @File    : text_Deduplication.py
# @Software: PyCharm

import sys
import os
import collections
def bar(now,total):
    sys.stdout.write('\r')
    sys.stdout.write("[%s>%s] %s" % ('-'*int(100*now/total), ' '*int(100*(total-now)/total),str(int(100*(now+1)/total))+'%'))
    sys.stdout.flush()
def sort_by_count(d):
    #字典排序
    d = collections.OrderedDict(sorted(d.items(), key = lambda t: -t[1]))
    return d
def main():
    keys_dic = {}
    for arg in sys.argv[1:]:
        print("Input file "+arg)
        with open(arg,'rt',encoding='UTF-8') as _i_f:
            # keys_dic = dict(keys_dic,**{}.fromkeys([l.strip("\n") for l in _i_f.readlines()]))

            # for word in ['#'.join(l.strip("\n").split('#')[1:]) for l in _i_f]:
            for word in [l.strip("\n") for l in _i_f]:
                if word not in keys_dic:
                    keys_dic[word] = 0
                keys_dic[word] += 1
    # for k,v in keys_dic.items():
    #     print("dict[%s]=" % k,v)
    # keys = keys_dic.keys()
    # print(keys)
    # print(keys_dic)
    file_name = ''.join(map(str, list(os.path.splitext(arg))[0:-1]))+"_all_"+list(os.path.splitext(arg))[-1]
    # print(file_name)
    with open(file_name,'a+',encoding='UTF-8') as _o_f:
        print("output file "+file_name)
        # [_o_f.writelines(key + "," + str(value) + "\n") for key, value in sort_by_count(keys_dic).items()]
        [_o_f.writelines(key + "\n") for key, value in sort_by_count(keys_dic).items()]

if __name__ == '__main__':
    main()


names = ['Michael', 'Bob', 'Tracy']
for name in names:
    print('Hello, %s' % name)

sum = 0
for x in list(range(101)):
    sum = sum+x

print(sum)

num = 0
n = 1

while n<100:
    num = num + n
    n = n+2

print(num)

n = 1
while n <= 100:
    if n > 10:
        break
    print(n)
    n = n + 1
print('END')

m = 0
while m < 10:
    m = m+1
    if m%2 ==0:
        continue
    print(m)


# Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.
import json
import requests
from bs4 import BeautifulSoup
import smtplib
import configparser

def alert_via_email(url):

    header = {"user-agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"}
    email_msg = ""
    # url = "https://www.avaloncommunities.com/california/san-jose-apartments/avalon-on-the-alameda/apartments?bedroom=2BD"

    page = requests.get(url, headers=header)
    soup = BeautifulSoup(page.content, 'html.parser')
    cards = soup.find_all(class_="apartment-card")
    email_content = []
    for card in cards:
        if card.find_all(class_="special-tag"):
            text = card.find(class_="content").find(class_="availability").get_text()
            price = card.find(class_="content").find(class_="price").get_text()
            price_in_int = price.replace(',','')[1:6]
            msg = ""
            if 'Dec' in text:
                msg="available special on month december \n availability:"+text+" \n price:"+price[0:6]
            email_content.append(msg)

    if(len(email_content) > 0):
        send_msg = '\n'.join(email_content)
        print(send_msg)
        send_email(send_msg)
    else:
        send_email("nothing new today!")

def send_email(send_msg):
    config = configparser.ConfigParser()
    config.read('email_info.ini')

    sender_email = 'shravaniparsi26@gmail.com'
    receiver_email = 'vishwakt@gmail.com'
    password_for_email = 'iamthegreatpinku'
    SUBJECT = "ALERT : Price Dropped for items your are tracking"
    message = 'Subject: {}\n\n{}'.format(SUBJECT, send_msg)
    fmt = 'From: {}\r\nTo: {}\r\nSubject: {}\r\n{}'

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(sender_email,password_for_email)
    print("login is green")
    server.sendmail(sender_email,receiver_email,fmt.format(receiver_email, sender_email, SUBJECT, message).encode('utf-8'))
    print("email is sent")
    server.quit()

def main():
    alert_via_email("https://www.avaloncommunities.com/california/san-jose-apartments/avalon-morrison-park/apartments?bedroom=2BD")
    alert_via_email("https://www.avaloncommunities.com/california/san-jose-apartments/avalon-on-the-alameda/apartments?bedroom=2BD")

if __name__ == '__main__':
    main()


#Copyright (c) 2012, Walter Bender

# Usage: Import this code into a Python (user-definable) block; when
# this code is run, the turtle will draw a line of the length of the
# numeric argument block docked to the Python block. But before
# drawing the line, it pushes the rgb values of the destination to the
# FILO.

def myblock(tw, name):
    ''' '''

    def _prim_forward_push(tw, line_length):
        try:  # make sure line_length is a number
            line_length = float(line_length)
        except ValueError:
            return
        penstatus = tw.canvas.pendown
        tw.canvas.setpen(False)
        tw.canvas.forward(line_length)
        r, g, b, a = tw.canvas.get_pixel()
        tw.lc.heap.append(b)
        tw.lc.heap.append(g)
        tw.lc.heap.append(r)
        tw.canvas.forward(-line_length)
        tw.canvas.setpen(penstatus)
        tw.canvas.forward(line_length)
        return

    from TurtleArt.tapalette import make_palette, palette_name_to_index
    from TurtleArt.talogo import primitive_dictionary
    from gettext import gettext as _

    # Choose a palette for the new block.
    palette = make_palette('turtle')

    primitive_dictionary['forwardpush'] = _prim_forward_push

    # Create a new block prototype.
    palette.add_block('forwardpush',
                      style='basic-style-1arg',
                      label=name,
                      default=100,
                      prim_name='forwardpush',
                      help_string=_('push destination rgb value to heap'))

    # Add its primitive to the LogoCode dictionary.
    tw.lc.def_prim('forwardpush', 1,
                   lambda self, x: primitive_dictionary['forwardpush'](tw, x))

    # Regenerate the palette, which will now include the new block.
    tw.show_toolbar_palette(palette_name_to_index('turtle'),
                            regenerate=True)


# Code for converting a FontFeatures object into feaLib statements
import fontTools.feaLib.ast as feaast

def add_language_system_statements(self, ff):
    self.hoist_languages()
    if len(self.scripts_and_languages.keys()) == 0:
        return
    if len(self.scripts_and_languages.keys()) == 1:
        return
    for s, entry in self.scripts_and_languages.items():
        for l in entry:
            ff.statements.append(feaast.LanguageSystemStatement(s, l))

def asFea(self):
    return self.asFeaAST().asFea()

def asFeaAST(self):
    """Returns this font's features as a feaLib AST object, for later
  translation to AFDKO code."""
    from fontFeatures import Routine

    ff = feaast.FeatureFile()

    add_language_system_statements(self, ff)

    # Preamble
    for k in self.routines:
        assert isinstance(k, Routine)
        if not k.name:
            k.name = self.gensym("Routine_")
        pre = k.feaPreamble(self)
        for s in pre:
            ff.statements.append(s)
    for k, v in self.features.items():
        for r in v:
            pre = r.feaPreamble(self)
            for s in pre:
                ff.statements.append(s)

    for k, v in self.namedClasses.items():
        asclass = feaast.GlyphClass([feaast.GlyphName(x) for x in v])
        ff.statements.append(feaast.GlyphClassDefinition(k, asclass))

    ff.statements.append(feaast.Comment(""))

    for k in self.routines:
        if not k.inlined:
            ff.statements.append(k.asFeaAST())

    for k, v in self.features.items():
        f = feaast.FeatureBlock(k)
        for n in v:
            # If it's a routine and it's in self.routines, use a reference
            if isinstance(n, Routine) and n in self.routines:
                f.statements.append(feaast.LookupReferenceStatement(n.asFeaAST()))
            elif not isinstance(n, Routine):
                r = Routine(rules=[n], parent=self)
                if hasattr(n, "languages"):
                    r.languages = n.languages
                f.statements.append(r.asFeaAST())
            else:
                f.statements.append(n.asFeaAST())
        ff.statements.append(f)
    return ff


############ The greedy algorithm for exemplar clustering #########
# An implementation of the greedy algorithm that optimizes a function f()
# under a cardinality constraint k. Also contains an implementation of the
# examplar-based clustering function f() from
# https://las.inf.ethz.ch/files/mirzasoleiman13distributed.pdf

import copy

# The distance function, simple hamming distance for testing purposes
def d(e1, e2):
    score = 0
    for i in range(len(e1)):
        if e1[i] != e2[i]:
            score += 1
    return score

# The loss function for the k-medoid problem defined in Section 3.1
# of https://las.inf.ethz.ch/files/mirzasoleiman13distributed.pdf
# Input:
#   S: a list of elements which are the exemplars
#   D: a list of elements correponding to the ground set of elements
# Output:
#   An integer corresponding to the loss from having S as exemplars
# Dependencies:
#   uses the distance function d(.,.) that is dependent on the application
def L(e0, D, new, closest):
    score = 0
    for e1 in D:
        score += min(closest[str(e1)], d(e1, new))
    return score

def loss(S,D):
    score = 0
    for e1 in D:
        closest = 10000
        for e2 in S:
            dist = d(e1,e2)
            if dist < closest:
                closest = dist
        score += closest
    return score

"""
    # Computes the value of set S over ground set D as described in Section 3.1
    # of https://las.inf.ethz.ch/files/mirzasoleiman13distributed.pdf
    # Input:
    #   S: a list of elements for which we want the value
    #   D: a list of elements correponding to the ground set of elements
    #   e0: an auxiliary element
    # Output:
    #   An integer corresponding to the value of S
    # Dependencies:
    #   uses the loss L() function defined above
    #def f(S, D, e0):
    #    return  - L(S,e0, D)
    """

# The classical greedy algorithm for maximizing f() with at most k elements
# Input:
#   V: a list of elements that are exemplars candidates
#   D: a list of elements that the exemplars should represent
#     (V = D on local machines but not on central machine)
#   k: an integer that is the cardinality constraint for greedy
#   e0: an auxiliary element
# Output:
#   S: a list of k elements from V that represent D well
# Dependencies:
#   uses the function f() that we wish to optimize defined above
def greedy(V, D, k, e0):
    S = []
    closest = dict()
    losse0 = 0
    for e in D:
        loss = d(e,e0)
        closest[str(e)] = loss
        losse0 += loss
    for i in range(k):
        bestElement = V[0]
        lS = L(e0, D,e0,closest)
        bestContribution = lS - L(e0, D,V[0],closest)
        for e in V:
            contribution = lS - L(e0, D,e,closest)
            if contribution > bestContribution:
                bestElement = e
                bestContribution = contribution
        S.append(bestElement)
        for e in D:
            distBeste = d(e,bestElement)
            if distBeste < closest[str(e)]:
                closest[str(e)] = distBeste
    score = losse0 - L(e0,D,e0,closest)
    return (S,score)

def score(S,D,e0):
    copyS = copy.deepcopy(S)
    copyS.append(e0)
    return loss([e0],D) - loss(copyS,D)


import logging
import time
import requests

logging.basicConfig()
logger = logging.getLogger('core.scrapers')
logger.setLevel(logging.DEBUG)

def get_ms_timestamp():
    return int((time.time() + 0.5) * 1000)

def scrape():
    logger.info('[ANYCOINDIRECT] Started lambda handler')

    ts = get_ms_timestamp()
    resp_buy = requests.get('https://anycoindirect.eu/en/buy/fiatpricev2?fiatCode=EUR&coinAmount=1&coinCode=BTC&paymentMethodId=1&nonce=%s&_=%s' % (ts, ts), timeout=3)
    resp_sell = requests.get('https://anycoindirect.eu/en/sell/fiatamountv2?fiatCode=EUR&coinCode=BTC&coins=1&nonce=%s&_=%s' % (ts, ts), timeout=3)
    resp_sell.raise_for_status()

    point_buy = resp_buy.json()
    point_buy = point_buy['Data']

    point_sell = resp_sell.json()
    point_sell = point_sell['Data']

    result = {
        'buy': float(point_buy['FiatPrice']),
        'sell': float(point_sell['TotalFiatPrice']),
    }

    logger.info('[ANYCOINDIRECT] Scraped pricepoint, buy: {}, sell: {}'.format(result['buy'], result['sell']))

    return result


"""
Photodiode Coupling
===================
"""

def run():
    from PyMieSim.source import PlaneWave
    from PyMieSim.detector import LPmode
    from PyMieSim.scatterer import Sphere

    source = PlaneWave(
        wavelength=450e-9,
        polarization=0,
        amplitude=1
    )

    detector = LPmode(
        mode_number="1-1",
        sampling=600,
        NA=0.2,
        gamma_offset=180,
        phi_offset=0,
        coupling_mode='Point'
    )

    scatterer = Sphere(
        diameter=300e-9,
        source=source,
        index=1.4
    )

    coupling = detector.coupling(scatterer=scatterer)

    print(coupling)  # 6.566085549292496e-18 Watt  (6.57e-03 fWatt)

if __name__ == '__main__':
    run()

# -


from flask import Flask, render_template, url_for, flash, redirect
from flask_wtf import FlaskForm
from wtforms import SelectMultipleField, SubmitField, SelectField
import predictions

app = Flask(__name__)

app.config['SECRET_KEY'] = '5791628bb0b13ce0c676dfde280ba245'

class SymptomForm(FlaskForm):
    symptom1 = SelectField('Symptom1', choices=[(x,x) for x in predictions.l1])
    symptom2 = SelectField('Symptom2', choices=[(x,x) for x in predictions.l1])
    symptom3 = SelectField('Symptom3', choices=[(x,x) for x in predictions.l1])
    submit = SubmitField('Submit')

symptoms = []
@app.route("/", methods=['GET', 'POST'])
def main():
    form = SymptomForm()
    if form.validate_on_submit():
        flash('Symptoms submitted', 'success')
        value1 = dict(form.symptom1.choices).get(form.symptom1.data)
        value2 = dict(form.symptom2.choices).get(form.symptom2.data)
        value3 = dict(form.symptom3.choices).get(form.symptom3.data)
        symptoms.append(value1)
        symptoms.append(value2)
        symptoms.append(value3)
        disease = predictions.NaiveBayes(symptoms)
        return redirect(url_for('result', name =disease))
    return render_template('main.html', form=form)

@app.route("/result")
def result():
    disease = predictions.NaiveBayes(symptoms)
    return render_template("results.html", name =disease)

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


from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.response import Response

from django.shortcuts import get_object_or_404
from django.http import Http404

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import generics

# importar modelo
from Login.models import Example2
# importar serializer
from Login.serializer import Example2Serializers

class ExampleList2(APIView):
    def get(self, request, format=None):
        print("Metodo get filter")
        queryset = Example2.objects.filter(delete=False)
        # many=True Si aplica si retorno multiples objetos
        serializer = Example2Serializers(queryset, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = Example2Serializers(data=request.data)
        if serializer.is_valid():
            serializer.save()
            datas = serializer.data
            return Response(datas)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class CustonAuthToken(ObtainAuthToken):

    def post(self, request, * args, **kwars):
        serializer = self.serializer_class(data=request.data,
                                           context={
                                               'request': request,
                                           }
                                           )
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)

        return Response({
            'token': token.key,
            'user_id': user.pk,
            'username': user.username
        })


import os
import time
import glob
import hd47780 as lcdModule
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setup(16, GPIO.OUT)
GPIO.setup(20, GPIO.OUT)

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

class TempSensorDS18B20():
    __sensorPath={}
    __sensorID=0
    __sensorList=[]
    __sensorName=""

    def __init__(self, sensid=None, path=None):

        self.__sensorID=sensid or self.__setID()
        self.__sensorPath[self.__sensorID]=path or self.__setPath()
        self.__setName()

    def __readPath(self):

        self.__sensorList=glob.glob('/sys/bus/w1/devices/28-*')

    def __checkPath(self):

        if os.path.exists(self.__sensorPath[self.__sensorID])==True:
            print('path ok')
            self.__checkData()
        else:
            print("Brak dostepu do sciezki %s"%self.__sensorPath[self.__sensorID]+' - usuwam niesprawny czujnik')
            lcdModule.lcdDisplay.setData('DS18B20 ID: %d'%self.__sensorID, lcdModule.lcdDisplay.LINE1)
            lcdModule.lcdDisplay.setData('Uszkodzony!', lcdModule.lcdDisplay.LINE2)
            GPIO.output(20, 1)
            self.__del__()
    def __checkData(self):

        f=open(self.__sensorPath[self.__sensorID], 'r')
        dataRead=f.readlines()
        f.close()
        endOfLine=dataRead[0].find('\n')
        dataReadErr=dataRead[0].strip()[endOfLine-2:]
        if dataReadErr=='NO':
            print('Problem z odczytem na czujniku %s' %self.__sensorPath[self.__sensorID])
            lcdModule.lcdDisplay.setData('DS18B20 ID: %d'%self.__sensorID, lcdModule.lcdDisplay.LINE1)
            lcdModule.lcdDisplay.setData('Error', lcdModule.lcdDisplay.LINE2)
            GPIO.output(16, 0)
            GPIO.output(20, 1)
            time.sleep(0.3)
            GPIO.output(20, 0)
        else:
            print('Odczyt danych na czujniku %s poprawny'%self.__sensorName)
            self.__getData()

    def __getData(self):

        f=open(self.__sensorPath[self.__sensorID], 'r')
        dataRead=f.readlines()
        f.close()
        endOfLine=dataRead[1].find('t=')
        temperature=dataRead[1].strip()[endOfLine+2:]
        temp_c=float(temperature)/1000.0
        print('temperatura na czujniku: %.1f C'%temp_c)
        GPIO.output(16, 1)
        lcdModule.lcdDisplay.setData('DS18B20 ID: %d'%self.__sensorID, lcdModule.lcdDisplay.LINE1)
        lcdModule.lcdDisplay.setData('%.1f C'%temp_c, lcdModule.lcdDisplay.LINE2)

    def getStatus(self):
            self.__checkPath()

    def getName(self):
        return self.__sensorName

    def __del__(self):
        print("USUNIETO CZUJNIK %s"%self.__sensorName)

    def __setID(self):
        self.__sensorList=glob.glob('/sys/bus/w1/devices/28-*')
        print("Dodawanie czujnika temperatury, wykryto czujniki: ")
        for i in range(len(self.__sensorList)):
            print(i+1, self.__sensorList[i])
        sensid=int(input("wybierz z listy powyzej czujnik, ktory chcesz zainstalowac: "))
        return sensid

    def __setPath(self):
        path=self.__sensorList[self.__sensorID-1]+'/w1_slave'
        return path

    def __setName(self):
        self.__sensorName='DS18B20 ID: '+str(self.__sensorID)


#! python3

# TODO:
# Change logo file
# insert inpute for client name and test number
# insert inputs for test standard and furnace size
# insert code that actually fucking does something

import tkinter, shutil, os
from tkinter import *
import PIL
from PIL import Image,ImageTk #pip install pillow

root = Tk()
root.geometry ('555x555')
root.title('imgeCFR')

imge=Image.open('C:\\Users\\gw444\\Downloads\\logo.png');
photo=ImageTk.PhotoImage(imge);

lab=Label(image=photo);
lab.pack();

fn=StringVar()
ln=StringVar()
var1=StringVar()
var2=StringVar()

def exit1():
    exit()
def printt(): #printt command for button
    clientName=fn.get()
    testNo=ln.get()
    testStd=var1.get()
    testScl=var2.get()
    print(f'The test code (and folder name) is {clientName}{testNo}')
    print(f'This is a {testScl} {testStd} test')

''
def makeFoldr():
    clientName=fn.get()
    testNo=ln.get()
    testStd=var1.get()
    testScl=var2.get()
    folderName = clientName + ' ' + testNo;
    folDir = ('C:\TEST REPORTS DATA PHOTOS\\' + folderName)
    os.makedirs('C:\TEST REPORTS DATA PHOTOS\\' + folderName);
    os.makedirs('C:\TEST REPORTS DATA PHOTOS\\' + folderName +'\data');
    os.makedirs('C:\TEST REPORTS DATA PHOTOS\\' + folderName +'\Survey Photos');
    os.makedirs('C:\TEST REPORTS DATA PHOTOS\\' + folderName +'\Test Photos');
    os.makedirs('C:\TEST REPORTS DATA PHOTOS\\' + folderName +'\Obsolete');
    if testScl == 'Full':
        if testStd == 'BS':
                shutil.copy('C:\Templates and Forms CURRENT\Templates for Report writing\Test Data Sheets\Data Sheets\Ful Furnace\BS Test\Data Template Master BS Ful.xlsx', 'C:\TEST REPORTS DATA PHOTOS\\' + folderName +'\data');
        else:
                shutil.copy('C:\Templates and Forms CURRENT\Templates for Report writing\Test Data Sheets\Data Sheets\Ful Furnace\EN Test\Data Template Master EN Ful.xlsx', 'C:\TEST REPORTS DATA PHOTOS\\' + folderName +'\data');
    else:
        if testStd == 'BS':
                shutil.copy('C:\Templates and Forms CURRENT\Templates for Report writing\Test Data Sheets\Data Sheets\Med Furnace\BS Test\Data Template Master Med BS.xlsx', 'C:\TEST REPORTS DATA PHOTOS\\' + folderName +'\data');
        else:
                shutil.copy('C:\Templates and Forms CURRENT\Templates for Report writing\Test Data Sheets\Data Sheets\Med Furnace\EN Test\Data Template Master EN Med.xlsx', 'C:\TEST REPORTS DATA PHOTOS\\' + folderName +'\data');
    os.startfile(folDir)

##window = Tk()
##window.geometry('600x300')
##window.title('Welcome')

#Create title
label1=Label(root,text='Welcome to FolderMakerLite',fg='black',bg='white',relief='flat',font=('arial',16,'bold')).pack()
#label1.place(x=90,y=53)

#Client name: text
label2=Label(root,text='Client name:',fg='black',bg='white',relief='flat',font=('arial',10,'bold'))
label2.place(x=90,y=190)

#Client name user entry
entry1=Entry(root,textvar=fn)
entry1.place (x=240, y=190)

#Test number: text
label3=Label(root,text='Test number:',fg='black',bg='white',relief='flat',font=('arial',10,'bold'))
label3.place(x=90,y=220)

#Test number user entry
entry2=Entry(root,textvar=ln)
entry2.place (x=240, y=220)

#Test standard: text
label4=Label(root,text='Test standard:',fg='black',bg='white',relief='flat',font=('arial',10,'bold'))
label4.place(x=90,y=250)

#Test standard dropbox
list1=['BS','EN']
droplist=OptionMenu(root,var1,*list1)
var1.set('Select standard')
droplist.config(width=15)
droplist.place(x=240, y=250)

#Furnace: text
label5=Label(root,text='Furnace:',fg='black',bg='white',relief='flat',font=('arial',10,'bold'))
label5.place(x=90,y=280)

#Furnace: dropbox
list2=['Med','Full']
droplist=OptionMenu(root,var2,*list2)
var2.set('Select standard')
droplist.config(width=15)
droplist.place(x=240, y=280)

button1=Button(root,text='Produce fucking folder',fg='black',bg='red',relief='ridge',font=('arial',10,'bold'),command=makeFoldr)
button1.place(x=90,y=350)

button2=Button(root,text='Just fuck off',fg='black',bg='red',relief='ridge',font=('arial',10,'bold'), command=exit1)
button2.place(x=350,y=350)

##
##root.mainloop()


# 404. Sum of Left Leaves

# Find the sum of all left leaves in a given binary tree.

# Example:

#    3
#   / \
#  9  20
#    /  \
#   15   7

# There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class sumOfLeftLeaves:

    def doit1(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        def search(node):
            res = 0
            if not node:
                return res

            if node.left and not node.left.left and not node.left.right:
                res += node.left.val

            res += search(node.left) + search(node.right)

            return res

        return search(root)

    def doit(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        node = root
        stack = []
        res = 0

        while node:

            if node.right:
                stack.append(node.right)

            if node.left and not node.left.left and not node.left.right:
                res += node.left.val
                node = None
            else:
                node = node.left

            if not node and stack:
                node = stack.pop()

        return res

if __name__=="__main__":

    a = TreeNode(3)
    a.left = TreeNode(9)
    a.right = TreeNode(20)
    a.right.left, a.right.right = TreeNode(15), TreeNode(7)

    res = sumOfLeftLeaves().doit(a)

    pass


from eth2spec.phase0 import spec
from eth_utils import (
    to_dict, to_tuple
)
from gen_base import gen_runner, gen_suite, gen_typing
from preset_loader import loader

@to_dict
def shuffling_case(seed: spec.Bytes32, count: int):
    yield 'seed', '0x' + seed.hex()
    yield 'count', count
    yield 'shuffled', [spec.get_permuted_index(i, count, seed) for i in range(count)]

@to_tuple
def shuffling_test_cases():
    for seed in [spec.hash(spec.int_to_bytes4(seed_init_value)) for seed_init_value in range(30)]:
        for count in [0, 1, 2, 3, 5, 10, 33, 100, 1000]:
            yield shuffling_case(seed, count)

def mini_shuffling_suite(configs_path: str) -> gen_typing.TestSuiteOutput:
    presets = loader.load_presets(configs_path, 'minimal')
    spec.apply_constants_preset(presets)

    return ("shuffling_minimal", "core", gen_suite.render_suite(
        title="Swap-or-Not Shuffling tests with minimal config",
        summary="Swap or not shuffling, with minimally configured testing round-count",
        forks_timeline="testing",
        forks=["phase0"],
        config="minimal",
        runner="shuffling",
        handler="core",
        test_cases=shuffling_test_cases()))

def full_shuffling_suite(configs_path: str) -> gen_typing.TestSuiteOutput:
    presets = loader.load_presets(configs_path, 'mainnet')
    spec.apply_constants_preset(presets)

    return ("shuffling_full", "core", gen_suite.render_suite(
        title="Swap-or-Not Shuffling tests with mainnet config",
        summary="Swap or not shuffling, with normal configured (secure) mainnet round-count",
        forks_timeline="mainnet",
        forks=["phase0"],
        config="mainnet",
        runner="shuffling",
        handler="core",
        test_cases=shuffling_test_cases()))

if __name__ == "__main__":
    gen_runner.run_generator("shuffling", [mini_shuffling_suite, full_shuffling_suite])


class Vertex:
    def __init__(self, data):
        """param:
        data: string
        """
        self.data = data  # data of vertex
        self.adjList = []  # list of adjacences vertexs
        self.edgeDict = {} # dictionary of adjacences edges; key is target.data
        self.color = "white"  # color of vertex
        self.parent = None  # vertex parent
        self.d = None
        self.f = None

class Edge:
    def __init__(self, data, source, target):
        """params:
        source: vertex
        target: vertex
        data: string
        """
        source.adjList.append(target)
        self.source = source  # vertex origin of edge
        self.target = target  # vertex destiny of edge
        self.data = data  # data of edge
        self.classification = None
        self.count = 0
        source.edgeDict[target.data] = self

class Graph:
    def __init__(self):
        self.vertexSet = []
        self.edgeSet = []

    def insert_vertex(self, vertex):
        self.vertexSet.append(vertex)

    def insert_edge(self, data, source, target):
        self.edgeSet.append(Edge(data, source, target))

    def dfs_visit(self, vertex):
        global time
        time += 1
        vertex.d = time
        vertex.color = 'gray'
        print(vertex.data + ":gray")
        for i in vertex.adjList:
            if i.color == 'white':
                i.parent = vertex
                self.dfs_visit(i)
            else:
                if i.f is None and i.d < vertex.d:
                    vertex.edgeDict[i.data].classification = "Back"
                elif i.f is not None and i.d < vertex.d:
                    vertex.edgeDict[i.data].classification = "Cross"
                elif i.f is not None and i.d > vertex.d:
                    vertex.edgeDict[i.data].classification = "Foward"
                # back: tempo final do target não existe, tempo inicial do target é menor
                # cross: tempo final do target existe, tempo inicial do target é menor
                # foward: tempo final do target existe, tempo inicial do target é maior
        vertex.color = 'black'
        print(vertex.data + ":black")
        time += 1
        vertex.f = time

    def dfs(self):
        global time
        for vertex in self.vertexSet:
            if vertex.color == 'white':
                print(vertex.data+":white")
                self.dfs_visit(vertex)

    def auxiliar_walk(self, initial_vertex, final_vertex, string, walks):
        if initial_vertex.edgeDict:
            for key in initial_vertex.edgeDict:
                original_string = string
                if not (initial_vertex.edgeDict[key].classification == "Back" and initial_vertex.edgeDict[key].count == 1):
                    initial_vertex.edgeDict[key].count += 1
                    string += key
                    if key == final_vertex.data:
                        walks.append(string)
                    self.auxiliar_walk(initial_vertex.edgeDict[key].target, final_vertex, string, walks)
                string = original_string
        return(walks)

    def walks(self, initial_vertex, final_vertex):
        self.dfs()
        for edge in self.edgeSet:
            edge.count = 0
        return(self.auxiliar_walk(initial_vertex, final_vertex, initial_vertex.data, []))

    def print(self):
        for element in self.vertexSet:
            if element.f is not None:
                print(element.data, element.d, element.f)
            else:
                print(element.data)
        for element in self.edgeSet:
            print(element.data, element.source.data, element.target.data, element.classification)

if __name__ == '__main__':
    g = Graph()
    a = Vertex('a')
    g.insert_vertex(a)
    b = Vertex('b')
    g.insert_vertex(b)
    c = Vertex('c')
    g.insert_vertex(c)
    d = Vertex('d')
    g.insert_vertex(d)
    e = Vertex('e')
    g.insert_vertex(e)
    f = Vertex('f')
    g.insert_vertex(f)

    g.insert_edge('ab', a, b)
    g.insert_edge('ac', a, c)
    g.insert_edge('ad', a, d)
    g.insert_edge('ae', a, e)
    g.insert_edge('bc', b, c)
    g.insert_edge('bf', b, f)
    g.insert_edge('cd', c, d)
    g.insert_edge('da', d, a)
    g.insert_edge('de', d, e)

    #g.print()

    time = 0
    g.dfs()
    g.print()

    print("Walks from a to c:")
    print(g.walks(a, c))
    print("Walks from a to d:")
    print(g.walks(a, d))
    print("Walks from a to f:")
    print(g.walks(a, f))
    print("Walks from c to b:")
    print(g.walks(c, b))
    print("Walks from b to c:")
    print(g.walks(b, c))
    print("Walks from f to e:")
    print(g.walks(f, e))


# -*- coding: utf-8 -*-
"""
Created on Fri Sep 30 12:25:49 2016

@author: Lima
"""

from json import load

def load_json(path):
    with open(path,'r') as f:
        data = load(f)
    return data

data = load_json('Data/amsterdam.json')
for i in range(0,3):
    print(data[i]['_id'])


# -*- coding: utf-8 -*-
"""
Created on Sun Apr 21 18:40:59 2019

@author: sudachar
"""

import time

sonnet = [letter.strip() for letter in open('sonnet_words.txt', 'r').readlines()]
sowpod = [letter.strip() for letter in open('sowpods.txt', 'r').readlines()]
#word_dictionary = dict((letter, 1) for letter in sowpod) # the Dictionary way
word_set = set(sowpod)

counter = 0

start_timelog = time.time()

for word in sonnet :
    #if word not in word_dictionary :  # the Dictionary way
    if word not in word_set :
        print(word)

        counter += 1

stop_timelog = time.time()

print('Total new words : %d' %counter)
print('Total time elapsed : %1f seconds' %(stop_timelog - start_timelog))


import os, time, random
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
#### HOW TO USE ################################################################################################
'''
If you aren't using 64 bit linux delete the chromedriver from assets and download the correct drive for your os:
https://chromedriver.storage.googleapis.com/index.html?path=2.30/
Add the driver to the assets folder

Make sure that:
You have PIP installed
You have google chrome installed

For all OSes:
Use pip to install selenium
pip install -U selenium

Modify the settings
'''
################################################################################################################

#is linux or mac
unix = True;

#Who's profile to spam (ie https://victim.sarahah.com/)
victim = "victim"

#A random message will get picked each iteration
messages = [
"Message 1",
"Message 2",
"Message 3"
]

#author tag (leave blank for none)
author = ""

#use https ("s" = https, "" = http)
https = "s"

if unix:
	os.system("clear")

print("Yeasty Sarahah Bot v1")
print("Launching chrome automation...")
chromedriver = "assets/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver)

count = 0
mes = len(messages)
while 1:
	count += 1
	try:
		message = messages[random.randint(0, mes-1)]
		print("Spamming " + victim + " with " + message)
		driver.get("http" + https + "://" + victim + ".sarahah.com/")
		q = driver.find_element_by_id("Text")
		q.send_keys(message + author)
		driver.find_element_by_id("Send").click()
		time.sleep(3)
	except:
		driver.quit()
		os.system("python auto.py")


#!/usr/bin/env python
# $Id$
# -*- coding: utf-8

import time
import tempfile
from functools import reduce
import numpy

from pyscf.lib import logger
from pyscf import ao2mo

'''
spin-adapted MP2
t2[i,j,b,a] = (ia|jb) / D_ij^ab
'''

# the MO integral for MP2 is (ov|ov). The most efficient integral
# transformation is
# (ij|kl) => (ij|ol) => (ol|ij) => (ol|oj) => (ol|ov) => (ov|ov)
#   or    => (ij|ol) => (oj|ol) => (oj|ov) => (ov|ov)

def kernel(mp, mo_energy, mo_coeff, nocc, verbose=None):
    nvir = len(mo_energy) - nocc
    eia = mo_energy[:nocc,None] - mo_energy[None,nocc:]
    t2 = numpy.empty((nocc,nocc,nvir,nvir))
    emp2 = 0

    with mp.ao2mo(mo_coeff, nocc) as ovov:
        for i in range(nocc):
            djba = (eia.reshape(-1,1) + eia[i].reshape(1,-1)).ravel()
            gi = numpy.array(ovov[i*nvir:(i+1)*nvir], copy=False)
            gi = gi.reshape(nvir,nocc,nvir).transpose(1,2,0)
            t2[i] = (gi.ravel()/djba).reshape(nocc,nvir,nvir)
            # 2*ijab-ijba
            theta = gi*2 - gi.transpose(0,2,1)
            emp2 += numpy.einsum('jab,jab', t2[i], theta)

    return emp2, t2

def make_rdm1(mp, mo_energy, mo_coeff, nocc, verbose=None):
    nmo = len(mo_energy)
    nvir = nmo - nocc
    dm1occ = numpy.zeros((nocc,nocc))
    dm1vir = numpy.zeros((nvir,nvir))
    eia = mo_energy[:nocc,None] - mo_energy[None,nocc:]
    emp2 = 0
    with mp.ao2mo(mo_coeff, nocc) as ovov:
        for i in range(nocc):
            djba = (eia.reshape(-1,1) + eia[i].reshape(1,-1)).ravel()
            gi = numpy.array(ovov[i*nvir:(i+1)*nvir]).reshape(nvir,nocc,nvir)
            gi = gi.transpose(1,2,0)
            t2i = (gi.ravel()/djba).reshape(nocc,nvir,nvir)
            # 2*ijab-ijba
            theta = gi*2 - gi.transpose(0,2,1)
            emp2 += numpy.einsum('jab,jab', t2i, theta)

            dm1vir += numpy.einsum('jca,jcb->ab', t2i, t2i) * 2 \
                    - numpy.einsum('jca,jbc->ab', t2i, t2i)
            dm1occ += numpy.einsum('iab,jab->ij', t2i, t2i) * 2 \
                    - numpy.einsum('iab,jba->ij', t2i, t2i)

    rdm1 = numpy.zeros((nmo,nmo))
# *2 for beta electron
    rdm1[:nocc,:nocc] =-dm1occ * 2
    rdm1[nocc:,nocc:] = dm1vir * 2
    rdm1 = reduce(numpy.dot, (mo_coeff, rdm1, mo_coeff.T))
    return rdm1

class MP2(object):
    def __init__(self, mf):
        self.mol = mf.mol
        self._scf = mf
        self.verbose = self.mol.verbose
        self.stdout = self.mol.stdout
        self.max_memory = mf.max_memory

        self.emp2 = None
        self.t2 = None

    def kernel(self, mo_energy=None, mo_coeff=None, nocc=None):
        if mo_coeff is None:
            mo_coeff = self._scf.mo_coeff
        if mo_energy is None:
            mo_energy = self._scf.mo_energy
        if nocc is None:
            nocc = self.mol.nelectron // 2

        self.emp2, self.t2 = \
                kernel(self, mo_energy, mo_coeff, nocc, verbose=self.verbose)
        logger.log(self, 'RMP2 energy = %.15g', self.emp2)
        return self.emp2, self.t2

    # return eri_ovov array[nocc*nvir,nocc*nvir]
    def ao2mo(self, mo_coeff, nocc):
        log = logger.Logger(self.stdout, self.verbose)
        time0 = (time.clock(), time.time())
        log.debug('transform (ia|jb)')
        nmo = mo_coeff.shape[1]
        nvir = nmo - nocc
        co = mo_coeff[:,:nocc]
        cv = mo_coeff[:,nocc:]
        if self._scf._eri is not None and \
           (nocc*nvir*nmo**2/2*8 + (nocc*nvir)**2*8 \
            + self._scf._eri.nbytes)/1e6 < self.max_memory:
            eri = ao2mo.incore.general(self._scf._eri, (co,cv,co,cv))
        else:
            erifile = tempfile.NamedTemporaryFile()
            ao2mo.outcore.general(self.mol, (co,cv,co,cv), erifile.name,
                                  verbose=self.verbose)
            eri = erifile
        time1 = log.timer('Integral transformation', *time0)
        return ao2mo.load(eri)

if __name__ == '__main__':
    from pyscf import scf
    from pyscf import gto
    mol = gto.Mole()
    mol.verbose = 5
    mol.output = 'out_h2o'
    mol.atom = [
        [8 , (0. , 0.     , 0.)],
        [1 , (0. , -0.757 , 0.587)],
        [1 , (0. , 0.757  , 0.587)]]

    mol.basis = {'H': 'cc-pvdz',
                 'O': 'cc-pvdz',}
    mol.build()
    mf = scf.RHF(mol)
    print(mf.scf())

    nocc = mol.nelectron//2
    nmo = mf.mo_energy.size
    nvir = nmo - nocc

    co = mf.mo_coeff[:,:nocc]
    cv = mf.mo_coeff[:,nocc:]
    g = ao2mo.incore.general(mf._eri, (co,cv,co,cv)).ravel()
    eia = mf.mo_energy[:nocc,None] - mf.mo_energy[nocc:]
    t2ref0 = g/(eia.reshape(-1,1)+eia.reshape(-1)).ravel()
    t2ref0 = t2ref0.reshape(nocc,nvir,nocc,nvir).transpose(0,2,3,1)

    pt = MP2(mf)
    emp2, t2 = pt.kernel()
    print(emp2 - -0.204019967288338)
    print('incore', numpy.allclose(t2, t2ref0))
    pt.max_memory = 1
    print('direct', numpy.allclose(pt.kernel()[1], t2ref0))

    t2s = numpy.zeros((nocc*2,nocc*2,nvir*2,nvir*2))
    t2s[ ::2, ::2, ::2, ::2] = t2ref0 - t2ref0.transpose(0,1,3,2)
    t2s[1::2,1::2,1::2,1::2] = t2ref0 - t2ref0.transpose(0,1,3,2)
    t2s[ ::2,1::2,1::2, ::2] = t2ref0
    t2s[1::2, ::2, ::2,1::2] = t2ref0
    t2s[ ::2,1::2, ::2,1::2] = -t2ref0.transpose(0,1,3,2)
    t2s[1::2, ::2,1::2, ::2] = -t2ref0.transpose(0,1,3,2)
    dm1occ =-.5 * numpy.einsum('ikab,jkab->ij', t2s, t2s)
    dm1vir = .5 * numpy.einsum('ijac,ijbc->ab', t2s, t2s)
    dm1ref = numpy.zeros((nmo,nmo))
    dm1ref[:nocc,:nocc] = dm1occ[ ::2, ::2]+dm1occ[1::2,1::2]
    dm1ref[nocc:,nocc:] = dm1vir[ ::2, ::2]+dm1vir[1::2,1::2]
    dm1ref = reduce(numpy.dot, (mf.mo_coeff, dm1ref, mf.mo_coeff.T))
    rdm1 = make_rdm1(pt, mf.mo_energy, mf.mo_coeff, nocc)
    print(numpy.allclose(rdm1, dm1ref))


import numpy as np
import matplotlib.pyplot as plt
from utils import tf

s = tf([1, 0], 1)
"""Set-up plant and Disturbance model"""
G = 200/((10*s + 1)*(0.05*s + 1)*(0.05*s + 1))
G_d = 100/(10*s + 1)

"""The four different controllers in question"""
K0 = ((10*(10*s + 1))*(0.1*s + 1))/(s*200*(0.01*s + 1))
K1 = 0.5
K2 = 0.5*(s + 2)/s
K3 = (0.5*(s + 2)*(0.05*s + 1))/(s*(0.005*s + 1))

w = np.logspace(-2, 2, 100)
s = 1j*w

"""Closed loop tf"""
L0 = G*K0
L1 = G*K1
L2 = G*K2
L3 = G*K3

tspan = np.linspace(0, 3, 100)

"""Step response in the disturbance"""
cont0 = (1/(1+L0))*G_d
cont1 = (1/(1+L1))*G_d
cont2 = (1/(1+L2))*G_d
cont3 = (1/(1+L3))*G_d

[t, y0] = cont0.step(0, tspan)
[t, y1] = cont1.step(0, tspan)
[t, y2] = cont2.step(0, tspan)
[t, y3] = cont3.step(0, tspan)

"""Plot results"""
plt.subplot(1, 2, 1)
plt.loglog(w, np.abs(L0(s)))
plt.loglog(w, np.abs(L1(s)))
plt.loglog(w, np.abs(L2(s)))
plt.loglog(w, np.abs(L3(s)))

plt.subplot(1, 2, 2)
plt.plot(t, y0)
plt.plot(t, y1)
plt.plot(t, y2)
plt.plot(t, y3)
plt.show()


import os
import re
import cv2
import json
import platform

from subprocess import Popen, PIPE, STDOUT
from barez import *

def _get_command_path(command):
    if platform.system() == 'Windows':
        command = command + '.exe'
    return command

def _pdf_info(pdf_path):
    command = [_get_command_path("pdfinfo"), pdf_path]
    proc = Popen(command, stdout=PIPE, stderr=PIPE)
    out, err = proc.communicate()

    page_count = int(re.search(r'Pages:\s+(\d+)',
                      out.decode("utf8", "ignore")).group(1))

    pdf_info = []
    for i in range(page_count):
        cmd = [_get_command_path("pdfinfo"), '-f',
               str(i + 1), '-l', str(i + 1), pdf_path]
        proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
        out, err = proc.communicate()
        # Page size: 792 x 1224 pts
        page_size = int(re.search('Page.*size:\s+(\d+)',
                        out.decode("utf8", "ignore")).group(1))
        pdf_info.append((str(i+1),  page_size))
    return pdf_info

def textline2ocr(file_path='./input/GED00264650_03_001_PROJECT DOCUMENTS_S5_30 PDFA.pdf',
                 path_out='debug', thread_num=12):
    """
    file_path: path of pdf file
    path_out: path out of image(s)
    thread_num: number of thread
    output is jpeg file
    """
    assert 'pdf' in file_path
    base_name = file_path.split('/')[-1][:-4]
    page_info = _pdf_info(file_path)

    large_page = [(pnum, psize) for (pnum, psize) in page_info if psize > 3000]
    small_page = [(pnum, psize) for (pnum, psize) in page_info if psize <= 3000]

    processes = []
    proc_cnt = 0

    for page_num, page_size in small_page + large_page:
        if (page_num, page_size) in large_page:
            dpi = 150
        else:
            dpi = 300

        img = cv2.imread('./input/GED00264650_03_001_PROJECT DOCUMENTS_S5_30 PDFA/images/{}.jpg'.format(int(page_num) - 1))

        command = ['pdftotext', '-r', str(dpi), '-f', page_num,
                   '-l', page_num, '-bbox-layout', file_path]
        p = Popen(command, stdout=PIPE)
        stdout, _ = p.communicate()

        # open html file
        html_file_path = file_path[:-3] + 'html'
        html_file = open(html_file_path, 'r')

        # <line xMin="3835.000000" yMin="2381.166667" xMax="5008.999500" yMax="2418.704167">
        html_data = ''.join(html_file.readlines())

        line_pattern = re.compile(r"<line xMin=\"([\d.]+)\" yMin=\"([\d.]+)\" xMax=\"([\d.]+)\" yMax=\"([\d.]+)\">")
        bbox = line_pattern.findall(html_data)

        json_out = {
            "imageData": None,
            "imagePath": "{}.jpg".format(int(page_num) - 1),
            "lineColor": [0, 255, 0, 128],
            "fillColor": [254, 0, 0, 128],
            "shapes": [],
            "flags": {}}

        # get the list of text line
        for xMin, yMin,xMax, yMax in bbox:
            top = int(float(xMin)) - 2
            left = int(float(yMin)) - 2
            width = int(float(xMax)) - top  + 4
            height = int(float(yMax)) - left + 4

            command = ['pdftotext', '-r', str(dpi), '-f', page_num,
                       '-l', page_num, '-x', str(top), "-y",
                       str(left), "-W", str(width), "-H",
                       str(height), file_path, "-"]
            p = Popen(command, stdout=PIPE)
            stdout, _ = p.communicate()

            ocr_value = stdout.decode('utf-8')

            json_out["shapes"].append({
                "label": ocr_value,
                "points": [
                    [top, left],
                    [top + width, left],
                    [top + width, left + height],
                    [top, left + height]
                ],
                "line_color": None,
                "fill_color": None
            })

            cv2.putText(img,
                        ocr_value,
                        (top - 5, left - 5),
                        cv2.FONT_HERSHEY_SIMPLEX,
                        0.5, (0,0,255), 2)
        cv2.imwrite("./visualize/{}.jpg".format(int(page_num) - 1), img)

        json.dump(json_out, open("./debug/{}.json".format(int(page_num) - 1), 'w'))

if __name__ == "__main__":
    textline2ocr()


from itertools import combinations
import time

def factors(n):
    for x in xrange(2,n):
        if n%x == 0:
            return (x,) + factors(n/x)
    return (n,)

start = time.time()

i = 2
triang = 3
cond = True

while cond:
    div = 2 # 1 and triang counted
    fac = list(factors(triang))
    # print(triang)
    # print(fac)
    for j in xrange(len(fac)):
        b = set(combinations(fac,j+1))
        # c = list(combinations(fac, j+1))
        div += len(b)
    if div >= 500:
        print(triang)
        cond = False
    else:
        i = i+1
        triang += i

end = time.time()
print(end-start)

"""
second method: shiiiit
"""

# y = 1
# div1 = 1
# div2 = 1

# def factors2(n):
#     global y, div1, div2
#     for x in range(2,n):
#         if n%x == 0:
#             if y != x:
#                 print(x)
#                 y = x
#                 div2 = div1
#                 div1 = 1
#                 print("div2 " + str(div2))
#             else:
#                 div1 += 1
#             return (x,) + factors2(n/x)
#     # print(n)
#     return (n,)

# a = factors2(600)
# print(a)

# div = dict()

# def factors3(n):
#     global div
#     for x in range(2,n):
#         if n%x == 0:
#             try:
#                 div[x] += 1
#             except:
#                 div[x] = 1
#             return (x,) + factors3(n/x)
#     try:
#         div[n] += 1
#     except:
#         div[n] = 1
#     return (n,)

# a = factors3(144)


from collections import namedtuple

# the order of the keys of this dictionary
FunctionalGroup = namedtuple("FunctionalGroup", ["resName", "donor", "acceptor", "atoms"])
FunctionalGroup.__doc__ = """Store hydrogen bonding information about a
functional group as well as information that can be used to position it
in three-space.

Attributes
----------
resName : str
    Name of the functional group.
donor : bool
    True if the functional group can be a donor in a hydrogen bond.
acceptor : bool
    True if the functional group can be an acceptor in a hydrogen bond.
atoms : list of str
    List of three atom names that are used to construct a coordinate
    frame to describe the position of the functional group in three-space.
"""

functional_groups = {
    "OH_": FunctionalGroup("hydroxide", True, True, ["CV", "OH", "HH"]),
    "G__": FunctionalGroup("guanidinium", True, False, ["CZ", "NH1", "NH2"]),
    "I__": FunctionalGroup("imidazole", True, True, ["ND1", "CD2", "NE2"]),
    # imidazole tautomer
    "ID_": FunctionalGroup("imidazole_D", True, True, ["ND1", "CD2", "NE2"]),
    "A__": FunctionalGroup("amine", True, False, ["NZ", "1HZ", "2HZ"]),
    "C__": FunctionalGroup("carboxylate", False, True, ["CD", "OE1", "OE2"]),
    "CA_": FunctionalGroup("carboxamide", True, True, ["CG", "OD1", "ND2"])
}

ResInfo = namedtuple("ResInfo", ["grp", "atoms"])
ResInfo.__doc__ = """Store functional group information about an amino
acid as well as information that can be used to position it in
three-space.

Attributes
----------
grp : str
    Name of a functional group.
atoms : list of str
    List of three atom names that are used to construct a coordinate
    frame to describe the position of the functional group of the amino
    acid in three-space.
"""

def resolve_rays(groups):
    """Expand list of interaction groups into the appropriate ray
    selection methods.

    Parameters
    ----------
    groups : list of str
        Interaction groups to search in.

    Returns
    -------
    list of tuple of str, function
        Names of groups and the corresponding ray selectors for the
        groups.
    """

    from . import (
        bidentate, network, catpi
    )
    ray_bins = {
        "bidentate": [
            ("sc_sc", bidentate.sc_sc_rays),
            ("sc_scbb", bidentate.sc_scbb_rays),
            ("sc_bb", bidentate.sc_bb_rays)
        ],
        "network": [
            ("acceptor_acceptor", network.acceptor_acceptor_rays),
            ("acceptor_donor", network.donor_acceptor_rays),
            ("donor_acceptor", network.donor_acceptor_rays),
            ("donor_donor", network.donor_donor_rays)
        ],
        "cation-pi": [("cation-pi", catpi.rays)]
    }

    ray_selectors = [ ]

    for group in groups:
        for k in ray_bins:
            for v in ray_bins[k]:
                if (group == "all" or group in [k, v[0]]):
                    ray_selectors.append(v)

    return ray_selectors


from sklearn.base import BaseEstimator
import numpy as np

__all__ = [
    '_StagedClassifier',
    '_StagedRegressor',
    '_cat_staged_predict',
    '_xgb_staged_predict',
    '_lgb_staged_predict',
    '_get_scores',
]

class _StagedClassifier(BaseEstimator):

    _estimator_type = 'classifier'

    def predict_proba(self, X):
        return X

    def predict(self, X):
        y = X[:, 1] > 0.5
        y = y.astype(int)
        return y

class _StagedRegressor(BaseEstimator):

    _estimator_type = 'regressor'

    def predict(self, X):
        return X

def _xgb_staged_predict(estimator, X, max_iter=0, step=1):

    booster = estimator.get_booster()

    leafs = estimator.apply(X, max_iter)
    M = leafs.shape[0]
    N = leafs.shape[1]

    trees = np.mgrid[0:M, 0:N][1]
    return None

def _lgb_staged_predict(estimator, X, max_iter=0, step=1):

    booster = estimator.booster_

    max_iter = max_iter if max_iter else booster.num_trees()

    leafs = booster.predict(X, pred_leaf=True, num_iteration=max_iter)
    M = leafs.shape[0]
    N = leafs.shape[1]

    trees = np.mgrid[0:M, 0:N][1]

    mapper = {}
    for i in range(estimator.n_estimators):
        for j in range(estimator.num_leaves):
            mapper[i, j] = booster.get_leaf_output(i, j)

    preds = np.vectorize(lambda i, j: mapper[i, j])(trees, leafs).T
    preds = preds.cumsum(axis=0)[np.arange(step, max_iter+step, step)-1]

    if estimator._estimator_type == 'classifier':
        preds = sigmoid(preds)

        for pred in preds:
            yield np.vstack([1-pred, pred]).T

    elif estimator._estimator_type == 'regressor':
        for pred in preds:
            yield pred

def _cat_staged_predict(estimator, X, max_iter=0, step=1):

    if estimator._estimator_type == 'classifier':
        return estimator.staged_predict_proba(X, ntree_end=max_iter, eval_period=step)

    elif estimator._estimator_type == 'regressor':
        return estimator.staged_predict(X, ntree_end=max_iter, eval_period=step)

def _get_scores(estimator, generator, predictor, trn, val, X, y,
                scorer, max_iter, step, train_score):

    stages = np.arange(step, max_iter+step, step)

    trn_scores = []
    val_scores = []

    if train_score:
        X_trn, y_trn = X.iloc[trn], y.iloc[trn]
        S_trn = generator(estimator, X_trn, max_iter, step)

        for _ in stages:
            trn_scores.append(scorer(predictor, next(S_trn), y_trn))

    if True:
        X_val, y_val = X.iloc[val], y.iloc[val]
        S_val = generator(estimator, X_val, max_iter, step)

        for _ in stages:
            val_scores.append(scorer(predictor, next(S_val), y_val))

    return trn_scores, val_scores

def sigmoid(x):
    return 1 / (1 + np.exp(-x))


import simpy
import numpy
import progressbar

from constants import (MONSTERS_NUMBER,
                       TIMEZONES_NUMBER,
                       VISITING_HOURS,
                       TIMID_CHILDREN,
                       TIMEZONES_POPULATION,
                       TIME_DELAY,
                       HOUR,
                       STUCK_TIME,
                       DURATION_OF_FRIGHT)

bar = progressbar.ProgressBar(widgets=[
    progressbar.Timer(),
    progressbar.AnimatedMarker(markers='<3 '),
    progressbar.AnimatedMarker(markers='3 <'),
    progressbar.AnimatedMarker(markers=' <3'),
    progressbar.AnimatedMarker(markers='<3 '),
    progressbar.AnimatedMarker(markers='3 <'),
    progressbar.AnimatedMarker(markers=' <3'),
    progressbar.AnimatedMarker(markers='<3 '),
    progressbar.AnimatedMarker(markers='3 <'),
    progressbar.AnimatedMarker(markers=' <3'),

    progressbar.Bar()
])

class Runner:
    def __init__(self):
        self.total_timezones_population = 0
        self.queue_length = 0
        self.monsters_stuck = 0
        self.doors_stuck = 0
        self.processed_doors = 0
        self.env = simpy.Environment()
        self.scenario_num = 0
        self.experiment_num = 0

    def execute(self, scenario_num, experiment_num):
        self.scenario_one = simpy.Resource(self.env, capacity=MONSTERS_NUMBER[scenario_num][experiment_num])    #smo

        for i in range(TIMEZONES_NUMBER[scenario_num]):
            self.total_timezones_population += TIMEZONES_POPULATION[i+TIME_DELAY]

        self.env.process(self.source_doors(self.env))
        self.env.run(until=HOUR*VISITING_HOURS[scenario_num])
        # print("\nNot processed doors {}. Monsters stuck {}. Processed doors {}"
        #       .format(self.queue_length + self.doors_stuck, self.monsters_stuck, self.processed_doors))
        #
        # print("Monster productivity {} %/per monster"
        #       .format((self.processed_doors*100)/(self.total_timezones_population*MONSTERS_NUMBER[scenario_num][experiment_num])))
        print("\n")
        return (self.queue_length + self.doors_stuck,
                self.monsters_stuck,
                self.processed_doors,
                self.processed_doors*100 / (self.total_timezones_population * MONSTERS_NUMBER[scenario_num][experiment_num])
                )

    def source_doors(self, env):
        while env.now < (HOUR * VISITING_HOURS[self.scenario_num]):
            doors_number = TIMEZONES_POPULATION[int(env.now / HOUR) + TIME_DELAY]

            for _ in range(doors_number):
                env.process(self.run())
            yield env.timeout(HOUR)

    def run(self):
        self.queue_length += 1
        with self.scenario_one.request() as request:  # SMO 1
            yield request
            self.queue_length -= 1

            if (self.processed_doors % round((self.total_timezones_population/100), 0)) == 0:
                bar.update(round(self.processed_doors / self.total_timezones_population * 100), 0)

            brave = (numpy.random.randint(0, high=100) > TIMID_CHILDREN[self.scenario_num][self.experiment_num])

            if not brave:
                service_time = numpy.random.uniform(DURATION_OF_FRIGHT[0], DURATION_OF_FRIGHT[1])
                self.processed_doors += 1
                yield self.env.timeout(service_time)
            else:
                service_time = STUCK_TIME
                if self.monsters_stuck < MONSTERS_NUMBER[self.scenario_num][self.experiment_num]:
                    self.doors_stuck += 1
                    self.monsters_stuck += 1
                    yield self.env.timeout(service_time)
                else:
                    self.doors_stuck += 1


"""
Keras models
By: Xiaochi (George) Li
Dec.2018

Unfortunately, non of them can work.
Last Error:FailedPreconditionError: Attempting to use uninitialized value training/TFOptimizer/beta1_power
"""
import tensorflow as tf
from keras import layers
from keras import optimizers
from keras.applications import inception_v3
from keras.applications import mobilenet
from keras.models import Model
from keras import backend as K
from keras import metrics

def first_model():
    """
    This model just makes sure that the code can work
    :return:
        model: keras model object
    """
    model = tf.keras.Sequential([
        layers.Conv2D(64, kernel_size=3, activation='relu', input_shape=(100,100,3)),
        layers.Conv2D(32, kernel_size=3, activation='relu'),
        layers.Flatten(),
        layers.Dense(7, activation='softmax')
    ])

    model.compile(optimizer=tf.train.AdadeltaOptimizer(0.001),
                  loss='categorical_crossentropy',
                 metrics=[tf.keras.metrics.categorical_accuracy])

    return model

def ft_inception_v3():
    """
    Use pretrained VGG16 as bottom

    :return:
    """
    base_model = inception_v3.InceptionV3(include_top=False, weights='imagenet', input_shape=(299, 299, 3))
    base_out = base_model.output
    x = layers.Flatten()(base_out)
    # 'Concatenate' object has no attribute 'outbound_nodes'
    x = layers.Dense(4096, activation='relu')(x)  # Can't connect
    x = layers.Dense(1024, activation='relu')(x)
    x = layers.Dense(256, activation='relu')(x)
    x = layers.Dense(64, activation='relu')(x)
    x = layers.Dense(16, activation='relu')(x)
    predictions = layers.Dense(7, activation='softmax')(x)

    model = Model(inputs=base_model.input, outputs=predictions)
    for layer in base_model.layers():
        layer.trainable = False

    model.compile(optimizer=tf.train.AdadeltaOptimizer(0.001),
                  loss='categorical_crossentropy',
                  metrics=[metrics.categorical_accuracy])

    return model

def ft_mobile_net():
    """
    Use pretrained mobile net as bottom

    :return:
    """
    # input = layers.Input((224,224,3), name='RGB')
    base_model = mobilenet.MobileNet(include_top=False, weights='imagenet', input_shape=(224, 224,3))
    base_out = base_model.output
    x = layers.Flatten()(base_out)
    x = layers.Dense(1024, activation='relu', kernel_initializer='random_uniform', bias_initializer='zeros', name='Dense1024')(x)
    x = layers.Dense(256, activation='relu',kernel_initializer='random_uniform', bias_initializer='zeros', name='Dense256')(x)
    x = layers.Dense(64, activation='relu',kernel_initializer='random_uniform', bias_initializer='zeros', name='Dense64')(x)
    x = layers.Dense(16, activation='relu',kernel_initializer='random_uniform', bias_initializer='zeros', name='Dense16')(x)
    predictions = layers.Dense(7, activation='softmax',kernel_initializer='random_uniform', bias_initializer='zeros')(x)

    model = Model(inputs=base_model.input, outputs=predictions)
    for layer in base_model.layers:
        layer.trainable = False
    sgd = optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
    with tf.Session() as sess:
        adam = tf.train.AdamOptimizer()
        print(adam.variables())
        sess.run(tf.variables_initializer(adam.variables()))
        model.compile(optimizer=adam,
                  loss='categorical_crossentropy',
                  metrics=[metrics.categorical_accuracy])
        # model.compile(optimizer=sgd,
        #               loss='categorical_crossentropy',
        #               metrics=[tf.keras.metrics.categorical_accuracy])
        K.set_session(tf.Session(graph=model.output.graph))
        init = K.tf.global_variables_initializer()
        K.get_session().run(init)

    # tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value training/TFOptimizer/beta1_power
        return model