# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:

        return self.find_sum(root, targetSum, 0)

    def find_sum(self, root, target, count):

        if root == None:
            return False

        ans = False

        count += root.val
        ans |= self.find_sum(root.left, target, count)
        ans |= self.find_sum(root.right, target, count)

        if root.left == None and root.right == None:
            if count == target:
                return True

        return ans


from __future__ import print_function

from collections import Mapping, namedtuple
import copy
import itertools
import os
import shlex
import stat
import subprocess
import tempfile

from cached_property import cached_property

from .base import Enumerator, Leaf, SEQUENCES, ConstraintTag, write_yaml_report

import six

from hpcbench import jinja_environment
from hpcbench.toolbox.contextlib_ext import pushd
from hpcbench.toolbox.process import (
    build_slurm_arguments,
    find_executable,
    parse_constraint_in_args,
)

Command = namedtuple('Command', ['execution', 'srun'])
Command.__new__.__defaults__ = (None,) * len(Command._fields)

class ExecutionDriver(Leaf):
    """Abstract representation of a benchmark command execution
    (a benchmark is made of several commands)
    """

    name = 'local'

    def __init__(self, parent):
        super(ExecutionDriver, self).__init__(parent)
        self.benchmark = self.parent.benchmark
        self.execution = parent.execution
        self.command_expansion_vars = dict(process_count=1)
        self.config = parent.config
        self.exec_context = parent.exec_context

    @classmethod
    def commands(cls, campaign, config, execution):
        """
        :param campaign: global configuration
        :param config: benchmark YAML configuration
        :param execution: one benchmark to execute,
        provided by `Benchmark.execution_matrix`
        """
        yield Command(execution=execution, srun=None)

    @cached_property
    def _executor_script(self):
        """Create shell-script in charge of executing the benchmark
        and return its path.
        """
        fd, path = tempfile.mkstemp(suffix='.sh', dir=os.getcwd())
        os.close(fd)
        with open(path, 'w') as ostr:
            self._write_executor_script(ostr)
        mode = os.stat(path).st_mode
        os.chmod(path, mode | stat.S_IEXEC | stat.S_IRGRP | stat.S_IRUSR)
        return path

    @property
    def _jinja_executor_template(self):
        """:return Jinja template of the shell-script executor"""
        template = self.campaign.process.executor_template
        if template.startswith('#!'):
            return jinja_environment.from_string(template)
        else:
            return jinja_environment.get_template(template)

    def _write_executor_script(self, ostr):
        """Write shell script in charge of executing the command"""
        environment = self.execution.get('environment') or {}
        if not isinstance(environment, Mapping):
            msg = 'Expected mapping for environment but got '
            msg += str(type(environment))
            raise Exception(msg)
        escaped_environment = dict(
            (var, six.moves.shlex_quote(str(value)))
            for var, value in environment.items()
        )
        modules = self.execution.get('modules') or []
        properties = dict(
            command=self.command,
            cwd=os.getcwd(),
            modules=modules,
            environment=escaped_environment,
        )
        self._jinja_executor_template.stream(**properties).dump(ostr)

    @cached_property
    def command(self):
        """:return command to execute inside the generated shell-script"""
        exec_prefix = self.parent.parent.parent.config.get('exec_prefix', [])
        command = self.execution['command']
        if isinstance(command, SEQUENCES):
            command = [arg.format(**self.command_expansion_vars) for arg in command]
        else:
            command = command.format(**self.command_expansion_vars)
        if self.execution.get('shell', False):
            if not isinstance(exec_prefix, six.string_types):
                exec_prefix = ' '.join(exec_prefix)
            if not isinstance(command, six.string_types):
                msg = "Expected string for shell command, not {type}: {value}"
                msg = msg.format(type=type(command).__name__, value=repr(command))
                raise Exception(msg)
            eax = [exec_prefix + command]
        else:
            if not isinstance(exec_prefix, SEQUENCES):
                exec_prefix = shlex.split(exec_prefix)
            if not isinstance(command, SEQUENCES):
                eax = exec_prefix + shlex.split(command)
            else:
                eax = exec_prefix + command
            eax = [six.moves.shlex_quote(arg) for arg in eax]
        return eax

    @cached_property
    def command_str(self):
        """get command to execute as string properly escaped

        :return: string
        """
        if isinstance(self.command, six.string_types):
            return self.command
        return ' '.join(map(six.moves.shlex_quote, self.command))

    def popen(self, stdout, stderr):
        """Build popen object to run

        :rtype: subprocess.Popen
        """
        self.logger.info('Executing command: %s', self.command_str)
        return subprocess.Popen([self._executor_script], stdout=stdout, stderr=stderr)

    def __execute(self, stdout, stderr):
        with self.module_env(), self.spack_env():
            self.benchmark.pre_execute(self.execution, self.exec_context)
        exit_status = self.popen(stdout, stderr).wait()
        with self.module_env(), self.spack_env():
            self.benchmark.post_execute(self.execution, self.exec_context)
        return exit_status

    def module_env(self):
        category_driver = self.parent.parent
        return category_driver._module_env(self.execution)

    def spack_env(self):
        category_driver = self.parent.parent
        return category_driver._spack_env(self.execution)

    @write_yaml_report
    @Enumerator.call_decorator
    def __call__(self, **kwargs):
        with open('stdout', 'w') as stdout, open('stderr', 'w') as stderr:
            cwd = self.execution.get('cwd')
            if cwd is not None:
                ctx = self.parent.parent.parent.exec_context
                cwd = cwd.format(node=ctx.node, tag=ctx.tag)
                with pushd(cwd):
                    exit_status = self.__execute(stdout, stderr)
            else:
                exit_status = self.__execute(stdout, stderr)
        report = dict(
            exit_status=exit_status,
            benchmark=self.benchmark.name,
            executor=type(self).name,
        )

        expected_es = self.execution.get('expected_exit_statuses', {0})
        report['command_succeeded'] = exit_status in expected_es
        if not report['command_succeeded']:
            self.logger.error('Command failed with exit status: %s', exit_status)
        report.update(self.execution)

        report.update(command=self.command)
        return report

class SrunExecutionDriver(ExecutionDriver):
    """Manage process execution with srun (SLURM)
    """

    name = 'srun'

    @classmethod
    def commands(cls, campaign, config, execution):
        top = super(SrunExecutionDriver, cls)
        for top_cmd in top.commands(campaign, config, execution):
            top_cmd = top_cmd._asdict()
            for srun in cls.srun_cartesian_product(campaign, config):
                top_cmd.update(srun=srun)
                yield Command(**top_cmd)

    @classmethod
    def srun_cartesian_product(cls, campaign, config):
        """
        :param campaign: global YAML configuration
        :param config: benchmark YAML configuration
        """
        options = copy.copy(cls.common_srun_options(campaign))
        options.update(config.get('srun') or {})
        options_tuple = []
        for k, v in options.items():
            if not isinstance(v, SEQUENCES):
                v = [v]
            options_tuple.append([(k, e) for e in v])
        return [dict(combination) for combination in itertools.product(*options_tuple)]

    @cached_property
    def srun(self):
        """Get path to srun executable

        :rtype: string
        """
        commands = self.campaign.process.get('commands', {})
        srun = find_executable(commands.get('srun', 'srun'))
        if six.PY2:
            srun = srun.encode('utf-8')
        return srun

    @classmethod
    def common_srun_options(cls, campaign):
        """Get options to be given to all srun commands

        :rtype: list of string
        """
        default = dict(campaign.process.get('srun') or {})
        default.update(output='slurm-%N-%t.stdout', error='slurm-%N-%t.error')
        return default

    @cached_property
    def tag(self):
        return self.parent.parent.parent.parent.name

    @cached_property
    def command(self):
        """get command to execute

        :return: list of string
        """
        srun_optlist = build_slurm_arguments(self.parent.command.srun or {})
        if not isinstance(self.root.network.nodes(self.tag), ConstraintTag):
            pargs = parse_constraint_in_args(srun_optlist)
            self.command_expansion_vars['process_count'] = pargs.ntasks
            if not pargs.constraint:
                # Expand nodelist if --constraint option is not specified
                # in srun options
                srun_optlist += [
                    '--nodelist=' + ','.join(self.srun_nodes),
                    '--nodes=' + str(len(self.srun_nodes)),
                ]
        command = super(SrunExecutionDriver, self).command
        return [self.srun] + srun_optlist + command

    @cached_property
    def srun_nodes(self):
        """Get list of nodes where to execute the command
        """
        count = self.execution.get('srun_nodes', 0)
        if isinstance(count, six.string_types):
            tag = count
            count = 0
        elif isinstance(count, SEQUENCES):
            return count
        else:
            assert isinstance(count, int)
            tag = self.tag
        nodes = self._srun_nodes(tag, count)
        if 'srun_nodes' in self.execution:
            self.execution['srun_nodes'] = nodes
            self.execution['srun_nodes_count'] = len(nodes)
        return nodes

    def _srun_nodes(self, tag, count):
        assert count >= 0
        if tag != '*' and not self.root.network.has_tag(tag):
            raise ValueError('Unknown tag: {}'.format(tag))
        nodes = sorted(list(self.root.network.nodes(tag)))
        if count > 0:
            return self._filter_srun_nodes(nodes, count)
        return nodes

    def _filter_srun_nodes(self, nodes, count):
        assert count <= len(nodes)
        pos = nodes.index(self.node)
        nodes = nodes * 2
        return nodes[pos : pos + count]


import itertools

class Solution:
    def letterCombinations(self, digits: str):
        #Approach 1: Product of characters - Time Complexity - O(4^N) and Space Complexity - O(N)
        valMap = {'2':'abc', '3':'def', '4':'ghi', '5':'jkl', '6':'mno', '7':'pqrs', '8':'tuv', '9':'wxyz'}

        charMap = [valMap[digit] for digit in digits] #mapping the digit characters

        charComb = itertools.product(*charMap) #take product of each chars

        res = []

        for i in charComb:
            if not i:
                continue
            tempStr = ''.join(i)
            res.append(tempStr)

        return res

        #Approach 2: One Liner - Time Complexity - O(4^N) and Space Complexity - O(N)
        '''
        return list(map(''.join, product(*({'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}[dig] for dig in digits)))) if digits else []
        '''

if __name__ == '__main__':
    s = Solution()
    print(s.letterCombinations('23'))


from project.computer_types.computer import Computer
import math

class DesktopComputer(Computer):
    ALLOWED_PROCESSORS = {
        "AMD Ryzen 7 5700G": 500,
        "Intel Core i5-12600K": 600,
        "Apple M1 Max": 1800
    }
    MAX_RAM = 128

    def __init__(self, manufacturer: str, model: str):
        super().__init__(manufacturer, model)

    def configure_computer(self, processor: str, ram: int):
        if processor not in self.ALLOWED_PROCESSORS:
            raise ValueError(f"{processor} is not compatible with desktop computer {self.manufacturer} {self.model}!")

        if not self.ram_is_valid(ram):
            raise ValueError(f"{ram}GB RAM is not compatible with desktop computer {self.manufacturer} {self.model}!")

        self.processor = processor
        self.ram = ram
        self.price = self.ALLOWED_PROCESSORS[processor] + self.ram_price(ram)

        return f"Created {self.manufacturer} {self.model} with {self.processor} and {self.ram}GB RAM for {self.price}$."

    @staticmethod
    def ram_is_valid(ram):
        if 0 < ram <= DesktopComputer.MAX_RAM:
            while ram != 1:
                if ram % 2 != 0:
                    return False
                ram = ram // 2
            return True
        return False

    @staticmethod
    def ram_price(ram):
        return int(math.log2(ram) * 100)


#coding:utf8
''''''
'''
对于常驻内存的小整数池，深浅拷贝实际上都相当于是浅拷贝 都引用同一份变量

对于一些容器变量：

浅拷贝： objc=copy.copy(obj)  把obj的当前层次所有引用拷贝给objc

深拷贝： objc = copy.deepcopy(obj) 把obj的所有变量引用追到源头 开辟新的内存 把值存过来
        形成为安全新的另一份数据

'''
import copy

a = 1
b = copy.copy(a)
c = copy.deepcopy(a)
print(a is b)   #True
print( a is c)  #True

print("-"*50)

list = [1,2,["a","b"]]

list1 = list
list2 = copy.copy(list)
list3 = copy.deepcopy(list)

list1.append(4)
list[2].append("c")

print(list)
print(list1)    #list1 是list相同引用 两个完全相同
print(list2)    #浅拷贝拷贝当前第一层的所有引用，拷贝了1 2 和内列表的引用，添加元素的时候它获取不到
                #   内列表的引用添加进来了，所以内列表的更改是能看见的
print(list3)    #深拷贝 不会任何更改 完全全新的

'''
特殊情况： 如果拷贝对象是 元组 等不可变类型，那么深拷贝和浅拷贝的结果都只返回了相同的引用
'''
a = (1,2,3)
b  = copy.deepcopy(a)
c = copy.copy(a)
print( b is c )

01 高级语法、系统、网络、正则/01 Python高级/03模块、作用域、==is、拷贝、面向对象/复习/04 深拷贝 浅拷贝.py

04 深拷贝 浅拷贝.py


#! /usr/bin/python
import csv
from google.protobuf.descriptor import FieldDescriptor
from pathlib import Path
import json
import os
lang = os.getenv('MAJSOUL_LANG', 'jp')

def main(original_assets_path, translation_path, dist_path, temp_path):
    target_csvs = []

    with open(Path(translation_path) / 'translate_sheet.csv', 'r', encoding='utf-8-sig') as csvfile:
        csv_reader = csv.reader(csvfile)
        is_header = True
        for row in csv_reader:
            if is_header:
                is_header = False
                continue
            if row[0] not in target_csvs:
                target_csvs.append(row[0])

    import_config_path = Path(temp_path) / 'proto' / 'config_pb2.py'
    with open(import_config_path, 'r', encoding='utf-8') as config_pb2_file:
        config_pb2_code = config_pb2_file.read()
        exec(config_pb2_code, globals())

    import_sheets_path = Path(temp_path) / 'proto' / 'sheets_pb2.py'
    with open(import_sheets_path, 'r', encoding='utf-8') as sheets_pb2_file:
        sheets_pb2_code = sheets_pb2_file.read()
        exec(sheets_pb2_code, globals())

    config_table = ConfigTables()
    with open(Path(original_assets_path) / 'res' / 'config' / 'lqc.lqbin', "rb") as lqc:
        config_table.ParseFromString(lqc.read())

    for data_index in range(len(config_table.datas)):
        data = config_table.datas[data_index]
        class_words = f"{data.table}_{data.sheet}".split("_")
        class_name = "".join(name.capitalize() for name in class_words)

        csv_path = Path(temp_path) / 'csv' / f'{class_name}.csv'

        if not csv_path.is_file():
            print(f'[!] This csv is not exist: {csv_path}')
            continue

        if csv_path.name not in target_csvs:
            print(f'[.] Skip {csv_path}')
            continue

        print(f'[+] Building {csv_path}')

        csv_path = str(csv_path) # for matching csv format

        with open(csv_path, 'r', encoding='utf-8-sig') as csvfile:
            csv_reader = csv.reader(csvfile)
            del data.data[:]
            header = []
            is_header = True
            for row in csv_reader:
                if is_header:
                    header = row
                    is_header = False
                    continue
                field = globals()[class_name]()
                for i, col in enumerate(header):
                    value = row[i]
                    fd = field.DESCRIPTOR.fields_by_name[col]
                    if fd.label == FieldDescriptor.LABEL_REPEATED:
                        getattr(field, col).extend(json.loads(value))
                    else:
                        field_type = fd.type
                        if field_type in [
                            FieldDescriptor.TYPE_INT32,
                            FieldDescriptor.TYPE_INT64,
                            FieldDescriptor.TYPE_SINT32,
                            FieldDescriptor.TYPE_SINT64,
                            FieldDescriptor.TYPE_UINT32,
                            FieldDescriptor.TYPE_UINT64,
                            ]:
                            value = int(value)
                        elif field_type in [
                            FieldDescriptor.TYPE_DOUBLE,
                            FieldDescriptor.TYPE_FIXED32,
                            FieldDescriptor.TYPE_FIXED64,
                            FieldDescriptor.TYPE_FLOAT,
                            ]:
                            value = float(value)
                        setattr(field, col, value)
                data.data.append(field.SerializeToString())

    target_path = Path(dist_path) / 'assets' / 'res' / 'config' / 'lqc.lqbin'
    target_path.parent.mkdir(parents=True, exist_ok=True)
    with open(target_path, "wb") as lqc:
        lqc.write(config_table.SerializeToString())

if __name__ == '__main__':
    main(
        str(Path('./dev-resources/assets-latest')),
        str(Path('./translation')),
        str(Path('./dist/korean')),
        str(Path('./temp'))
    )


from django.urls import path, include

from applications.appointments.views import patient
from applications.appointments.views import timetable
from applications.users.decorators import patient_required, login_required

app_name = 'appointments'
urlpatterns = [
    path('select/', patient.SelectOffice.as_view(), name='select'),
    path('old/', patient.OldAppointmentListView.as_view(), name='old'),
    path('upcoming/', patient.AppointmentListView.as_view(), name='upcoming'),
    path('<int:pk>/', include([
        path('timetable/', login_required(patient_required(timetable.TimetableView.as_view())), name='timetable'),
        path('change/', patient.AppointmentUpdateView.as_view(), name='update'),
        path('cancel/', patient.AppointmentCancelView.as_view(), name='delete'),
        path('<str:date>/<str:service>/make/', patient.MakeAppointment.as_view(), name='make')
    ]))
]


import math

def leap_year(year):
    if year % 4 != 0:
        return False
    elif year % 100 != 0:
        return True
    elif year % 400 != 0:
        return False
    else:
        return True

def day_of_week_jan1(year):
    x = 1 + 5 * ((year - 1) % 4) + 4 * ((year - 1) % 100) + 6 * ((year - 1) % 400)
    return x % 7

def num_days_in_month(month_num, leap_year):
    # return 29 if (leap_year and month_num == 2) else [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month_num - 1]
    # return ((1151794505154789279 ^ (leap_year << 5)) >> (5 * (month_num - 1))) & 31
    if month_num == 2:
        if leap_year:
            return 29
        else:
            return 28

    elif month_num in [1, 3, 5, 7, 8, 10, 12]:
        return 31

    elif month_num in [4, 6, 9, 11]:
        return 30

def construct_cal_month(month_num, first_day_of_month, num_days_in_month):
    output = []
    months = {1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October", 11: "November", 12: "December"}

    output.append(months.get(month_num))

    week_list = []

    initial_jump = first_day_of_month
    number_of_weeks = -((num_days_in_month + initial_jump) // -7)  # Ceiling division

    week = 1
    day_count = 1

    for week in range(1, number_of_weeks + 1):
        if week == 1:
            jumpcut = "   " * initial_jump
            rest_of_first_week = ""

            while day_count <= (7 - initial_jump):
                rest_of_first_week += "  {}".format(day_count)
                day_count += 1

            jumpcut += rest_of_first_week
            week_list.append(jumpcut)

        elif week == number_of_weeks:
            final_week = ""

            while day_count <= num_days_in_month:
                final_week += " {}".format(day_count)
                day_count += 1

            week_list.append(final_week)

        else:
            subsequent_week = ""

            while day_count <= num_days_in_month:

                if day_count <= (week * 7 - initial_jump):

                    # Digit checker
                    if int(math.log10(day_count)) + 1 == 1:
                        subsequent_week += "  {}".format(day_count)
                    elif int(math.log10(day_count)) + 1 == 2:
                        subsequent_week += " {}".format(day_count)

                    day_count += 1

                else:
                    week_list.append(subsequent_week)
                    subsequent_week = ""
                    break

    output.extend(week_list)

    return output

def initial_month_day(year):
    output = []
    jan1 = day_of_week_jan1(year)
    prev_first_day = jan1
    num_days = []

    output.append(jan1)

    for month in range(1, 12):
        num_days.append(num_days_in_month(month, leap_year(year)))

    for each_month in num_days:
        prev_first_day = (prev_first_day + each_month) % 7
        output.append(prev_first_day)

    return output

def construct_cal_year(year):
    output = []
    output.append(int(year))

    first_days = initial_month_day(year)

    months = []

    for month in range(1, 13):
        month_sublist = construct_cal_month(month, first_days[month - 1], num_days_in_month(month, leap_year(year)))

        months.append(month_sublist)

    output.extend(months)

    return output

def display_calendar(year):
    year_list = construct_cal_year(year)
    year_list.remove(year_list[0])

    main_output = ""

    for month in year_list:
        main_output += month[0] + "\n"
        main_output += "  S  M  T  W  T  F  S\n"

        for week in month[1:]:
            if month[0] == "December" and week == month[-1]:
                main_output += week
            else:
                main_output += week + "\n"

        if month[0] == "December":
            pass
        else:
            main_output += "\n"

    return main_output


import numpy as np
import pandas as pd

from xgboost import XGBClassifier
import xgboost as xgb

from sklearn.metrics import auc
from sklearn.metrics import roc_curve
import matplotlib.pyplot as plt
from sklearn.metrics import f1_score
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
from sklearn.model_selection import learning_curve
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.metrics import precision_recall_curve
from sklearn.model_selection import cross_val_score
from sklearn.metrics import confusion_matrix
from sklearn.tree import export_graphviz
from sklearn.model_selection import KFold
from sklearn.model_selection import GridSearchCV

warnings.filterwarnings('ignore')

df=pd.read_csv('/usr/local/dataset/cardio_train.csv',
                        sep = ';'
                        #names = ['age','gender','height','weight',
                                 #'ap_hi','ap_lo','cholesterol','glu',
                                 #'smoke','alco','active',
                                 #'cardio']
                                 )

data = df[(df['ap_lo'] <= df['ap_hi']) &
                 (df['height'] >= df['height'].quantile(0.025)) &
                 (df['height'] <= df['height'].quantile(0.975)) &
                 (df['weight'] >= df['weight'].quantile(0.025)) &
                 (df['weight'] <= df['weight'].quantile(0.975))]
1 - data.shape[0] / df.shape[0]
print(data.groupby("cardio").size())
data.drop(columns=['id'], inplace=True)
data['age']=round(data['age']/365).apply(lambda x: int(x))

print(f"In {data[data['ap_hi'] < data['ap_lo']].shape[0]} obeservation ap_hi is lower than ap_low, which is incorrect.")
print('_'*80)
print()
print("Let's remove them:")

data = data[data['ap_hi'] > data['ap_lo']].reset_index(drop=True)
data.head()

def BMI(data):
    return data['weight'] / (data['height']/100)**2
data['bmi'] = data.apply(BMI, axis=1)
data.drop(columns=['height','weight'], inplace=True)
# print(data.head())
#data.drop(columns=['id'], inplace=True)
#data.head()
data.info()
print(data.groupby("cardio").size())
data.dtypes
print(data.dtypes)

y = data['cardio']
x = data.drop(['cardio'], axis = 1)
print("Shape of X: {0}; positive example: {1}; negative: {2}".format(x.shape, y[y==1].shape[0], y[y==0].shape[0]))  # 查看数据的形状和类别分布
x_train, x_test, y_train, y_test = train_test_split(data.drop('cardio', 1), data['cardio'], test_size = .2, random_state=10) #split the data

#model=XGBClassifier()
model = XGBClassifier(learning_rate=0.055,n_estimators=400,max_depth=5,
			min_child_weight=32,gamma=0.1,subsample=0.7,
			colsample_bytree=1,reg_alpha=0.04,reg_lambda=1,
			scale_pos_weight=1,eta=0.1
			)

model.fit(x_train, y_train)
train_score = model.score(x_train, y_train)
test_score = model.score(x_test, y_test)
print("train score: {train_score:.6f}; test score: {test_score:.6f}".format(train_score=train_score, test_score=test_score))

#模型预测
y_pred = model.predict(x_test)
print("matchs: {0}/{1}".format(np.equal(y_pred, y_test).shape[0], y_test.shape[0]))
xg_result = accuracy_score(y_test,y_pred)
print("Accuracy:", xg_result)

f1_score(y_test,y_pred)
print(classification_report(y_test,y_pred))

confusion_matrix = confusion_matrix(y_test,y_pred)
print(confusion_matrix)
print('confusion_matrix:\n' , confusion_matrix)
y_predict = model.predict_proba(x_test)[:,1]
y_pred_quant=model.fit(x_train, y_train).predict_proba(x_test)[:, 1]

recall = confusion_matrix[1][1]/(confusion_matrix[1][1]+confusion_matrix[1][0])
precision = confusion_matrix[1][1]/(confusion_matrix[1][1]+confusion_matrix[0][1])
print("Recall:",recall,"Precision:",precision)

precisions,recalls,thresholds = precision_recall_curve(y_test,y_pred)
plt.plot(thresholds,precisions[:-1])
plt.plot(thresholds,recalls[:-1])
plt.grid()
plt.show()

#Plot ROC
fpr, tpr, thresholds = roc_curve(y_test, y_pred_quant)
fig, ax = plt.subplots()
ax.plot(fpr, tpr)
ax.plot([0, 1], [0, 1], transform=ax.transAxes, ls="--", c=".3")
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.0])
plt.rcParams['font.size'] = 12
plt.title('ROC curve for diabetes classifier')
plt.xlabel('False Positive Rate (1 - Specificity)')
plt.ylabel('True Positive Rate (Sensitivity)')
plt.grid(True)
plt.show()
plt.savefig('xgb_roc_2.png')
#Compute AUC
roc_auc = auc(fpr, tpr)
print('ROC_AUC_Score:', roc_auc)
print('successful')

plt.figure(figsize=(12,6))
xgb.plot_importance(model, max_num_features=30)
plt.title("Featurertances")
plt.savefig('xgboost.png')
plt.show()
'''
param_test1 = {'n_estimators':[45,49,50,51,55]}
gsearch1 = GridSearchCV(estimator = XGBClassifier(learning_rate=0.1, n_estimators=500, max_depth= 5, min_child_weight= 1, seed= 0,subsample=0.8, colsample_bytree=0.8, gamma=0, reg_alpha=0, reg_lambda=1),
                       param_grid = param_test1, scoring='roc_auc',cv=5)
gsearch1.fit(x_train,y_train)
print( gsearch1.best_params_, gsearch1.best_score_)
'''


from News_Crawler import utils
from lxml import html
import requests, os
import pandas as pd

def crawl_latest_proxies():
    url = "https://free-proxy-list.net"
    root = html.document_fromstring(requests.get(url).content)

    th_elms = root.cssselect("table#proxylisttable thead tr th")
    columns = [th.text for th in th_elms]
    print(columns)

    data = []

    tr_elms = root.cssselect("table#proxylisttable tbody tr")
    for tr in tr_elms:
        data.append([td.text for td in tr.cssselect("td")])

    print("Crawl {} proxies from {} done".format(len(data), url))
    return pd.DataFrame(data, columns=columns)

def get_proxy_urls(df):
    proxies = []
    for idx, row in df.iterrows():
        scheme = "https" if row["Https"] == "yes" else "http"
        url = "{}://{}:{}".format(scheme, row["IP Address"], row["Port"])
        proxies.append(url)

    return proxies

if __name__ == "__main__":
    proxies = crawl_latest_proxies()
    proxy_dir = "./Proxy"
    utils.mkdirs(proxy_dir)
    proxies.to_csv(os.path.join(proxy_dir, "proxies.csv"), index=False)

    proxy_urls = get_proxy_urls(proxies)
    utils.save_list(proxy_urls, path=os.path.join(proxy_dir, "proxy_list.txt"))
    print(proxies.head())

    # print("\n".join(proxy_urls[:10]))


# coding=utf-8

# a)
def contaDigitos(n, d):
    lista_s = str(n)
    digito = str(d)

    contador = 0
    for i in lista_s:
        if digito == i:
            contador += 1
        else:
            continue
    return "O digito {} aparece {} vezes em {}".format(d, contador, n)

# b)


import csv
import os
import numpy as np

from mapel.elections.cultures_ import store_votes_in_a_file

def convert_pb_to_app(experiment, num_candidates=100, num_voters=100, model='pabulib'):

    path = os.path.join(os.getcwd(), "experiments", experiment.experiment_id, "source")

    for p, name in enumerate(os.listdir(path)):
        print(name)

        path = f'experiments/{experiment.experiment_id}/source/{name}'

        votes = {}
        projects = {}

        # import from .pb file
        with open(path, 'r', newline='', encoding="utf-8") as csvfile:
            meta = {}
            section = ""
            header = []
            reader = csv.reader(csvfile, delimiter=';')
            for row in reader:
                if str(row[0]).strip().lower() in ["meta", "projects", "votes"]:
                    section = str(row[0]).strip().lower()
                    header = next(reader)
                elif section == "meta":
                    meta[row[0]] = row[1].strip()
                elif section == "projects":
                    projects[row[0]] = {}
                    for it, key in enumerate(header[1:]):
                        projects[row[0]][key.strip()] = row[it+1].strip()
                elif section == "votes":
                    votes[row[0]] = {}
                    for it, key in enumerate(header[1:]):
                        votes[row[0]][key.strip()] = row[it+1].strip()

        # extract approval ballots from votes
        approval_votes = []
        for vote in votes.values():
            vote = vote['vote'].split(',')
            approval_votes.append(set(vote))

        # randomly map projects to [0,1,2...,num_projects]
        mapping = {}
        perm = np.random.permutation(len(projects))
        for i, key in enumerate(projects.keys()):
            mapping[key] = perm[i]

        approval_votes = [[mapping[i] for i in vote] for vote in approval_votes]

        # cut projects to [0,1,2...,k]
        approval_votes_cut = []
        for vote in approval_votes:
            vote_cut = set()
            for c in vote:
                if c < num_candidates:
                    vote_cut.add(c)
            approval_votes_cut.append(vote_cut)

        # cut the voters:
        perm = np.random.permutation(len(votes))
        # print(len(perm))
        final_approval_votes_cut = []
        for i, vote in enumerate(approval_votes_cut):
            # print(num_voters)
            if perm[i] < num_voters:
                # print(perm[i])
                final_approval_votes_cut.append(vote)
        # print(len(final_approval_votes_cut))

        # store in .app file
        name = name.replace('.pb', '')
        path = f'experiments/{experiment.experiment_id}/elections/{model}_{p}.app'
        # num_candidates = num_candidates
        # num_voters = len(votes)
        params = {}
        ballot = 'approval'

        election = None
        model_id = model
        store_votes_in_a_file(election, model_id, num_candidates, num_voters,
                          params, path, ballot, votes=final_approval_votes_cut)


import random
import json
import torch
from main_function import NeuralNetwork, NeuralNet, bag_of_words, tokenize
from essential_function import dirlocation

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
with open(f"{dirlocation()}\database\main_function\intents.json",'r') as json_data:
  intents = json.load(json_data)

FILE = f"{dirlocation()}\TrainData.pth"
data = torch.load(FILE)

input_size = data["input_size"]
hidden_size = data["hidden_size"]
output_size = data["output_size"]
all_words = data["all_words"]
tags = data["tags"]
model_state = data["model_state"]

model = NeuralNet(input_size, hidden_size, output_size).to(device)
model.load_state_dict(model_state)
model.eval()

# =======================
Name = "Rafiq"

from main_function import Listen, Say, Say_in_arabic, NonInputExecution, InputExecution

global stop_this
stop_this = False

def Main():
  sentence = Listen()
  result = str(sentence)

  if sentence == "bye":
    exit()

  sentence = tokenize(sentence)
  X = bag_of_words(sentence, all_words)
  X = X.reshape(1,X.shape[0])
  X = torch.from_numpy(X).to(device)

  output = model(X)

  _ , predicted = torch.max(output,dim=1)

  tag = tags[predicted.item()]

  probs = torch.softmax(output, dim=1)
  prob = probs[0][predicted.item()]

  if prob.item() > 0.75:
    for intent in intents['intents']:
      if tag == intent["tag"]:
        reply = random.choice(intent["responses"])

        if "time" in reply:
          NonInputExecution(reply)

        elif "exit_loop" in reply:
          global stop_this
          stop_this = True

        elif "rafiq" in reply:
          NonInputExecution(reply)

        elif "open" in reply:
          InputExecution(reply, sentence)

        elif "close" in reply:
          InputExecution(reply, sentence)

        elif "date" in reply:
          NonInputExecution(reply)

        elif "wikipedia" in reply:
          InputExecution(reply, sentence)

        elif "ctrweb" in reply:
          InputExecution(reply, sentence)

        elif "google" in reply:
          InputExecution(reply, result)

        elif "health" in reply:
          NonInputExecution(reply)

        else:
          Say(reply)

while True:
  Main()
  if stop_this == True:
    break
  else:
    continue


from typing import Any, Dict
import unittest

import pandas as pd

from mlir_pandas import DataFrame, Series

class AggregationTest(unittest.TestCase):
    data: Dict[str, Any] = {"col1": [1, 2, 3], "col2": [4, 5, 6], "col3": [7, 8, 9]}

    def test_aggregation_df(self) -> None:
        df: DataFrame = DataFrame(self.data)
        df_orig: pd.DataFrame = pd.DataFrame(self.data)

        self.assertTrue(
            df_orig.agg(s=("col1", "sum"), m=("col2", "mean")).equals(
                df.agg(s=("col1", "sum"), m=("col2", "mean"))._mock
            )
        )

        self.assertTrue(
            df_orig.agg(s=("col1", "sum"), c=("col1", "count"), m=("col2", "mean")).equals(
                df.agg(s=("col1", "sum"), c=("col1", "count"), m=("col2", "mean"))._mock
            )
        )

        self.assertTrue(
            df_orig.agg(s=("col1", "sum")).equals(
                df.agg(s=("col1", "sum"))._mock
            )
        )

    def test_aggregation_series(self) -> None:
        s: Series = Series(self.data["col1"], name="col1")
        s_orig: pd.Series = pd.Series(self.data["col1"], name="col1")

        self.assertTrue(s_orig.agg(s="sum").astype("Int64").equals(s.agg(s="sum")._mock))

        self.assertTrue(
            s_orig.agg(s="sum", m="mean").astype("Int64").equals(s.agg(s="sum", m="mean")._mock)
        )


from itertools import product

with open('inputs/d18.txt', 'r') as in_f:
  lines = [line.strip() for line in in_f.readlines()]

cubes = {}
for line in lines:
  toks = line.split(',')
  cubes[(int(toks[0]), int(toks[1]), int(toks[2]))] = 0

# Count faces that are only covered by air (component 1)
def get_uncovered(cubes):
  ret = 0

  for cube in cubes:
    # Only count lava
    if cubes[cube] == 1:
      continue
    # Count and subtract covered faces
    uncovered = 6
    if cubes.get((cube[0] + 1, cube[1], cube[2]), 1) != 1:
      uncovered -= 1
    if cubes.get((cube[0] - 1, cube[1], cube[2]), 1) != 1:
      uncovered -= 1
    if cubes.get((cube[0], cube[1] + 1, cube[2]), 1) != 1:
      uncovered -= 1
    if cubes.get((cube[0], cube[1] - 1, cube[2]), 1) != 1:
      uncovered -= 1
    if cubes.get((cube[0], cube[1], cube[2] + 1), 1) != 1:
      uncovered -= 1
    if cubes.get((cube[0], cube[1], cube[2] - 1), 1) != 1:
      uncovered -= 1

    ret += uncovered

  return ret

# Silver
print(get_uncovered(cubes))

# Gold
def spread_component(cubes, cube, component):
  stack = [cube]

  while stack:
    curr = stack.pop()

    # Only spread to unmarked cubes
    if not curr in cubes or cubes[curr] != -1:
      continue

    cubes[curr] = component
    # X
    stack.append((curr[0] + 1, curr[1],     curr[2]))
    stack.append((curr[0] - 1, curr[1],     curr[2]))
    # Y
    stack.append((curr[0],     curr[1] + 1, curr[2]))
    stack.append((curr[0],     curr[1] - 1, curr[2]))
    # Z
    stack.append((curr[0],     curr[1],     curr[2] + 1))
    stack.append((curr[0],     curr[1],     curr[2] - 1))

# Get lax envelope
max_x = 0
max_y = 0
max_z = 0
for cube in cubes:
  max_x = max(cube[0], max_x)
  max_y = max(cube[1], max_y)
  max_z = max(cube[2], max_z)
max_x += 3
max_y += 3
max_z += 3

# Add air cubes
for x, y, z in product(range(0, max_x), range(0, max_y), range(0, max_z)):
  cube = (x, y, z)

  # Is already lava
  if cube in cubes:
    continue
  # Mark as neither lava nor air
  cubes[cube] = -1

# Mark corner as air and spread from there
spread_component(cubes, (0, 0, 0), 1)
print(get_uncovered(cubes))


from PyQt4.QtCore import *
from PyQt4.QtGui import *

import appGlobal
import os

class AboutDialog(QDialog):
	def __init__(self, parent = None, firstTime = False):
		app = appGlobal.getApp()
		QDialog.__init__(self, parent, flags = Qt.WindowStaysOnTopHint)
		self.setFixedSize(400, 260)
		#self.setFixedWidth(400)
		self.setStyleSheet("background: white")

		if app.isWindows or app.isLinux:
			frame = QFrame(self)
			frame.setFrameShape(QFrame.Box)
			frame.setLineWidth(1)
			#frame.setFixedSize(400, height)
			frame.setFixedSize(400, 260)

			self.sizer = QVBoxLayout(frame)
		else:
			self.sizer = QVBoxLayout(self)
		self.sizer.setMargin(0)
		self.sizer.setSpacing(5)

		pm = QPixmap(os.path.join(appGlobal.getPath(), 'icons/icarra.png'))
		self.img = QLabel()
		self.img.setPixmap(pm)
		self.sizer.addWidget(self.img)

		self.sizer.addSpacing(20)
		label = QLabel("Icarra version %d.%d.%d" % (appGlobal.gMajorVersion, appGlobal.gMinorVersion, appGlobal.gRelease))
		label.setStyleSheet("font-weight: bold")
		self.sizer.addWidget(label, alignment = Qt.AlignCenter)
		self.sizer.addWidget(QLabel("<qt>© 2004-2011 Jesse Liesch</qt>", alignment = Qt.AlignCenter))
		self.sizer.addSpacing(20)

		label = QLabel("Developers")
		label.setStyleSheet("font-weight: bold")
		self.sizer.addWidget(label, alignment = Qt.AlignCenter)
		for name in ["Jesse Liesch", "James G Scherer"]:
			self.sizer.addWidget(QLabel(name, alignment = Qt.AlignCenter))
		self.sizer.addSpacing(30)

		# Center
		screen = app.desktop().screenGeometry()
		self.move(screen.center() - self.rect().center())

		self.exec_()


import streamlit as st
import numpy as np
import pandas as pd

# load model
from recommender_model import lover_recommender_test, offspring_subset

# load data
cupid_df = pd.read_pickle('data/grouped_cupid.pkl')
cupid = pd.read_pickle('data/clean_cupid.pkl')

# drop "status", "location"
cupid.drop(columns = ['status', 'location'], inplace = True)

st.set_page_config(layout = "wide", page_title = 'Lover Recommender App', page_icon = '💘')

# sidebar

st.title("💘 Lover Recommender App 💘")
st.header("Looking For A Partner? 💑👩❤👩👨❤👨")
st.markdown("----------------------------------------")

# user input features
st.subheader("Tell us a little bit about yourself first...")

# user_form = st.form(key = "my_form")

# input
age = st.number_input('How old are you?')

st.write("What's your age range?")

col1, col2 = st.beta_columns(2)
with col1:
    lowest_age = st.number_input('Lowest Age:')
with col2:
    highest_age = st.number_input('Highest Age:')

sex = st.radio('What gender do you identify as?',['m', 'f'])
orientation = st.radio('What sexual orientation do you identify with?',['straight', 'gay', 'bisexual'])
body_type = st.selectbox('What body type do you have?',('average', 'fit', 'thin', 'full figured', 'used up', 'rather not say'))
diet = st.selectbox('What does your diet consist of?',('anything', 'vegetarian', 'vegan', 'kosher', 'halal', 'other'))
drinks = st.radio('Do you consume alcoholic beverages?',['yes','no', 'sometimes'])
drugs = st.radio('Do you use drugs?',['yes', 'no', 'sometimes'])

# offspring

# do you have any children? yes/no
any_children = st.radio('Do you have any kid(s)/children?', ['yes', 'no'])

# do you want any [more] children? yes/no
more_children = st.radio('Do you want any [more] kid(s)/children?', ['yes', 'no'])

if any_children == 'no' and more_children == 'yes':
    offspring = "doesn't have kid(s), but wants kid(s)"
elif any_children == 'no' and more_children == 'no':
    offspring = "doesn't have kids, and doesn't want any"
elif any_children == 'yes' and more_children == 'no':
    offspring = "has kid(s), but doesn't want more"
elif any_children == 'yes' and more_children == 'yes':
    offspring = "has kid(s) and wants more"

pets = st.selectbox("What's your sentiment on dogs and/or cats?",('likes dogs', 'likes cats', 'likes dogs and cats', 'dislikes dogs and cats'))
smokes = st.radio('Do you smoke?',['yes', 'no', 'sometimes'])

# does religion matter?
religion = st.selectbox("Please specify your religion.", ("doesn't matter", 'agnosticism', 'christianity', 'catholicism', 'judaism', 'buddhism', 'hinduism', 'islam', 'other'))

invalue = np.array([age, sex, orientation, body_type, diet, drinks, drugs, offspring, pets, religion, smokes])

st.subheader("Show Me My Matches!!!")
click = st.checkbox("Check Here ✔")

if click:
    matches = lover_recommender_test(invalue, religion, lowest_age, highest_age)

    # show matches from OG cupid
    try:
        st.table(matches)

        st.markdown("What profile(s) catch your eye? 👀")
        options = st.multiselect("", list(matches.index))

        # keep a running df of recommended matches
        all_recs = matches

        # keep a running df of profiles liked
        liked = pd.DataFrame(columns = cupid_df.columns)
        invalue_df = pd.DataFrame(columns = cupid_df.columns)

        for value in options:
            liked = liked.append(cupid.loc[value])
            invalue_df = invalue_df.append(cupid_df.loc[value])

        # more matches
        st.markdown("Would you like to see more matches?")
        more = st.radio("", ['No', 'Yes'])

        # try:
        if more == 'Yes' and len(liked) > 0:

            # straight female
            if sex == 'f' and orientation == 'straight':
                straight_female = cupid_df[(((cupid_df['sex'] == 'm') & (cupid_df['orientation'] == 'straight')) | ((cupid_df['sex'] == 'm') & (cupid_df['orientation'] == 'bisexual'))) \
                & (cupid_df['religion'] == religion) & (cupid_df['age'] >= lowest_age) & (cupid_df['age'] <= highest_age)]

                matches = offspring_subset(invalue_df, straight_female)

            # straight male
            elif sex == 'm' and orientation == 'straight':
                straight_male = cupid_df[(((cupid_df['sex'] == 'f') & (cupid_df['orientation'] == 'straight')) | ((cupid_df['sex'] == 'f') & (cupid_df['orientation'] == 'bisexual'))) \
                    & (cupid_df['religion'] == religion) & (cupid_df['age'] >= lowest_age) & (cupid_df['age'] <= highest_age)]

                matches = offspring_subset(invalue_df, straight_male)

            # gay female
            elif sex == 'f' and orientation == 'gay':
                gay_female = cupid_df[(cupid_df['sex'] == 'f') & ((cupid_df['orientation'] == 'gay') | (cupid_df['orientation'] == 'bisexual')) & \
                    (cupid_df['religion'] == religion) & (cupid_df['age'] >= lowest_age) & (cupid_df['age'] <= highest_age)]

                matches = offspring_subset(invalue_df, gay_female)

            # gay male
            elif sex == 'm' and orientation == 'gay':
                gay_male = cupid_df[(cupid_df['sex'] == 'm') & ((cupid_df['orientation'] == 'gay') | (cupid_df['orientation'] == 'bisexual')) & \
                    (cupid_df['religion'] == religion) & (cupid_df['age'] >= lowest_age) & (cupid_df['age'] <= highest_age)]

                matches = offspring_subset(invalue_df, gay_male)

            # bi female looking for bi individual or straight male or gay female
            elif sex == 'f' and orientation == 'bisexual':
                bi_female = cupid_df[((cupid_df['sex'] == 'f') & (cupid_df['orientation'] == 'gay') & (cupid_df['religion'] == religion) & \
                        (cupid_df['age'] >= lowest_age) & (cupid_df['age'] <= highest_age)) | ((cupid_df['sex'] == 'm') & (cupid_df['orientation'] == 'straight') & \
                    (cupid_df['religion'] == religion) & (cupid_df['age'] >= lowest_age) & (cupid_df['age'] <= highest_age)) | \
                    (cupid_df['orientation'] == 'bisexual')  & (cupid_df['religion'] == religion) & (cupid_df['age'] >= lowest_age) & (cupid_df['age'] <= highest_age)]

                matches = offspring_subset(invalue_df, bi_female)

            # bi male looking for bi individual or straight female or gay male
            elif orientation == 'bisexual' and sex == 'm':
                bi_male = cupid_df[((cupid_df['sex'] == 'm') & (cupid_df['orientation'] == 'gay') & (cupid_df['religion'] == religion) & \
                        (cupid_df['age'] >= lowest_age) & (cupid_df['age'] <= highest_age)) | ((cupid_df['sex'] == 'f') & (cupid_df['orientation'] == 'straight') & \
                    (cupid_df['religion'] == religion) & (cupid_df['age'] >= lowest_age) & (cupid_df['age'] <= highest_age)) | \
                    (cupid_df['orientation'] == 'bisexual')  & (cupid_df['religion'] == religion) & (cupid_df['age'] >= lowest_age) & (cupid_df['age'] <= highest_age)]

                matches = offspring_subset(invalue_df, bi_male)

            # to return OG cupid outputs, that were based off grouped values
            # df to show users -- OG cupid
            show_users = pd.DataFrame(columns = cupid.columns)

            for value2 in matches.index:
                show_users = show_users.append(cupid.loc[value2])

            st.markdown("Here are more matches, based on the profile(s) that caught your eye earlier! 🤗")
            st.table(show_users)

            # any more profiles that users liked
            st.markdown("Any of these profiles catch your eye? 👁")
            options_more = st.multiselect("", list(show_users.index))

            for value in options_more:
                liked = liked.append(cupid.loc[value])

            # if options_more:
            #     st.subheader("Here are all the profiles you liked:")
            #     st.table(liked)
            #     st.subheader("Go on and send a message! 💌 Happy chatting! 💞💓")

        elif more == 'No':
            pass

        else:
            st.markdown("**❗❗ NOTE: If you'd like to see more matches, please select profiles from above that piqued your interest! 🙎**")

        # except:
        #     st.markdown("**NOTE: If you'd like to see more matches, please select profiles from above that piqued your interest! 🙎**")

        st.subheader("Here are all the profiles you liked:")
        st.table(liked)
        st.subheader("Go on and send a message! 💌 Happy chatting! 💞💓")

    except:
        st.image("https://media1.tenor.com/images/5a7baa3abccc024569143229fa700dd6/tenor.gif?itemid=10592594", width = 350)
        st.subheader("Apologies!! We don't have any profiles in the database that relate to your *age range*, *orientation*, *offspring sentiment* and *religious* inputs at the moment. 🙅😭")


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

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import sys
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from shiboken2 import wrapInstance
import maya.OpenMayaUI as OpenMayaUI
import maya.cmds as cmds
from . import editTangent
from ..manuWidget import boxSliderWidget as boxSliderWidget

class EditorUI(QMainWindow):
	def __init__(self,parent=None):
		super(EditorUI,self).__init__(parent)
		self.setWindowFlags(Qt.Window)
		self.resize(400,100)

		self.widget = EditorWidget(self)
		self.setCentralWidget(self.widget)
		title = self.widget.windowTitle()
		self.setWindowTitle(title)

	def closeEvent(self, e):
		try:
			self.widget.close()
		except:
			pass

class EditorWidget(QWidget):
	def __init__(self,parent=None):
		super(EditorWidget,self).__init__(parent)
		self.setWindowTitle('Curve Editor')
		self.initUI()

	def initUI(self):
		self.widget_t = TanSliderWidget(self)
		self.widget_w = WgtSliderWidget(self)
		layout = QVBoxLayout()
		layout.addWidget(self.widget_t)
		layout.addWidget(self.widget_w)
		self.setLayout(layout)

	def closeEvent(self, e):
		try:
			self.widget_t.close()
			self.widget_w.close()
		except:
			pass

class TanSliderWidget(QWidget):
	def __init__(self,parent=None):
		super(TanSliderWidget,self).__init__(parent)
		self.setWindowTitle('Tangent Editor')
		self.initUI()

	def initUI(self):
		self.boxSlider = boxSliderWidget.BoxSliderWidget(self,-90,90)
		self.boxSlider.funcValueChanged = self.changed_editor

		# maya上から値を拾っている
		if editTangent.check_animation():
			self.set_ui_value(1)
		else:
			self.boxSlider.slider.setValue(0)
			self.boxSlider.dspinBox.setValue(0)

		#　ラジオボタンとか
		self.radioIo_A = QRadioButton('both',self)
		self.radioIo_A.setChecked(True)
		self.radioIo_B = QRadioButton('in',self)
		self.radioIo_C = QRadioButton('out',self)
		self.radioIoGroup = QButtonGroup()
		self.radioIoGroup.addButton(self.radioIo_A,1)
		self.radioIoGroup.addButton(self.radioIo_B,2)
		self.radioIoGroup.addButton(self.radioIo_C,3)

		self.radioIo_A.setFixedWidth(50)
		self.radioIo_B.setFixedWidth(50)
		self.radioIo_C.setFixedWidth(50)

		self.tangentLlabel = QLabel('Tangent :',self)

		self.radioIoGroup.buttonClicked[int].connect(self.set_ui_value)

		# レイアウト決め
		self.vLayout = QVBoxLayout()

		self.hLayout_A = QHBoxLayout()
		self.hLayout_A.addWidget(self.tangentLlabel)
		self.hLayout_A.addWidget(self.radioIo_A)
		self.hLayout_A.addWidget(self.radioIo_B)
		self.hLayout_A.addWidget(self.radioIo_C)
		self.hLayout_A.addStretch()
		self.vLayout.addLayout(self.hLayout_A)

		self.hlayout_b = QHBoxLayout()
		self.hlayout_b.addWidget(self.boxSlider)
		self.vLayout.addLayout(self.hlayout_b)
		self.scriptNo = []
		self.scriptNo.append(cmds.scriptJob(e=["SelectionChanged",self.changed_selection]))
		self.scriptNo.append(cmds.scriptJob(e=["Redo",self.changed_selection]))
		self.scriptNo.append(cmds.scriptJob(e=["Undo",self.changed_selection]))
		self.vLayout.setContentsMargins(0, 0, 0, 0)
		self.vLayout.setSpacing(0)
		self.setLayout(self.vLayout)

	def closeEvent(self, e):
		if self.scriptNo:
			for no in self.scriptNo:
				cmds.scriptJob(k=no)

	def changed_editor(self):
		if editTangent.check_animation():
			editTangent.set_angle(self.radioIoGroup.checkedId(),self.boxSlider.dspinBox.value())

	def changed_selection(self):
		io = self.radioIoGroup.checkedId()
		self.set_ui_value(io)

	def set_ui_value(self,io):
		if editTangent.check_animation():
			self.boxSlider.blockSignals(True)
			self.boxSlider.slider.setValue(editTangent.get_angle(io) * 100)
			self.boxSlider.dspinBox.setValue(editTangent.get_angle(io))
			self.boxSlider.blockSignals(False)
		else:
			self.boxSlider.blockSignals(True)
			self.boxSlider.slider.setValue(0)
			self.boxSlider.dspinBox.setValue(0)
			self.boxSlider.blockSignals(False)

class WgtSliderWidget(TanSliderWidget):
	def __init__(self,parent=None):
		super(WgtSliderWidget,self).__init__(parent)
		self.setWindowTitle('Weight Editor')

	def initUI(self):
		self.boxSlider = boxSliderWidget.BoxSliderWidget(self,0,100)
		self.boxSlider.funcValueChanged = self.changed_editor

		# maya上から値を拾っている
		if editTangent.check_animation():
			self.set_ui_value(1)
		else:
			self.boxSlider.slider.setValue(0)
			self.boxSlider.dspinBox.setValue(0)

		#　ラジオボタンとか
		self.radioIo_A = QRadioButton('both',self)
		self.radioIo_A.setChecked(True)
		self.radioIo_B = QRadioButton('in',self)
		self.radioIo_C = QRadioButton('out',self)
		self.radioIoGroup = QButtonGroup()
		self.radioIoGroup.addButton(self.radioIo_A,1)
		self.radioIoGroup.addButton(self.radioIo_B,2)
		self.radioIoGroup.addButton(self.radioIo_C,3)

		self.radioIo_A.setFixedWidth(50)
		self.radioIo_B.setFixedWidth(50)
		self.radioIo_C.setFixedWidth(50)

		self.weighLlabel = QLabel('Weight :',self)

		self.radioIoGroup.buttonClicked[int].connect(self.set_ui_value)

		self.checkBox = QCheckBox('Weight Tangent',self)
		self.set_weight_checkBox()
		self.checkBox.stateChanged.connect(editTangent.toggle_wieghtTangent)

		# レイアウト決め
		self.vLayout = QVBoxLayout()

		self.hLayout_A = QHBoxLayout()
		self.hLayout_A.addWidget(self.weighLlabel)
		self.hLayout_A.addWidget(self.radioIo_A)
		self.hLayout_A.addWidget(self.radioIo_B)
		self.hLayout_A.addWidget(self.radioIo_C)
		self.hLayout_A.addWidget(self.checkBox)
		self.hLayout_A.addStretch()
		self.vLayout.addLayout(self.hLayout_A)

		self.hlayout_b = QHBoxLayout()
		self.hlayout_b.addWidget(self.boxSlider)
		self.vLayout.addLayout(self.hlayout_b)
		self.scriptNo = []
		self.scriptNo.append(cmds.scriptJob(e=["SelectionChanged",self.changed_selection]))
		self.scriptNo.append(cmds.scriptJob(e=["Redo",self.changed_selection]))
		self.scriptNo.append(cmds.scriptJob(e=["Undo",self.changed_selection]))
		self.vLayout.setContentsMargins(0, 0, 0, 0)
		self.vLayout.setSpacing(0)
		self.setLayout(self.vLayout)

	def changed_editor(self):
		if editTangent.check_animation():
			editTangent.set_weight(self.radioIoGroup.checkedId(),self.boxSlider.dspinBox.value())

	def changed_selection(self):
		self.set_weight_checkBox()
		io = self.radioIoGroup.checkedId()
		self.set_ui_value(io)

	def set_weight_checkBox(self):
		self.checkBox.blockSignals(True)
		if editTangent.check_animation():
			self.checkBox.setChecked(editTangent.get_weightTangent())
		else:
			self.checkBox.setChecked(False)
		self.checkBox.blockSignals(False)

	def set_ui_value(self,io):
		if editTangent.check_animation():
			self.boxSlider.blockSignals(True)
			self.boxSlider.slider.setValue(editTangent.get_weight(io) * 100)
			self.boxSlider.dspinBox.setValue(editTangent.get_weight(io))
			self.boxSlider.blockSignals(False)
		else:
			self.boxSlider.blockSignals(True)
			self.boxSlider.slider.setValue(0)
			self.boxSlider.dspinBox.setValue(0)
			self.boxSlider.blockSignals(False)

def main():
	mayaWindow = 'graphEditor1Window' #常にこのウィンドウより前にいます
	ptr = OpenMayaUI.MQtUtil.findWindow(mayaWindow)
	if ptr is not None:
		parent = wrapInstance(int(ptr),QWidget)
	else:
		cmds.error('Please open the GraphEditor')
	app = QApplication.instance()
	ui = EditorUI(parent)
	ui.show()
	sys.exit()
	app.exec_()

if __name__ == "__main__":
	main()


from ....core.runtime.task_base import TaskBase
from ....core.log.log import Log
from .sonar_control_messages import SonarDataInd

try:
    import RPi.GPIO as GPIO
except ImportError:
    from ....core.runtime.gpio_stub import GPIOStub as GPIO

from time import time
from time import sleep
from threading import Lock

class SonarTask(TaskBase):
    INIT_PULSE = 0
    WAIT_FOR_PULSE_START = 1
    WAIT_FOR_PULSE_END = 2
    PULSE_END = 3
    def __init__(self, comm_if):
        self.comm_if = comm_if
        self.trig_pin = 11
        self.echo_pin = 13

        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(self.trig_pin, GPIO.OUT)
        GPIO.setup(self.echo_pin, GPIO.IN)
        GPIO.add_event_detect(self.echo_pin, GPIO.BOTH, callback=self.pin_callback)

        self.pulse_start = time()
        self.pulse_end = time()

        self.pin_states = [SonarTask.INIT_PULSE, SonarTask.WAIT_FOR_PULSE_START, SonarTask.WAIT_FOR_PULSE_END, SonarTask.PULSE_END]
        self.pin_state = 0

        self.interrupt_lock = Lock()

    def pin_callback(self, pin):
        self.interrupt_lock.acquire()
        if SonarTask.WAIT_FOR_PULSE_START == self.pin_states[self.pin_state]:
            self.pulse_start = time()
            if 1 == GPIO.input(self.echo_pin):
                self.pin_state += 1
            else:
                #Pin toggled back to 0 before we had the chance to read it.
                #We're CLOSE to something. Set pulse_end to pulse_start and
                # set state to PULSE_END asap
                self.pulse_end = self.pulse_start
                self.pin_state += 2

        elif SonarTask.WAIT_FOR_PULSE_END == self.pin_states[self.pin_state]:
            if 0 == GPIO.input(self.echo_pin):
                self.pulse_end = time()
                self.pin_state += 1
        else:
            pass
        self.interrupt_lock.release()

    def run(self):
        self.interrupt_lock.acquire()
        if SonarTask.INIT_PULSE == self.pin_states[self.pin_state]:
            GPIO.output(self.trig_pin, GPIO.HIGH)
            sleep(0.00001)
            GPIO.output(self.trig_pin, GPIO.LOW)
            self.pin_state += 1
        elif SonarTask.PULSE_END == self.pin_states[self.pin_state]:
            pulse_duration = self.pulse_end - self.pulse_start
            distance = int(round(pulse_duration * 171500, 0))
            sonar_msg = SonarDataInd(distance)
            self.comm_if.send_message(sonar_msg)
            self.pin_state = 0
        self.interrupt_lock.release()


"""Channel tasks helpers"""
from django.conf import settings

from channels.spam import extract_spam_check_headers, exempt_from_spamcheck
from open_discussions.features import HOT_POST_REPAIR, if_feature_enabled

@if_feature_enabled(HOT_POST_REPAIR)
def maybe_repair_post_in_host_listing(post_obj):
    """
    Runs a task to maybe repair a post if it's missing from the hot listing

    Args:
        post_obj (channels.proxies.PostProxy): A proxied post/submission
    """
    from channels import tasks

    post = post_obj._self_post  # pylint: disable=protected-access

    tasks.maybe_repair_post_in_host_listing.apply_async(
        args=[post.channel.name, post.post_id],
        countdown=settings.OPEN_DISCUSSIONS_HOT_POST_REPAIR_DELAY,
    )

def check_post_for_spam(request, post_id):
    """
    Run a task to determine if the post is spam

    Args:
        request(): the request to create or update the post
        post_id(str): the base36 post id
    """
    from channels import tasks

    if exempt_from_spamcheck(request.user.email):
        return

    headers = extract_spam_check_headers(request)
    tasks.check_post_for_spam.apply_async(
        kwargs=dict(
            user_ip=headers.user_ip, user_agent=headers.user_agent, post_id=post_id
        ),
        countdown=15,
    )

def check_comment_for_spam(request, comment_id):
    """
    Run a task to determine if the post is spam

    Args:
        request(): the request to create or update the post
        comment_id(str): the base36 comment id
    """
    from channels import tasks

    if exempt_from_spamcheck(request.user.email):
        return

    headers = extract_spam_check_headers(request)
    tasks.check_comment_for_spam.apply_async(
        kwargs=dict(
            user_ip=headers.user_ip,
            user_agent=headers.user_agent,
            comment_id=comment_id,
        ),
        countdown=15,
    )


from gensim.corpora import Dictionary, MmCorpus
from gensim.models.coherencemodel import CoherenceModel
from gensim.models import word2vec
import matplotlib.pyplot as plt
import numpy as np

def get_coherence(aspect_num, corpus, dic):
    #######aspects as topics#########
    aspect_txt = open("./output_dir/" + "beer" + "/aspect.log")
    aspect_words = []
    for line in aspect_txt:
        words = line.split()
        if len(words) <= 5 or "Aspect" in words[0]:
            continue
        aspect_words.append([words[i] for i in range(aspect_num) if not (words[i] == "<unk>") or (words[i] == "<num>") or (words[i] == "<pad>")])
    #######creating model###########
    cm = CoherenceModel(topics=aspect_words, corpus=corpus, dictionary=dic, coherence='u_mass')

    ######compute###########
    coherence = cm.get_coherence()

    return coherence

#######creating dictionary, corpus from test data#########
test_txt = "../preprocessed_data/" + "beer" + "/train.txt"
sentences = [s for s in word2vec.LineSentence(test_txt)]
dic = Dictionary(sentences)
corpus = [dic.doc2bow(s) for s in sentences]

# texts = []
# for doc in MmCorpus(corpdir.format(50000)):
#     text = []
#     for word in doc:
#         for i in range(int(word[1])):
#             text.append(dictionary[word[0]])
#     texts.append(text)

#######creating graph#########
x = []
y = []
for i in range(1, 50, 2):
    score = get_coherence(i, corpus, dic)
    x.append(i)
    y.append(score)
    print("{} number of aspects: {}".format(i,score))

plt.xlabel('Top N Words')
plt.ylabel('Coherence Score')
plt.plot(x, y)
plt.show()


#! /usr/bin/env python
# encoding: utf-8

import sys
sys.path.append('..')
sys.path.append('mock')

import unittest
from mock import Mock
import simulator.relay

class TestPacket(unittest.TestCase):
    """Class for testing Relay."""

    def test_instantiation(self):
        """Test instantiation."""
        id = "test_id"
        stats = {}
        decoder = Mock(name="decoder_object")
        decoder.block_size = Mock(return_value=100)
        c = simulator.relay.Relay(id, stats, decoder)
        self.assertEqual(c.sender.id, id)
        self.assertEqual(c.receiver.id, id)
        self.assertEqual(c.receiver.decoder, decoder)

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


from functools import partial
from typing import Dict, Type, Tuple

import pytest
import torch

from nncf.common.tensor_statistics.statistics import TensorStatistic
from nncf.common.tensor_statistics.collectors import TensorStatisticCollectorBase, ReductionShape, \
    StatisticsNotCollectedError, OfflineTensorStatisticCollector
from nncf.torch.tensor_statistics.collectors import PTMinMaxStatisticCollector, PTMixedMinMaxStatisticCollector, \
    PTMeanMinMaxStatisticCollector, PTMedianMADStatisticCollector, PTPercentileStatisticCollector, \
    PTMeanPercentileStatisticCollector
from nncf.torch.tensor_statistics.collectors import PTNNCFCollectorTensorProcessor
from nncf.torch.tensor_statistics.statistics import PTMinMaxTensorStatistic, \
    PTMedianMADTensorStatistic, PTPercentileTensorStatistic
from nncf.torch.tensor import PTNNCFTensor

class TestCollectedStatistics:
    REF_INPUTS = [
        torch.tensor([
            [1.0, 2.0, 3.0],
            [-1.0, -2.0, -3.0],
            [4.0, 5.0, 6.0]
        ]),
        torch.tensor([
            [4.5, 2.6, 3.7],
            [-1.3, -4, -3.5],
            [4.3, 5.8, 6.1]
        ])
    ]

    @pytest.mark.parametrize(('collector', 'reduction_shapes_vs_ref_statistic'),
                             [
                                 (
                                         PTMinMaxStatisticCollector,
                                         {
                                             ((1,), (0, 1)): PTMinMaxTensorStatistic(min_values=torch.tensor([-4.0]),
                                                                                max_values=torch.tensor([6.1])),
                                             ((3, 1), (1,)): PTMinMaxTensorStatistic(
                                                 min_values=torch.tensor([[1.0], [-4.0], [4.0]]),
                                                 max_values=torch.tensor([[4.5], [4.0], [6.1]])),
                                             ((1, 3), (0,)): PTMinMaxTensorStatistic(
                                                 min_values=torch.tensor([[-1.3, -4.0, -3.5]]),
                                                 max_values=torch.tensor([[4.5, 5.8, 6.1]])),
                                             # Not supported for now:
                                             # ((3, 3), ): PTMinMaxTensorStatistic(
                                             #     min_values=torch.tensor([
                                             #         [1.0, 2.0, 3.0],
                                             #         [-1.3, -4, -3.5],
                                             #         [4.0, 5.0, 6.0]
                                             #     ]),
                                             #     max_values=torch.tensor([
                                             #         [4.5, 2.6, 3.7],
                                             #         [1.3, 4.0, 3.5],
                                             #         [4.3, 5.8, 6.1]
                                             #     ]),
                                             # ),
                                         }
                                 ),
                                 (
                                         partial(PTMeanMinMaxStatisticCollector, use_per_sample_stats=False),
                                         {
                                             ((1,), (0, 1)): PTMinMaxTensorStatistic(min_values=torch.tensor([-3.5]),
                                                                                max_values=torch.tensor([6.05])),
                                             ((3, 1), (1,)): PTMinMaxTensorStatistic(
                                                 min_values=torch.tensor([[1.8], [-3.5], [4.15]]),
                                                 max_values=torch.tensor([[3.75], [3.5], [6.05]])),
                                             ((1, 3), (0,)): PTMinMaxTensorStatistic(
                                                 min_values=torch.tensor([[-1.15, -3, -3.25]]),
                                                 max_values=torch.tensor([[4.25, 5.4, 6.05]])),
                                         }
                                 ),
                                 (
                                         partial(PTMixedMinMaxStatisticCollector,
                                                 use_per_sample_stats=False,
                                                 use_means_of_mins=False,
                                                 use_means_of_maxs=True),
                                         {
                                             ((1,), (0, 1)): PTMinMaxTensorStatistic(min_values=torch.tensor([-4.0]),
                                                                                max_values=torch.tensor([6.05])),
                                             ((3, 1), (1,)): PTMinMaxTensorStatistic(
                                                 min_values=torch.tensor([[1.0], [-4.0], [4.0]]),
                                                 max_values=torch.tensor([[3.75], [3.5], [6.05]])),
                                             ((1, 3), (0,)): PTMinMaxTensorStatistic(
                                                 min_values=torch.tensor([[-1.3, -4.0, -3.5]]),
                                                 max_values=torch.tensor([[4.25, 5.4, 6.05]])),
                                         }
                                 )
                             ])
    def test_collected_statistics_with_shape_convert(self, collector: Type[TensorStatisticCollectorBase],
                                                     reduction_shapes_vs_ref_statistic:
                                                     Dict[Tuple[ReductionShape, ReductionShape], TensorStatistic]):
        for shapes in reduction_shapes_vs_ref_statistic.keys():
            output_shape, reduction_shape = shapes
            collector_obj = collector(use_abs_max=True,
                                      reduction_shape=reduction_shape,
                                      output_shape=output_shape)
            for input_ in TestCollectedStatistics.REF_INPUTS:
                collector_obj.register_input(input_)
            test_stats = collector_obj.get_statistics()
            assert reduction_shapes_vs_ref_statistic[shapes] == test_stats

    @pytest.mark.parametrize(('collector', 'reduction_shapes_vs_ref_statistic'),
                             [
                                 (
                                         PTMedianMADStatisticCollector,
                                         {
                                             (1,): PTMedianMADTensorStatistic(median_values=torch.tensor([2.8]),
                                                                              mad_values=torch.tensor([2.6])),
                                             (3, 1): PTMedianMADTensorStatistic(
                                                 median_values=torch.tensor([[2.8], [-2.5], [5.4]]),
                                                 mad_values=torch.tensor([[0.85], [1.1], [0.65]])),
                                             (1, 3): PTMedianMADTensorStatistic(
                                                 median_values=torch.tensor([[2.5, 2.3, 3.35]]),
                                                 mad_values=torch.tensor([[1.9, 3.1, 2.7]])),
                                             # Not supported for now:
                                             # (3, 3): PTMedianMADTensorStatistic(
                                             #     median_values=torch.tensor([
                                             #         [2.75, 2.3, 3.35],
                                             #         [-1.15, -3, -3.25],
                                             #         [4.15, 5.4, 6.05]
                                             #     ]),
                                             #     mad_values=torch.tensor([
                                             #         [1.75, 0.3, 0.35],
                                             #         [0.15, 1, 0.25],
                                             #         [0.15, 0.4, 0.05]
                                             #     ]),
                                             # ),
                                         }
                                 ),
                                 (
                                         partial(PTPercentileStatisticCollector, percentiles_to_collect=[10.0]),
                                         {
                                             (1,): PTPercentileTensorStatistic(
                                                 {10.0: torch.tensor([-3.15])}),
                                             (3, 1): PTPercentileTensorStatistic(
                                                 {10.0: torch.tensor([[1.5], [-3.75], [4.15]])}),
                                             (1, 3): PTPercentileTensorStatistic(
                                                 {10.0: torch.tensor([[-1.15, -3, -3.25]])}),
                                             # Not supported for now:
                                             # (3, 3): PTPercentileTensorStatistic(
                                             #     {
                                             #         10.0: torch.tensor([
                                             #             [1.35, 2.06, 3.07],
                                             #             [-1.27, -3.8, -3.45],
                                             #             [4.03, 5.08, 6.01]
                                             #         ])
                                             #     }
                                             # ),
                                         }
                                 ),
                                 (
                                         partial(PTMeanPercentileStatisticCollector, percentiles_to_collect=[10.0]),
                                         {
                                             (1,): PTPercentileTensorStatistic(
                                                 {10.0: torch.tensor([-2.9])}),
                                             (3, 1): PTPercentileTensorStatistic(
                                                 {10.0: torch.tensor([[ 2.0100], [-3.3500], [ 4.4000]])}),
                                             (1, 3): PTPercentileTensorStatistic(
                                                 {10.0: torch.tensor([[-0.3900, -1.9400, -1.9300]])}),
                                             # Not supported for now:
                                             # (3, 3): PTPercentileTensorStatistic(
                                             #     {
                                             #         10.0: torch.tensor([
                                             #             [ 2.7500,  2.3000,  3.3500],
                                             #             [-1.1500, -3.0000, -3.2500],
                                             #             [ 4.1500,  5.4000,  6.0500]
                                             #         ])
                                             #     }
                                             # ),
                                         }
                                 ),
                             ])
    def test_collected_statistics(self, collector: Type[TensorStatisticCollectorBase],
                                  reduction_shapes_vs_ref_statistic: Dict[ReductionShape, TensorStatistic]):
        for shapes in reduction_shapes_vs_ref_statistic.keys():
            reduction_shape = shapes
            collector_obj = collector(reduction_shape=reduction_shape)
            for input_ in TestCollectedStatistics.REF_INPUTS:
                collector_obj.register_input(input_)
            test_stats = collector_obj.get_statistics()
            assert reduction_shapes_vs_ref_statistic[shapes] == test_stats

    COLLECTORS = [
        partial(PTMinMaxStatisticCollector,
                use_abs_max=False,
                output_shape=(1,)),
        partial(PTMixedMinMaxStatisticCollector,
                use_per_sample_stats=False,
                use_abs_max=False,
                use_means_of_mins=False,
                use_means_of_maxs=False,
                output_shape=(1,)),
        partial(PTMeanMinMaxStatisticCollector,
                use_per_sample_stats=False,
                use_abs_max=False,
                output_shape=(1,)),
        PTMedianMADStatisticCollector,
        partial(PTPercentileStatisticCollector, percentiles_to_collect=[10.0]),
        partial(PTMeanPercentileStatisticCollector, percentiles_to_collect=[10.0])]

    @pytest.fixture(params=COLLECTORS)
    def collector_for_interface_test(self, request):
        collector_type = request.param
        return collector_type(reduction_shape=(1,))

    def test_collected_samples(self, collector_for_interface_test: TensorStatisticCollectorBase):
        for input_ in TestCollectedStatistics.REF_INPUTS:
            collector_for_interface_test.register_input(input_)
        assert collector_for_interface_test.collected_samples() == len(TestCollectedStatistics.REF_INPUTS)

    def test_reset(self, collector_for_interface_test: TensorStatisticCollectorBase):
        for input_ in TestCollectedStatistics.REF_INPUTS:
            collector_for_interface_test.register_input(input_)
        collector_for_interface_test.reset()
        assert collector_for_interface_test.collected_samples() == 0
        with pytest.raises(StatisticsNotCollectedError):
            collector_for_interface_test.get_statistics()

    def test_enable_disable(self, collector_for_interface_test: TensorStatisticCollectorBase):
        for input_ in TestCollectedStatistics.REF_INPUTS:
            collector_for_interface_test.register_input(input_)

        collector_for_interface_test.disable()
        for input_ in TestCollectedStatistics.REF_INPUTS:
            collector_for_interface_test.register_input(input_)
        assert collector_for_interface_test.collected_samples() == len(TestCollectedStatistics.REF_INPUTS)

        collector_for_interface_test.enable()
        for input_ in TestCollectedStatistics.REF_INPUTS:
            collector_for_interface_test.register_input(input_)
        assert collector_for_interface_test.collected_samples() == 2 * len(TestCollectedStatistics.REF_INPUTS)

    OFFLINE_COLLECTORS = [
        partial(PTMixedMinMaxStatisticCollector,
                use_per_sample_stats=False,
                use_abs_max=False,
                use_means_of_mins=False,
                use_means_of_maxs=False,
                output_shape=(1,)),
        partial(PTMeanMinMaxStatisticCollector,
                use_per_sample_stats=False,
                use_abs_max=False,
                output_shape=(1,)),
        PTMedianMADStatisticCollector,
        partial(PTPercentileStatisticCollector, percentiles_to_collect=[10.0]),
        partial(PTMeanPercentileStatisticCollector, percentiles_to_collect=[10.0]),
    ]

    REF_NUM_SAMPLES = 3
    @pytest.fixture(params=OFFLINE_COLLECTORS)
    def collector_for_num_samples_test(self, request):
        collector_type = request.param
        return collector_type(reduction_shape=(1,),
                              num_samples=TestCollectedStatistics.REF_NUM_SAMPLES)

    def test_num_samples(self, collector_for_num_samples_test: OfflineTensorStatisticCollector):
        for input_ in TestCollectedStatistics.REF_INPUTS * 10:
            collector_for_num_samples_test.register_input(input_)
        assert collector_for_num_samples_test.collected_samples() == TestCollectedStatistics.REF_NUM_SAMPLES

class TestCollectorTensorProcessor:
    tensor_processor = PTNNCFCollectorTensorProcessor()

    def test_unstack(self):
        # Unstack tensor with dimensions
        tensor1 = torch.tensor([1.0])
        tensor_unstacked1 = TestCollectorTensorProcessor.tensor_processor.unstack(PTNNCFTensor(tensor1))

        # Unstack dimensionless tensor
        tensor2 = torch.tensor(1.0)
        tensor_unstacked2 = TestCollectorTensorProcessor.tensor_processor.unstack(PTNNCFTensor(tensor2))

        assert tensor_unstacked1 == tensor_unstacked2 == [PTNNCFTensor(torch.tensor(1.0))]