"""
There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

Example 1:
nums1 = [1, 3]
nums2 = [2]

The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5
"""

# ================ BS on smaller array =================
# Time: O(min(len(nums1), len(nums2)))
# Space: O(1)
# Idea: https://discuss.leetcode.com/topic/16797/very-concise-o-log-min-m-n-iterative-solution-with-detailed-explanation
"""
1. Simplify even and odd cases into one:
L/R is first one one the left/right
N        Index of L / R
1               0 / 0
2               0 / 1
3               1 / 1
4               1 / 2
5               2 / 2
6               2 / 3
7               3 / 3
8               3 / 4
(L + R)/2 = (A[(N-1)/2] + A[N/2])/2

To make L/R in odd number array has the same value, we add imaginary optitions between items:
[6 9 13 18]  ->   [# 6 # 9 # 13 # 18 #]    (N = 4)
position index     0 1 2 3 4 5  6 7  8     (N_Position = 9)

[6 9 11 13 18]->   [# 6 # 9 # 11 # 13 # 18 #]   (N = 5)
position index      0 1 2 3 4 5  6 7  8 9 10    (N_Position = 11)

As you can see, there are always exactly 2*N+1 'positions' regardless of length N.
Therefore, the middle cut should always be made on the Nth position (0-based).
Since index(L) = (N-1)/2 and index(R) = N/2 in this situation,
we can infer that index(L) = (CutPosition-1)/2, index(R) = (CutPosition)/2.

2. If we have L1 > R1, it means there are too many large numbers on the left half of A1, then we must move C1 to the left (i.e. move C2 to the right);
If L2 > R1, then there are too many large numbers on the left half of A2, and we must move C2 to the left.
Otherwise, this cut is the right one.
After we find the cut, the medium can be computed as (max(L1, L2) + min(R1, R2)) / 2;

3. The only edge case is when a cut falls on the 0th(first) or the 2Nth(last) position. For instance, if C2 = 2N2, then R2 = A2[2*N2/2] = A2[N2], which exceeds the boundary of the array. To solve this problem, we can imagine that both A1 and A2 actually have two extra elements, INT_MAX at A[-1] and INT_MAX at A[N]. These additions don't change the result, but make the implementation easier: If any L falls out of the left boundary of the array, then L = INT_MIN, and if any R falls out of the right boundary, then R = INT_MAX.
"""

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        n1, n2 = len(nums1), len(nums2)
        if n1 < n2:
            nums1, nums2 = nums2, nums1
            n1, n2 = n2, n1

        if n2 == 0:
            return (nums1[(n1-1)/2] + nums1[n1/2])/2.0

        lo, hi = 0, n2*2
        while lo <= hi:
            cut2 = (lo + hi)/2
            cut1 = n1 + n2 - cut2

            l1 = float('-inf') if cut1 == 0 else nums1[(cut1-1)/2]
            l2 = float('-inf') if cut2 == 0 else nums2[(cut2-1)/2]
            r1 = float('inf') if cut1 == n1*2 else nums1[cut1/2]
            r2 = float('inf') if cut2 == n2*2 else nums2[cut2/2]

            if l1 > r2:
                lo = cut2 + 1
            elif l2 > r1:
                hi = cut2 - 1
            else:
                return (max(l1, l2) + min(r1, r2))/2.0

        return -1


import logging
from collections import defaultdict
import flask
from flask.ext.script import Manager
from flask.ext.rq import job
from mptracker import models
from mptracker.common import ocr_url, csv_lines
from mptracker.nlp import match_text_for_mandate
from mptracker.auth import require_privilege

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

questions = flask.Blueprint('questions', __name__)

questions_manager = Manager()

@job
def ocr_question(question_id):
    question = models.Question.query.get(question_id)

    pages = ocr_url(question.pdf_url)
    question.text = '\n\n'.join(pages)

    models.db.session.add(question)
    models.db.session.commit()
    logger.info("done OCR for %s (%d pages)", question, len(pages))

@questions_manager.command
def ocr_all(number=None, force=False):
    text_row_ids = models.OcrText.all_ids_for('question')
    def has_text(question):
        return question.id in text_row_ids

    n_jobs = n_skip = n_ok = 0

    for question in models.Question.query:
        if not question.pdf_url:
            n_skip += 1
            continue
        if has_text(question) and not force:
            n_ok += 1
            continue
        ocr_question.delay(question.id)
        n_jobs += 1
        if number and n_jobs >= int(number):
            break
    logger.info("enqueued %d jobs, skipped %d, ok %d", n_jobs, n_skip, n_ok)

@job
@questions_manager.command
def analyze_question(question_id):
    question = models.Question.query.get(question_id)
    text = question.title + ' ' + question.text
    result = match_text_for_mandate(question.mandate, text)
    question.match.data = flask.json.dumps(result)
    question.match.score = len(result['top_matches'])
    models.db.session.commit()

@questions_manager.command
def analyze_all(number=None, force=False, minority_only=False):
    text_row_ids = models.OcrText.all_ids_for('question')
    def has_text(question):
        return question.id in text_row_ids

    match_row_ids = models.Match.all_ids_for('question')
    def has_match(question):
        return question.id in match_row_ids

    n_jobs = n_skip = n_ok = 0
    for question in models.Question.query:
        if not force:
            if has_match(question):
                n_ok += 1
                continue
        if not has_text(question):
            n_skip += 1
            continue
        mandate = question.mandate
        if not mandate.minority:
            county = mandate.county
            if (minority_only or
                county is None or
                county.geonames_code is None):
                n_skip += 1
                continue
        analyze_question.delay(question.id)
        n_jobs += 1
        if number and n_jobs >= int(number):
            break
    logger.info("enqueued %d jobs, skipped %d, ok %d", n_jobs, n_skip, n_ok)

@questions.route('/questions/')
def mandate_index():
    from sqlalchemy import func
    from sqlalchemy.orm import subqueryload
    question_count_for_mandate = dict(
        models.db.session
            .query(models.Question.mandate_id,
                   func.count(models.Question.mandate_id))
            .group_by(models.Question.mandate_id)
    )
    mandate_rows = (models.Mandate.query
                        .options(subqueryload(models.Mandate.county))
                        .options(subqueryload(models.Mandate.person)))
    mandates = [{
            'id': m.id,
            'person_id': m.person.id,
            'person': str(m.person),
            'county_name': m.county.name if m.county else '',
            'question_count': question_count_for_mandate.get(m.id, 0),
        } for m in mandate_rows]
    mandates.sort(key=lambda m: m['question_count'], reverse=True)
    return flask.render_template('questions/mandate_index.html', **{
        'mandates': mandates,
    })

@questions.route('/mandate/<uuid:mandate_id>/questions')
def mandate_questions(mandate_id):
    mandate = (models.Mandate.query
                     .filter_by(id=mandate_id)
                     .join(models.Mandate.person)
                     .first_or_404())
    addressee_count = defaultdict(int)
    questions = []
    for q in mandate.questions:
        questions.append({
            'id': q.id,
            'title': q.title,
            'date': q.date,
            'is_local_topic_flag': q.flags.is_local_topic,
            'score': q.match.score or 0,
            'addressee': q.addressee,
        })
        for name in q.addressee.split(';'):
            addressee_count[name.strip()] += 1

    if flask.request.args.get('format') == 'csv':
        cols = ['id', 'title', 'date', 'is_local_topic_flag',
                'score', 'addressee']
        return flask.Response(csv_lines(cols, questions),
                              mimetype='text/csv')

    addressee_top = sorted(((n, name) for name, n in addressee_count.items()),
                           reverse=True)[:5]

    def sort_key(question):
        if question['is_local_topic_flag']:
            return 11.0
        else:
            return question['score'] or 0
    questions.sort(key=sort_key, reverse=True)
    return flask.render_template('questions/mandate.html', **{
        'mandate': mandate,
        'questions': questions,
        'addressee_top': addressee_top,
    })

@questions.route('/questions/bugs')
def question_bugs():
    Question = models.Question
    questions = (Question.query
                         .join(Question.flags_row)
                            .filter(models.QuestionFlags.is_bug == True)
                         .join(Question.person))
    return flask.render_template('questions/bugs.html', **{
        'questions': questions,
    })

@questions.route('/questions/<uuid:question_id>')
def question_detail(question_id):
    question = models.Question.query.get_or_404(question_id)
    match_result = (flask.json.loads(question.match.data)
                    if question.match.data else None)

    return flask.render_template('questions/detail.html', **{
        'mandate': question.mandate,
        'person': question.mandate.person,
        'question': question,
        'match_result': match_result,
    })

@questions.route('/questions/<uuid:question_id>/save_flags', methods=['POST'])
@require_privilege
def question_save_flags(question_id):
    question = models.Question.query.get_or_404(question_id)
    for name in ['is_local_topic', 'is_bug']:
        if name in flask.request.form:
            value = flask.json.loads(flask.request.form[name])
            setattr(question.flags, name, value)
    models.db.session.commit()
    url = flask.url_for('.question_detail', question_id=question_id)
    return flask.redirect(url)


# iki kişinin maaşlarının vergi oranını iki farklı şekilde hesaplayalım. (iki yöntem de aynı işe yarar.)

# 1. yol:

#print("Ahmet'in maaşı : " , 5000 - (5000 * 0.27))
#print("Ali'nin maaşı :" , 4000 - (4000*0.27))

# 2. yol:

#maasAli = 4000
#maasAhmet = 5000
#vergiOranı = 0.27

#print("Ahmet'in maaşı : " , maasAhmet - (maasAhmet*vergiOranı))
#print("Ali'nin maaşı :" , maasAli - (maasAli * vergiOranı))

# Kullandığımız yollardan ilkinde değerleri sürekli tekrar tekrar yazmak zorunda kaldık.
# Kullandığımız ikinci yolda ise bir değişken (variable) atadık ve o değişkene bir değer verdik.
# Büyük projelerde değişken kullanılır. Bu sebepten ötürü değişken kullanmayı alışkanlık edinmek gerekir.

# Değişken tanımlama kuralları:

# 1. kural => Değişken tanımlarken sayı ile başlanmaz örneğin: 1örnek değişkeni kullanılamaz ama değişkenin sonuna sayı gelebilir yada değiken _ - gibi özel karakterlerle başlayabilir.
# 2. kural => Bir değişkeni 2 kere tanımlarsak o değişkeni güncellemiş oluruz örneğin:

variable1 = 20
print(variable1)
variable1 = 30
print(variable1)
# iki güncellemenin sonucunu da terminalde görebiliriz.
variable2 = 30
variable2 = 70
print(variable2)
# Terminalde 70 değeri yazar çünkü variable2 değişkenini 30 değerinden 70 değerine günccelledik.

# Bir değişkenin değerini arttırabiliriz örneğin:

variable3 = 10
print(variable3)
variable3 += 40          # Bu satırda variable3 değişkenini 40 arttırdık değişkenin çıktısını aldığımızda 10+40=50 yani bize 50 değerini vericek.
print(variable3)

# 3. kural => Değişken adı koyarken büyük küçük harf duyarlılığı olduğunu unutmaynız. Örneğin:

AGE = 15
age = 25

print(age , AGE)

# 4. kural türkçe kararkter kullanmamak çok önemlidir. İngiliz alfabesini kullanmaya özen gösterelim.

# Değişken tanımlama türleri tek satırda veya üstte yazdığım gibi alt alta değişken tanımlanabilir.

x = 1                        # Integer veri türüdür.
y = 2.0                      # Float veri türüdür.
name = "Çınar"               # String veri türüdür ve  çift tırnak veya tek tırnak içinde yazılır.
isSutudent = True            # Bool veri türüdür. Sadece True yada False değerini alabilir.

# Bu değişkenleri tek satırda tanımlayalım.

x, y, name, isSutudent = (1, 2.0, 'Çınar', True)

# String bir ifade ile String bir ifadeyi toplarsanız iki ifadeyi de yanyana yazmış olursunuz. Örneğin:

a = '10'
b = '20'
print(a+b)                   # Gördüğünüz gibi sonuç 1020 oldu. Bunu isim soyisim yazarken de kullanabiliriz.

firstName = 'Mahmut'
lastName = " Tuncer"         # Soyismin başına boşluk bırakmalıyız ki MahmutTuncer değil de Mahmut Tuncer olarak çıktımızı alalım.
print(firstName+lastName)


from collections import Counter
import heapq
class Solution:
    def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:
        counter1 = Counter(arr)
        counter2 = Counter(counter1.values())
        minHeap = list(counter2.items())
        heapify(minHeap)
        while  minHeap and k>=minHeap[0][0]:
            top = heapq.heappop(minHeap)
            if k>= top[0]*top[1]:
                k -= top[0]*top[1]
            else:
                heapq.heappush(minHeap,(top[0],top[1]-k//top[0]))
                k -= top[0]*(k//top[0])
        min_unique = 0
        for num_type, num_count in minHeap:
            min_unique += num_count
        return min_unique

from collections import Counter
class Solution:
    def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:
        counter1 = Counter(arr)
        counter2 = Counter(counter1.values())
        type_count = sorted(list(counter2.items()))
        num_unique = 0
        print(type_count)
        for n_count,n_unique in type_count:
            delete = min(k//n_count,n_unique)
            k -= delete*n_count
            num_unique += (n_unique- delete)
        return num_unique


from deeplabcut import create_project, analyze_videos
import os

FILE_STRING = "DLC_resnet50_vocal_foldAug7shuffle1_1030000"  # for newer DLC
# FILE_STRING = 'DeepCut_resnet50_vocal_foldAug7shuffle1_1030000'
# Only works on windows rn

# might change how we handle pathing
def new_vid(config: str, path: str):
    """
    adds new video to deeplabcut project
    :param config: the name of the path to the config.yaml file
    :param path: the path of videos or directory containing
    :return:
    """
    cfg = os.path.join(config, "config.yaml")
    if not os.path.isdir(os.path.join(config, "videos")):
        os.mkdir(os.path.join(config, "videos"))
    create_project.add_new_videos(cfg, [path])
    location = os.path.join("videos", path[path.rfind("/") + 1 :])
    test = os.path.join(config, location)
    videotype = path[path.rfind(".") :]
    print("test? " + str(test))
    print("videotype " + videotype)
    analyze_videos(cfg, [test], videotype=videotype, TFGPUinference=False, save_as_csv=True)
    return os.path.join(config, location)

def analyze(config, path, h5_dir=os.getcwd() + "/output"):
    """Analyzes new video"""
    cfg = os.path.join(config, "config.yaml")
    name = analyze_videos(cfg, [path], videotype=path[path.rfind(".") :], destfolder=h5_dir, save_as_csv=True)
    h5 = h5_dir + "/" + name + ".h5"
    return h5, name

if __name__ == "__main__":
    pass


import os
import traceback
from threading import local

from django.utils.functional import SimpleLazyObject

from django_perf_rec import pytest_plugin
from django_perf_rec.cache import AllCacheRecorder
from django_perf_rec.db import AllDBRecorder
from django_perf_rec.settings import perf_rec_settings
from django_perf_rec.utils import current_test, record_diff
from django_perf_rec.yaml import KVFile

record_current = local()

def record(*, record_name=None, path=None, capture_traceback=None):
    # Lazy since we may not need this to determine record_name or path,
    # depending on logic below
    test_details = SimpleLazyObject(current_test)

    if path is None or path.endswith("/"):
        file_name = get_perf_path(test_details.file_path)
    else:
        file_name = path

    if path is not None and path.endswith("/"):
        if not os.path.isabs(path):
            directory = os.path.join(os.path.dirname(test_details.file_path), path)
            if not os.path.exists(directory):
                os.makedirs(directory)
        else:
            directory = path

        file_name = os.path.join(directory, os.path.basename(file_name))

    if record_name is None:
        record_name = get_record_name(
            test_name=test_details.test_name,
            class_name=test_details.class_name,
            file_name=file_name,
        )

    return PerformanceRecorder(file_name, record_name, capture_traceback)

def get_perf_path(file_path):
    if file_path.endswith(".py"):
        perf_path = file_path[: -len(".py")] + ".perf.yml"
    elif file_path.endswith(".pyc"):
        perf_path = file_path[: -len(".pyc")] + ".perf.yml"
    else:
        perf_path = file_path + ".perf.yml"
    return perf_path

def get_record_name(test_name, class_name=None, file_name=""):
    if class_name:
        record_name = "{class_}.{test}".format(class_=class_name, test=test_name)
    else:
        record_name = test_name

    # Multiple calls inside the same test should end up suffixing with .2, .3 etc.
    record_spec = (file_name, record_name)
    if getattr(record_current, "record_spec", None) == record_spec:
        record_current.counter += 1
        record_name = record_name + ".{}".format(record_current.counter)
    else:
        record_current.record_spec = record_spec
        record_current.counter = 1

    return record_name

class PerformanceRecorder:
    def __init__(self, file_name, record_name, capture_traceback):
        self.file_name = file_name
        self.record_name = record_name

        self.record = []
        self.db_recorder = AllDBRecorder(self.on_op)
        self.cache_recorder = AllCacheRecorder(self.on_op)
        self.capture_traceback = capture_traceback

    def __enter__(self):
        self.db_recorder.__enter__()
        self.cache_recorder.__enter__()
        self.load_recordings()

    def __exit__(self, exc_type, exc_value, exc_traceback):
        self.cache_recorder.__exit__(exc_type, exc_value, exc_traceback)
        self.db_recorder.__exit__(exc_type, exc_value, exc_traceback)

        if exc_type is None:
            self.save_or_assert()

    def on_op(self, op):
        record = {op.name: op.query}

        if self.capture_traceback and self.capture_traceback(op):
            record["traceback"] = traceback.StackSummary.from_list(
                op.traceback
            ).format()

        self.record.append(record)

    def load_recordings(self):
        self.records_file = KVFile(self.file_name)

    def save_or_assert(self):
        orig_record = self.records_file.get(self.record_name, None)
        if perf_rec_settings.MODE == "none":
            assert (
                orig_record is not None
            ), "Original performance record does not exist for {}".format(
                self.record_name
            )

        if orig_record is not None:
            msg = "Performance record did not match for {}".format(self.record_name)
            if not pytest_plugin.in_pytest:
                msg += "\n{}".format(record_diff(orig_record, self.record))
            assert self.record == orig_record, msg

        self.records_file.set_and_save(self.record_name, self.record)

        if perf_rec_settings.MODE == "all":
            assert (
                orig_record is not None
            ), "Original performance record did not exist for {}".format(
                self.record_name
            )

class TestCaseMixin:
    """
    Adds record_performance() method to TestCase class it's mixed into
    for easy import-free use.
    """

    def record_performance(self, *, record_name=None, path=None):
        return record(record_name=record_name, path=path)


import heapq
def get_least_numbers_big_data(alist, k):
    max_heap = []
    length = len(alist)
    if not alist or k <= 0 or k > length:
        return
    k = k - 1
    for ele in alist:
        ele = -ele
        if len(max_heap) <= k:
            heapq.heappush(max_heap, ele)
        else:
            heapq.heappushpop(max_heap, ele)

    return map(lambda x:-x, max_heap)

if __name__ == "__main__":
    l = [1,1, 9, 2, 4, 7, 6, 3]
    min_k = get_least_numbers_big_data(l, 3)
    res=[]
    for i in min_k:
        res.append(i)
    print(res)


import abc
import itertools
from typing import Tuple, List

import ase.formula
from ase.build import molecule
from ase import io
import gym
import numpy as np
from ase import Atoms, Atom

from molgym.reward import InteractionReward
from molgym.spaces import ActionSpace, ObservationSpace, ActionType, ObservationType, NULL_SYMBOL
from molgym.tools import util

class AbstractMolecularEnvironment(gym.Env, abc.ABC):
    def __init__(
        self,
        reward: InteractionReward,
        observation_space: ObservationSpace,
        action_space: ActionSpace,
        bag_refills: int,
        initial_formula,
        min_atomic_distance=0.6,  # Angstrom
        max_h_distance=2.0,  # Angstrom
        min_reward=-0.6,  # Hartree
    ):
        self.reward = reward
        self.observation_space = observation_space
        self.action_space = action_space

        self.random_state = np.random.RandomState()

        self.min_atomic_distance = min_atomic_distance
        self.max_h_distance = max_h_distance
        self.min_reward = min_reward

        self.current_atoms = Atoms()
        self.current_formula = ase.formula.Formula()
        self.bag_refills = bag_refills
        self.initial_formula = initial_formula
    # Negative reward should be on the same order of magnitude as the positive ones.
    # Memory agent on QM9: mean 0.26, std 0.13, min -0.54, max 1.23 (negative reward indeed possible
    # but avoidable and probably due to PM6)

    @abc.abstractmethod
    def reset(self) -> ObservationType:
        raise NotImplementedError

    def step(self, action: ActionType) -> Tuple[ObservationType, float, bool, dict]:
        new_atom = self.action_space.to_atom(action)
        done = new_atom.symbol == NULL_SYMBOL

        if done:
            return self.observation_space.build(self.current_atoms, self.current_formula), 0.0, done, {}

        if not self._is_valid_action(current_atoms=self.current_atoms, new_atom=new_atom):
            return (
                self.observation_space.build(self.current_atoms, self.current_formula),
                self.min_reward,
                True,
                {},
            )

        reward, info = self.reward.calculate(self.current_atoms, new_atom, self.min_reward, len(self.current_formula), self.bag_refills)

        if reward < self.min_reward:
            done = True
            reward = self.min_reward

        self.current_atoms.append(new_atom)
        self.current_formula = util.remove_from_formula(self.current_formula, new_atom.symbol)

        if len(self.current_formula) == 0 and self.bag_refills > 0:
            self.current_formula = self.initial_formula[-1]
            self.bag_refills -= 1

        # Check if state is terminal
        if self._is_terminal():
            done = True

        return self.observation_space.build(self.current_atoms, self.current_formula), reward, done, info

    def _is_terminal(self) -> bool:
        return len(self.current_atoms) == self.observation_space.canvas_space.size or len(self.current_formula) == 0

    def _is_valid_action(self, current_atoms: Atoms, new_atom: Atom) -> bool:
        if self._is_too_close(current_atoms, new_atom):
            return False

        return self._all_h_covered(current_atoms, new_atom)

    def _is_too_close(self, existing_atoms: Atoms, new_atom: Atom) -> bool:
        # Check distances between new and old atoms
        for existing_atom in existing_atoms:
            if np.linalg.norm(existing_atom.position - new_atom.position) < self.min_atomic_distance:
                return True

        return False

    def _all_h_covered(self, existing_atoms: Atoms, new_atom: Atom) -> bool:
        # Ensure that H atoms are not too far away from the nearest heavy atom
        if len(existing_atoms) == 0 or new_atom.symbol != 'H':
            return True

        for existing_atom in existing_atoms:
            if existing_atom.symbol == 'H':
                continue

            distance = np.linalg.norm(existing_atom.position - new_atom.position)
            if distance < self.max_h_distance:
                return True

        return False

    def render(self, mode='human'):
        pass

    def seed(self, seed=None) -> int:
        seed = seed or np.random.randint(int(1e5))
        self.random_state = np.random.RandomState(seed)
        return seed

class MolecularEnvironment(AbstractMolecularEnvironment):
    def __init__(self, formulas: List[ase.formula.Formula], *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.formulas = formulas
        self.init_refills = kwargs['bag_refills']
        self.bag_refills = kwargs['bag_refills']
        self.formulas_cycle = itertools.cycle(formulas)
        self.reset()

    def reset(self) -> ObservationType:
        # self.current_atoms = molecule('CH3CH2OH') # Ethanol
        #self.current_atoms = molecule('F')
        #self.current_atoms.set_initial_charges([-1])
        self.current_atoms = molecule('CH3OH') # Methanol
        # self.current_atoms = molecule('H2CO')

        self.current_formula = next(self.formulas_cycle)
        self.bag_refills = self.init_refills
        return self.observation_space.build(self.current_atoms, self.current_formula)


from card import *
from hand import *
from player import *
from card import *
from dealer import *

mydealer = Dealer()

mycard1 = Card("A", "Diamonds")
mycard2 = Card("2", "Diamonds")
mycard3 = Card("3", "Hearts")
myhand = Hand()

def test_init():
    assert mydealer.__status__ == ''
    assert type(mydealer.__hand__) == Hand
    assert type(mydealer.__deck__) == Deck

def test_dealer_deals():
    assert type(mydealer.deal()) == Card
    assert mydealer.__deck__.get_length() == 51

def test_dealer_add_card():
    mydealer.add_card(mycard1)
    assert str(mydealer.get_hand()) == "['A of Diamonds']"
    mydealer.add_card(mycard2)
    assert str(mydealer.get_hand()) == "['A of Diamonds', '2 of Diamonds']"

def test_set_and_get_status():
    mydealer.set_status('H')
    assert mydealer.get_status() == 'H'
    mydealer.set_status('B')
    assert mydealer.get_status() == 'B'

def test_and_get_hand_status():
    mydealer.set_hand_status('S')
    assert mydealer.get_hand_status() == 'S'

def get_hand_value():
    mydealer.set_hand_status('S')
    assert mydealer.get_hand_value() == 16
    mydealer.set_hand_status('H')
    assert mydealer.get_hand_value() == 6


from utils.sparse import inplace_set_rows_zero
from scipy.sparse import csr_matrix
from utils.datareader import Datareader
from utils.definitions import ROOT_DIR
import numpy as np
import scipy.sparse as sps
import os, sys

mode = sys.argv[1] # online or offline

if __name__ == '__main__':

    dr = Datareader(mode=mode, only_load=True, verbose=False)

    track_to_artist_dict = dr.get_track_to_artist_dict()
    track_to_album_dict = dr.get_track_to_album_dict()

    test_pids = dr.get_test_pids()
    urm = dr.get_urm()
    popularity = np.diff(urm.tocsc().indptr)

    cluster_1_artist = list()
    cluster_2_artist = list()
    cluster_3_artist = list()
    cluster_4_artist = list()

    ## clustering the matrices
    for prog, pid in enumerate(test_pids):
        songs = urm[pid].nonzero()[1]

        if len(songs) > 0:
            artists_array = [track_to_artist_dict[song] for song in songs]

            unique_songs_l = len(np.unique(songs))
            unique_artists_l = len(np.unique(artists_array))

            tracks_div_artists = np.log2(unique_songs_l / unique_artists_l)

            if tracks_div_artists == 0:
                cluster_1_artist.append(prog)
            elif tracks_div_artists < 1:
                cluster_2_artist.append(prog)
            elif tracks_div_artists < 2:
                cluster_3_artist.append(prog)
            else:
                cluster_4_artist.append(prog)

    ## folder creation
    ar1 = ROOT_DIR+'/recommenders/script/creative/'+mode+'_npz/npz_ar1/'
    ar2 = ROOT_DIR+'/recommenders/script/creative/'+mode+'_npz/npz_ar2/'
    ar3 = ROOT_DIR+'/recommenders/script/creative/'+mode+'_npz/npz_ar3/'
    ar4 = ROOT_DIR+'/recommenders/script/creative/'+mode+'_npz/npz_ar4/'

    folders = [ar1,ar2,ar3,ar4]

    for folder in folders:
        if not os.path.exists(folder):
            os.makedirs(folder)

    directory_npz= ROOT_DIR+'/recommenders/script/creative/'+mode+'_npz/'

    filenames = list(
        map(lambda x: directory_npz + x, list(filter(lambda x: mode in x, os.listdir(directory_npz)))))

    ## selecting lines for each cluster
    all_lines = np.array([x for x in range(10000)])

    cluster_1_artist = np.array(cluster_1_artist).ravel()
    cluster_2_artist = np.array(cluster_2_artist).ravel()
    cluster_3_artist = np.array(cluster_3_artist).ravel()
    cluster_4_artist = np.array(cluster_4_artist).ravel()

    cluster_1_artist_skip_lines = np.setdiff1d(all_lines, cluster_1_artist)
    cluster_2_artist_skip_lines = np.setdiff1d(all_lines, cluster_2_artist)
    cluster_3_artist_skip_lines = np.setdiff1d(all_lines, cluster_3_artist)
    cluster_4_artist_skip_lines = np.setdiff1d(all_lines, cluster_4_artist)

    ## writing the clustered matrices

    for path_eurm in filenames:

        eurm = sps.load_npz(path_eurm)
        print(path_eurm)

        eurm_cluster_1_art = csr_matrix(eurm.copy())
        inplace_set_rows_zero(eurm_cluster_1_art, cluster_1_artist_skip_lines)
        sps.save_npz(ar1 + path_eurm.split('/')[-1], eurm_cluster_1_art.tocsr())

        eurm_cluster_2_art = csr_matrix(eurm.copy())
        inplace_set_rows_zero(eurm_cluster_2_art, cluster_2_artist_skip_lines)
        sps.save_npz(ar2 + path_eurm.split('/')[-1], eurm_cluster_2_art.tocsr())

        eurm_cluster_3_art = csr_matrix(eurm.copy())
        inplace_set_rows_zero(eurm_cluster_3_art, cluster_3_artist_skip_lines)
        sps.save_npz(ar3 + path_eurm.split('/')[-1], eurm_cluster_3_art.tocsr())

        eurm_cluster_4_art = csr_matrix(eurm.copy())
        inplace_set_rows_zero(eurm_cluster_4_art, cluster_4_artist_skip_lines)
        sps.save_npz(ar4 + path_eurm.split('/')[-1], eurm_cluster_4_art.tocsr())


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

import json
import uuid

from TM1py.Exceptions import TM1pyException
from TM1py.Objects import Process
from TM1py.Services import ObjectService

class ProcessService(ObjectService):
    """ Service to handle Object Updates for TI Processes

    """
    def __init__(self, rest):
        super().__init__(rest)

    def get(self, name_process):
        """ Get a process from TM1 Server

        :param name_process:
        :return: Instance of the TM1py.Process
        """
        request = "/api/v1/Processes('{}')?$select=*,UIData,VariablesUIData," \
                  "DataSource/dataSourceNameForServer," \
                  "DataSource/dataSourceNameForClient," \
                  "DataSource/asciiDecimalSeparator," \
                  "DataSource/asciiDelimiterChar," \
                  "DataSource/asciiDelimiterType," \
                  "DataSource/asciiHeaderRecords," \
                  "DataSource/asciiQuoteCharacter," \
                  "DataSource/asciiThousandSeparator," \
                  "DataSource/view," \
                  "DataSource/query," \
                  "DataSource/userName," \
                  "DataSource/password," \
                  "DataSource/usesUnicode," \
                  "DataSource/subset".format(name_process)
        response = self._rest.GET(request, "")
        return Process.from_dict(response.json())

    def get_all(self):
        """ Get a processes from TM1 Server

        :return: List, instances of the TM1py.Process
        """
        request = "/api/v1/Processes?$select=*,UIData,VariablesUIData," \
                  "DataSource/dataSourceNameForServer," \
                  "DataSource/dataSourceNameForClient," \
                  "DataSource/asciiDecimalSeparator," \
                  "DataSource/asciiDelimiterChar," \
                  "DataSource/asciiDelimiterType," \
                  "DataSource/asciiHeaderRecords," \
                  "DataSource/asciiQuoteCharacter," \
                  "DataSource/asciiThousandSeparator," \
                  "DataSource/view," \
                  "DataSource/query," \
                  "DataSource/userName," \
                  "DataSource/password," \
                  "DataSource/usesUnicode," \
                  "DataSource/subset"
        response = self._rest.GET(request, "")
        response_as_dict = response.json()
        return [Process.from_dict(p) for p in response_as_dict['value']]

    # TODO Redesign required!
    def get_all_process_names_filtered(self):
        """ Get List with all process names from TM1 Server.
            Does not return:
                - system process
                - Processes that have Subset as Datasource

        :Returns:
            List of Strings
        """
        response = self._rest.GET("/api/v1/Processes?$select=Name&$filter=DataSource/Type ne 'TM1DimensionSubset'"
                                  " and  not startswith(Name,'}')", "")
        processes = list(process['Name'] for process in response.json()['value'])
        return processes

    def get_all_names(self):
        """ Get List with all process names from TM1 Server

        :Returns:
            List of Strings
        """
        response = self._rest.GET('/api/v1/Processes?$select=Name', '')
        processes = list(process['Name'] for process in response.json()['value'])
        return processes

    def update(self, process):
        """ Update an existing Process on TM1 Server

        :param process: Instance of TM1py.Process class
        :return: Response
        """
        request = "/api/v1/Processes('" + process.name + "')"
        # Adjust process body if TM1 version is lower than 11 due to change in Process Parameters structure
        # https://www.ibm.com/developerworks/community/forums/html/topic?id=9188d139-8905-4895-9229-eaaf0e7fa683
        if int(self.version[0:2]) < 11:
            process.drop_parameter_types()
        response = self._rest.PATCH(request, process.body)
        return response

    def create(self, process):
        """ Create a new process on TM1 Server

        :param process: Instance of TM1py.Process class
        :return: Response
        """
        request = "/api/v1/Processes"
        # Adjust process body if TM1 version is lower than 11 due to change in Process Parameters structure
        # https://www.ibm.com/developerworks/community/forums/html/topic?id=9188d139-8905-4895-9229-eaaf0e7fa683
        if int(self.version[0:2]) < 11:
            process.drop_parameter_types()
        response = self._rest.POST(request, process.body)
        return response

    def delete(self, name):
        """ Delete a process in TM1

        :param name:
        :return: Response
        """
        request = "/api/v1/Processes('{}')".format(name)
        response = self._rest.DELETE(request)
        return response

    def exists(self, name):
        """ Check if Process exists.

        :param name:
        :return:
        """
        request = "/api/v1/Processes('{}')".format(name)
        return self._exists(request)

    def compile(self, name):
        """ Compile a Process. Return List of Syntax errors.

        :param name:
        :return:
        """
        request = "/api/v1/Processes('{}')/tm1.Compile".format(name)
        response = self._rest.POST(request, '')
        syntax_errors = response.json()["value"]
        return syntax_errors

    def execute(self, process_name, parameters=None, **kwargs):
        """ Ask TM1 Server to execute a process. Call with parameter names as keyword arguments:
        tm1.processes.execute("Bedrock.Server.Wait", pLegalEntity="UK01")

        :param process_name:
        :param parameters: Deprecated! dictionary, for instance {"Parameters": [ { "Name": "pLegalEntity", "Value": "UK01" }] }
        :return:
        """
        request = "/api/v1/Processes('{}')/tm1.Execute".format(process_name)
        if not parameters:
            if kwargs:
                parameters = {"Parameters": []}
                for parameter_name, parameter_value in kwargs.items():
                    parameters["Parameters"].append({"Name": parameter_name, "Value": parameter_value})
            else:
                parameters = {}
        return self._rest.POST(request=request, data=json.dumps(parameters, ensure_ascii=False))

    def execute_with_return(self, process_name, **kwargs):
        """ Ask TM1 Server to execute a process.
        pass process parameters as keyword arguments to this function. E.g:

        self.tm1.processes.execute_with_return(
            process_name="Bedrock.Server.Wait",
            pWaitSec=2)

        :param process_name: name of the TI process
        :param kwargs: names of process parameters
        :return: success (boolean), status (String), error_log_file (String)
        """
        request = "/api/v1/Processes('{}')/tm1.ExecuteWithReturn?$expand=*".format(process_name)
        parameters = dict()
        if kwargs:
            parameters = {"Parameters": []}
            for parameter_name, parameter_value in kwargs.items():
                parameters["Parameters"].append({"Name": parameter_name, "Value": parameter_value})
        response = self._rest.POST(
            request=request,
            data=json.dumps(parameters, ensure_ascii=False))
        execution_summary = response.json()
        success = execution_summary["ProcessExecuteStatusCode"] == "CompletedSuccessfully"
        status = execution_summary["ProcessExecuteStatusCode"]
        error_log_file = None if execution_summary["ErrorLogFile"] is None else execution_summary["ErrorLogFile"]["Filename"]
        return success, status, error_log_file

    def execute_ti_code(self, lines_prolog, lines_epilog=None):
        """ Execute lines of code on the TM1 Server

            :param lines_prolog: list - where each element is a valid statement of TI code.
            :param lines_epilog: list - where each element is a valid statement of TI code.
        """
        process_name = '}' + 'TM1py' + str(uuid.uuid4())
        p = Process(name=process_name,
                    prolog_procedure=Process.auto_generated_string + '\r\n'.join(lines_prolog),
                    epilog_procedure=Process.auto_generated_string + '\r\n'.join(lines_epilog) if lines_epilog else '')
        self.create(p)
        try:
            self.execute(process_name)
            pass
        except TM1pyException as e:
            raise e
        finally:
            self.delete(process_name)

    def get_error_log_file_content(self, file_name):
        """ Get content of error log file (e.g. TM1ProcessError_20180926213819_65708356_979b248b-232e622c6.log)

        :param file_name: name of the error log file in the TM1 log directory
        :return: String, content of the file
        """
        request = "/api/v1/ErrorLogFiles('{file_name}')/Content".format(file_name=file_name)
        response = self._rest.GET(request=request)
        return response.text

    def get_processerrorlogs(self, process_name):
        """ Get all ProcessErrorLog entries for a process

        :param process_name: name of the process
        :return: list - Collection of ProcessErrorLogs
        """
        request = "/api/v1/Processes('{}')/ErrorLogs".format(process_name)
        response = self._rest.GET(request=request)
        return response.json()['value']

    def get_last_message_from_processerrorlog(self, process_name):
        """ Get the latest ProcessErrorLog from a process entity

            :param process_name: name of the process
            :return: String - the errorlog, e.g.: "Fehler: Prolog Prozedurzeile (9): Zeichenfolge "US772131
            kann nicht in eine reelle Zahl umgewandelt werden."
        """
        logs_as_list = self.get_processerrorlogs(process_name)
        if len(logs_as_list) > 0:
            timestamp = logs_as_list[-1]['Timestamp']
            request = "/api/v1/Processes('{}')/ErrorLogs('{}')/Content".format(process_name, timestamp)
            # response is plain text - due to entity type Edm.Stream
            response = self._rest.GET(request=request)
            return response


"""

Question:
    Define a class, which have a class parameter and have a same instance parameter.

Hints:
    Define a instance parameter, need add it in __init__ method
    You can init a object with construct parameter or set the value later

"""

class Person:

    name = "Person"

    def __init__(self, name = None):
        self.name = name

john = Person("John")
print("Name of %s is %s" % (Person.name, john.name))

jane = Person()
jane.name = "Jane"
print("Name of %s is %s" % (Person.name, jane.name))


from app.core.exceptions.not_mounted import NotMountedException

class MainWindowControllerProvider:
    def __init__(
        self,
        view_reference: object,
        menubar_controller,
        toolbar_controller,
        central_widget_controller,
        statusbar_controller,
    ):
        self.view = view_reference
        self.__add_menubar(menubar_controller)
        self.__add_toolbar(toolbar_controller)
        self.__add_central_widget(central_widget_controller)
        self.__add_statusbar(statusbar_controller)

    """
    add_menubar
    @desc:
        Adds a menubar inside MainWindowContller's view
    @params:
        menubar_controller - A instance of MenuBarController,
    @return: MenuBar - Added menubar instance
    """

    def __add_menubar(self, menubar_controller: object):
        self.view.setMenuBar(menubar_controller.get_view())
        return menubar_controller.get_view()

    """
    add_tool_bar
    @desc:
        Adds a toolbar inside MainWindowController's view
    @return: Toolbar - added toolbar
    """

    def __add_toolbar(self, toolbar_controller: object):
        self.view.addToolBar(toolbar_controller.get_view())
        return toolbar_controller.get_view()

    """
    add_central_widget
    @desc:
        Adds central widget to the view
    @params:
        central_widget_controller - An instance of central widget controller,
    @return: CentralWidgetController - added controller
    """

    def __add_central_widget(self, central_widget_controller):
        self.view.setCentralWidget(central_widget_controller.view())
        return central_widget_controller.view()

    """
    add_statusbar
    @desc:
        Adds a statusbar inside MainWindowController's view
    @return: StatusBar - Added statusbar
    """

    def __add_statusbar(self, statusbar_controller: object):
        self.view.setStatusBar(statusbar_controller.get_view())
        return statusbar_controller.get_view()


import pickle
from kb import KB , Profession
from term_freq import create_term_freq
from UtilityFuncts import qid

## create_term_freq()

file_to_read = open("term_freq.pickle", "rb")

loaded_dictionary = pickle.load(file_to_read)

## Choose the 10 term
throne = "throne"
tyrion = "tyrion"
stark = "stark"
robert = "robert"
arya = "arya"
cersei = "cersei"
rob  = "rob"
emilia  = "emilia"
melisandre = "melisandre"
jon = "jon"
top_term = [throne, tyrion, stark, robert , arya , cersei , rob , emilia , melisandre , jon ]

## add throne
kb = KB(Entities= dict())

## add throne and
freq = loaded_dictionary["throne"]
val = qid("throne")
relationship = {qid("emilia"):" She wants the throne"}
kb.add_entity( name = "throne" , freq = freq , qid = val , relationship = relationship )

## add tyrion
freq = loaded_dictionary["tyrion"]
val = qid("tyrion")
relationship = {qid("cersia"):" younger brother of Cerseia"}
kb.add_entity( name = "tyrion" , freq = freq , qid = val , relationship = relationship )

## stark
freq = loaded_dictionary["stark"]
val = qid("stark")
kb.add_entity( name = "stark" , freq = freq , qid = val , relationship = None )
kb.add_profession(val , Profession.Knight)

## robert
freq = loaded_dictionary["stark"]
val = qid("stark")
relationship = {qid("Lord Steffon Baratheron"):" oldest son and heir of Lord Steffon Baratheon"}
kb.add_entity( name = "stark" , freq = freq , qid = val , relationship = relationship )
kb.add_profession(val , Profession.Lord)

## arya
freq = loaded_dictionary["arya"]
val = qid("arya")
kb.add_entity( name = "arya" , freq = freq , qid = val , relationship = None )

## cersei
freq = loaded_dictionary["cersei"]
val = qid("cersei")
kb.add_entity( name = "cersei" , freq = freq , qid = val , relationship = None )

for x in range( 5, len(top_term)):
    freq = loaded_dictionary[top_term[x]]
    val = qid(top_term[x])
    kb.add_entity( name = top_term[x] , freq = freq , qid = val , relationship = None )

## add rob
kb.add_realtionship( qid("rob") , {qid("Lord Eddard Stark of Winterfell") : "The eldest sone of Eddard Stark of Winterfell"})

## emilia
kb.add_realtionship(qid("emilia"), {qid("Targaryen"):"She is a Targaryen"})

## melisandre
kb.add_realtionship(qid( "melisandre"), {qid("melisandre") : "She is hte Red Priestress"})
kb.add_profession(qid("melisandre") , Profession.Priestress)

## jon
kb.add_realtionship( qid( "jon") , { qid("lyanna") : "He is the sone of Lyanna Stark " })

kb.save_entities()

file_to_read = open("Entities.pickle", "rb")

loaded_dictionary = pickle.load(file_to_read)

print(loaded_dictionary)

## What is stark profession
print("What is Start profession? ")
print( " Stark Profession is "+kb.determine_profession(qid("stark")) )

## How many profession are the in game throne
print("How many professionals are in the game of throne")
print( "There is "+ str(kb.number_of_profession()) + " profession in game of throne")

## how many time did jon appear in the movie
print( "How many time did jon appear in the game throne")
print( "Jon appear "+ str(kb.freq(qid("jon"))) +" times in game of throne")


from src.geometry import GeometryGraph, Stringer, Edge, SparIdealization
from src.sections import SectionGeometry, Section
from src.reaction_forces import ReactionForces
from src.distributions import Distributions
from src.aileron import Aileron, forward_euler
from src.simulation_constraints import AileronConstraints, MaterialProperties
from src.post_processing import plot_deflections, plot_twist, plot_normal_stresses, \
    plot_shear_stress, verification_normal_stresses, verification_shear_stresses, \
    verification_twist, verification_von_mises, verification_y_deflection, verification_z_deflection
from src.analytical_distributions import shearflowtotal, normalstressinX, torsionaroundX, \
    vanMisesstress, deflectionaboutY, deflectionaboutZ
import matplotlib.pyplot as plt
import numpy as np

def run():
    area_stringer = 3.6 * 10 ** -5
    node0 = Stringer([0.3396, 0.0161], 0, area_stringer)
    node14 = Stringer([0.3396, -0.0161], 14, area_stringer)
    node1 = Stringer([0.2547, 0.0322], 1, area_stringer)
    node13 = Stringer([0.2547, -0.0322], 13, area_stringer)
    node2 = Stringer([0.1698, 0.0483], 2, area_stringer)
    node12 = Stringer([0.1698, -0.0483], 12, area_stringer)
    node3 = Stringer([0.0849, 0.0644], 3, area_stringer)
    node11 = Stringer([0.0849, -0.0644], 11, area_stringer)
    node5 = Stringer([-0.0569, 0.0569], 5, area_stringer)
    node7 = Stringer([-0.0569, -0.0569], 7, area_stringer)
    node6 = Stringer([-0.0805, 0], 6, area_stringer)
    node4 = SparIdealization([0, 0.0805], 4)
    node8 = SparIdealization([0, -0.0805], 8)
    node9 = SparIdealization([0, 0.04025], 9)
    node10 = SparIdealization([0, -0.04025], 10)

    node15 = Stringer([0.4245, 0], 15, 0)

    skin_thickness = 1.1 * 10 ** -3
    spar_thickness = 2.4 * 10 ** -3
    edge_01 = Edge(node0, node1, skin_thickness)
    edge_12 = Edge(node1, node2, skin_thickness)
    edge_23 = Edge(node2, node3, skin_thickness)
    edge_34 = Edge(node3, node4, skin_thickness)
    edge_45 = Edge(node4, node5, skin_thickness, 0.06322)
    edge_56 = Edge(node5, node6, skin_thickness, 0.06322)
    edge_67 = Edge(node6, node7, skin_thickness, 0.06322)
    edge_78 = Edge(node7, node8, skin_thickness, 0.06322)
    edge_49 = Edge(node4, node10, spar_thickness, 0.053666)
    edge_910 = Edge(node9, node10, spar_thickness, 0.05366)
    edge_108 = Edge(node10, node8, spar_thickness, 0.05366)
    edge_811 = Edge(node8, node11, skin_thickness)
    edge_1112 = Edge(node11, node12, skin_thickness)
    edge_1213 = Edge(node12, node13, skin_thickness)
    edge_1314 = Edge(node13, node14, skin_thickness)
    # edge_140 = Edge(node14, node0, skin_thickness)

    edge_1415 = Edge(node14, node15, skin_thickness)
    edge_150 = Edge(node15, node0, skin_thickness)

    nodes = [node0, node1, node2, node3, node4, node5, node6, node7, node8, node9, node10, node11,
             node12, node13, node14, node15]
    cell_0 = [edge_01, edge_12, edge_23, edge_34, edge_49, edge_910, edge_108, edge_811, edge_1112,
              edge_1213, edge_1314, edge_1415, edge_150]
    cell_1 = [edge_45, edge_56, edge_67, edge_78, edge_108.reverse(), edge_910.reverse(),
              edge_49.reverse()]

    graph = GeometryGraph(nodes)
    graph.add_cycles(cell_0)
    graph.add_cycles(cell_1)
    graph.areas_cycles = [0.03381, 5.0895 * 10 ** -3]
    section_geometry_reference = SectionGeometry(graph, 0, 0)
    section_geometry = SectionGeometry(graph, np.pi / 6, [0, 0])
    material = MaterialProperties(73.1 * 10 ** 9, 28. * 10 ** 9)
    constraints = AileronConstraints(material)
    aileron = Aileron(0.505, 0.161, 1.611, 150, section_geometry, material,

                           constraints)
    # plot_aileron_geometry(aileron)
    reactions = ReactionForces(constraints, section_geometry)
    distributions = Distributions(reactions)
    domain = np.linspace(0, aileron.span, aileron.num_sections)

    aileron.simulate(forward_euler,
                     (distributions.shear_z(), distributions.shear_y()), (
                          distributions.moment_z(), distributions.moment_y(),
                          distributions.torque()))

    num_von_mises_8 = aileron.get_von_mises_stress(8)
    idx_max_von_mises = np.argmax(num_von_mises_8)
    print(domain[idx_max_von_mises], aileron.sections[idx_max_von_mises].geometry.booms_angled[
        8].position)

    # verification plots
    ana_y_deflections = [deflectionaboutZ(x) for x in domain]
    num_y_deflections = aileron.deflections[1]

    ana_z_deflections = [deflectionaboutY(x) for x in domain]
    num_z_deflections = aileron.deflections[0]

    ana_shear_stress = [-shearflowtotal(x, -aileron.max_thickness/2, zbar)[1] for x in domain]
    num_shear_stress = [section.shear_stress[4, 5] for section in aileron.sections]

    ana_normal_stress = [normalstressinX(x, -aileron.max_thickness/2, zbar) for x in domain]
    num_normal_stress = [section.normal_stress[8] for section in aileron.sections]

    ana_twist = [torsionaroundX(x)[1] for x in domain]
    num_twist = aileron.twist*180/np.pi

    ana_von_mises = [vanMisesstress(x, -aileron.max_thickness/2, 0) for x in domain]
    num_von_mises = aileron.get_von_mises_stress(8)

    verification_normal_stresses(domain, num_normal_stress, ana_normal_stress)
    verification_shear_stresses(domain, num_shear_stress, ana_shear_stress)
    verification_twist(domain, num_twist, ana_twist)
    verification_von_mises(domain, num_von_mises, ana_von_mises)
    verification_y_deflection(domain, num_y_deflections, ana_y_deflections)
    verification_z_deflection(domain, num_z_deflections, ana_z_deflections)

if __name__ == '__main__':
    # run_simplified_aileron()
    run()


import numpy as np
import cv2
p=0.5
img_path="../../img/seg1.jpg"
img = cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2GRAY)
hist = cv2.calcHist([img],[0],None,[256],[0,256])
t=256*p
for r in range(img.shape[0]):
    for c in range(img.shape[1]):
        if img[r][c] > t:
            img[r][c] = 0
        else:
            img[r][c] = 255
cv2.imwrite("./result.jpg",img)


#!/usr/bin/env python3
import rospy
import math

from geometry_msgs.msg import Twist, Vector3
from sensor_msgs.msg import LaserScan
from visualization_msgs.msg import Marker

class Avoid_Obstacles_Node(object):
    """
    Use potential fields to move forward while avoiding obstacles.
    Specifically, this node uses the LaserScan input to compute the total
    sum of repelling forces associated with objects in the path of the robot
    and then uses proportional control to adjust the linear velocity and
    steering parameters of the robot.
    """
    def __init__(self):
        """
        Initialize ROS, proportional control, and potential fields parameters.
        """
        # ROS Parameters.
        rospy.init_node('Avoid_Obstacles')
        self.r = rospy.Rate(10)
        self.scan_sub = rospy.Subscriber('/scan', LaserScan, self.analyzeScan)
        self.vel_pub = rospy.Publisher('/cmd_vel', Twist, queue_size=10)

        # Controller Parameters.
        self.speed = 0.2
        self.next_move_msg = Twist(linear=Vector3(x=self.speed), angular=Vector3(z=0))
        self.kp_distance = 0.3 # Proportional constant for linear speed.
        self.kp_angle = 0.5 # Proportional constant for steering.

        # Potential Fields Parameters.
        self.force_threshold = 1 # Cutoff for pos vs. neg force.
        self.potential_offset = 0.1 # Weight for each object.

    def analyzeScan(self, data):
        """
        Use potential fields to characterize obstacles and update the robot's
        next move to avoid the obstacles and continue moving forward. Acts as
        the callback function for the LaserScan subscriber.

        Args:
        data: Incoming LaserScan messages.

        Returns:
        Void. Updates self.next_move_msg with new values based on scan.
        """
        # Cumulative sums of forces.
        total_x_value= 0
        total_y_value = 0

        for scan_angle, value in enumerate(data.ranges):
            if (value < self.force_threshold) and (value != 0.0):
                x = value*math.cos(math.radians(scan_angle))
                y = value*math.sin(math.radians(scan_angle))
                distance = math.sqrt(math.pow(x,2) + math.pow(y,2))
                # Adjust angle if necessary.
                if distance < 1:
                    robot_angle = math.atan2(y, x)
                    # Get "other side" of distance by subtracting from 1.
                    total_x_value -= self.potential_offset*(1 - distance)*math.cos(robot_angle)
                    total_y_value -= self.potential_offset*(1 - distance)*math.sin(robot_angle)
        # Positive force for foward motion.
        total_x_value += self.force_threshold

        # Find next move messages, offset by proportional constant.
        self.next_move_msg.linear.x = math.sqrt(math.pow(total_x_value,2) + math.pow(total_y_value,2))*self.kp_distance
        self.next_move_msg.angular.z = math.atan2(total_y_value,total_x_value)*self.kp_angle

    def run(self):
        """
        Run the potential fields obstacle avoidance algorithm by publishing the
        next_move_msg which is constantly updated by the callback function
        Avoid_Obstacles_Node.analyzeScan.
        """
        while not rospy.is_shutdown():
            self.vel_pub.publish(self.next_move_msg)
            self.r.sleep()

if __name__ == '__main__':
    avoid_obstacles = Avoid_Obstacles_Node()
    avoid_obstacles.run()


import os
import csv
import numpy as np
import sys
import re

sys.path.append('..')

from utils.data_manager import DataManager
from utils.system_utils import ensure_current_directory
from models.entities.Song import Song
from models.enums.Genre import Genre

def save_dataset_text(song_entries, embeddings_folder_path, filename):
    embeddings_filename = os.path.join(embeddings_folder_path, filename)
    with open(embeddings_filename, 'w', encoding='utf8') as embeddings_file:
        # for _, song_entries in dataset.items():
        for song_entry in song_entries:
            embeddings_file.write(f'{song_entry.lyrics}\n')

ensure_current_directory()
main_path = os.path.join('local_data', 'data')

dataset_folder_path = os.path.join(main_path, '380000-lyrics-from-metrolyrics')
if not os.path.exists(dataset_folder_path):
    raise Exception('Dataset folder does not exist')

dataset_file_path = os.path.join(dataset_folder_path, 'lyrics.csv')
if not os.path.exists(dataset_file_path):
    raise Exception('Dataset file does not exist')

with open(dataset_file_path, 'r', encoding="utf8") as dataset_file:
    next(dataset_file)  # skip the first line - headers
    dataset_reader = csv.reader(dataset_file, delimiter=',')

    classes_to_skip = ['Other', 'Not Available']

    song_entries_by_genre = {}

    lines_counter = 0

    for _, row in enumerate(dataset_reader):
        if row[4] in classes_to_skip:
            continue

        # Cut off songs which have lyrics with less than 30 characters
        if len(row[5]) < 100:
            continue

        if not any(c.isalpha() for c in row[5]):
            continue

        song_genre = Genre.from_str(row[4])

        # if the song genre is None, it means it's not supported, so we skip this song
        if not song_genre:
            continue

        song_entry = Song(song_genre, row[5])

        if row[4] not in song_entries_by_genre.keys():
            song_entries_by_genre[row[4]] = [song_entry]
        else:
            song_entries_by_genre[row[4]].append(song_entry)

genres = list(song_entries_by_genre.keys())
songs_limit = 13000
for genre in genres:
    song_entries_by_genre[genre] = song_entries_by_genre[genre][:songs_limit]

train_data, validation_data, test_data = {}, {}, {}

embeddings_folder_path = os.path.join(main_path, 'embeddings')
if not os.path.exists(embeddings_folder_path):
    os.mkdir(embeddings_folder_path)

for genre, song_entries in song_entries_by_genre.items():
    # split data into train, validation and test sets
    train_data[genre] = song_entries[:int(len(song_entries)*0.7)]
    validation_data[genre] = song_entries[int(len(song_entries)*0.7):int(len(song_entries)*0.8)]
    test_data[genre] = song_entries[int(len(song_entries)*0.8):]

    # # print statistics
    min_length = min([len(song_entry.lyrics) for song_entry in song_entries])
    max_length = max([len(song_entry.lyrics) for song_entry in song_entries])
    avg_length = np.mean([len(song_entry.lyrics) for song_entry in song_entries])
    avg_number_of_unique_words = np.mean([song_entry.number_of_unique_words for song_entry in song_entries])
    avg_n_words = np.mean([song_entry.number_of_words for song_entry in song_entries])
    print(f'{genre} - min: {min_length} | n_words: {avg_n_words} | unique_words: {avg_number_of_unique_words} | max: {max_length} | mean: {avg_length} | all: {len(song_entries)} | train: {len(train_data[genre])} | validation: {len(validation_data[genre])} | test: {len(test_data[genre])}')

train_song_entries = sorted([item for value in train_data.values() for item in value], key=lambda song: len(song.lyrics))
validation_song_entries = sorted([item for value in validation_data.values() for item in value], key=lambda song: len(song.lyrics))
test_song_entries = sorted([item for value in test_data.values() for item in value], key=lambda song: len(song.lyrics))

n_lines_count = []
n_words_count = []
n_chars_count = []

lines_counter = 0
for song in train_song_entries:
    song.start_index = lines_counter
    lines_counter += song.number_of_lines
    n_lines_count.append(song.number_of_lines)
    n_words_count.append(song.number_of_words)
    n_chars_count.append(song.number_of_chars)

lines_counter = 0
for song in validation_song_entries:
    song.start_index = lines_counter
    lines_counter += song.number_of_lines
    n_lines_count.append(song.number_of_lines)
    n_words_count.append(song.number_of_words)
    n_chars_count.append(song.number_of_chars)

lines_counter = 0
for song in test_song_entries:
    song.start_index = lines_counter
    lines_counter += song.number_of_lines
    n_lines_count.append(song.number_of_lines)
    n_words_count.append(song.number_of_words)
    n_chars_count.append(song.number_of_chars)

n_lines_count = np.asarray(n_lines_count)
n_words_count = np.asarray(n_words_count)
n_chars_count = np.asarray(n_chars_count)

print('Average number of lines ', n_lines_count.mean())
print('Average number of words ', n_words_count.mean())
print('Average number of chars ', n_chars_count.mean())

data_manager = DataManager(main_path)
data_manager.save_python_obj(train_song_entries, 'song_lyrics.train')
data_manager.save_python_obj(validation_song_entries, 'song_lyrics.validation')
data_manager.save_python_obj(test_song_entries, 'song_lyrics.test')

save_dataset_text(train_song_entries, embeddings_folder_path, 'embeddings.train.txt')
save_dataset_text(validation_song_entries, embeddings_folder_path, 'embeddings.validation.txt')
save_dataset_text(test_song_entries, embeddings_folder_path, 'embeddings.test.txt')


"""
Module for construction of Radiative Decays Stripping Selections and StrippingLines.
Provides functions to build Bc, D0, Ds1 selections.
Provides class Bc2Ds1GammaConf, which constructs the Selections and
StrippingLines given a configuration dictionary.
Exported selection makers: 'makePhoton', 'makeD0', 'makeDs1', 'makeBc2Ds1Gamma',

"""

__author__ = ['Marco Pappagallo']
__date__ = '02/07/2014'
__version__ = '$Revision: 1.0 $'

__all__ = ('Bc2Ds1GammaConf',
           'makePhoton',
           'makeD0',
           'makeDs1',
           'makeDs1WS',
           'makeBc2Ds1Gamma',
           'default_config')

from Gaudi.Configuration import *
from GaudiConfUtils.ConfigurableGenerators import FilterDesktop, CombineParticles
from PhysSelPython.Wrappers import Selection, DataOnDemand
from StrippingConf.StrippingLine import StrippingLine
from StrippingUtils.Utils import LineBuilder

#default_name = 'Bc2Ds1Gamma'
default_config = {
    'NAME'              : 'Bc2Ds1Gamma',
    'BUILDERTYPE'       : 'Bc2Ds1GammaConf',
    'CONFIG'    : {
                  #'TrIPchi2'            : 4.        # Dimensionless Already implemented in the particle lists
#                   'BcMassWin'           : 1500.     # MeV
                   'MinBcMass'           : 4800.     # MeV
                  ,'MaxBcMass'           : 7500.     # MeV
                  ,'BcPVIPchi2'          : 16.       # Dimensionless
                  ,'photonPT'            : 1500.     # MeV
                  ,'KaonProbNN'          : 0.1       # Dimensionless
                  ,'pionProbNN'          : 0.1       # Dimensionless
                  ,'TrGhostProb'         : 0.5       # Dimensionless
                  ,'Ds1DeltaMassWin'     : 650       # MeV
                  ,'MaxDs1VertChi2DOF'   : 10        # Dimensionless
                  ,'Bc_PT'               : 1000      # MeV
                  ,'CTAU_Bc'             : 75        # microMeter
                  # Pre- and postscales
                  ,'Bc2Ds1GammaPreScale'               : 1.0
                  ,'Bc2Ds1GammaPostScale'              : 1.0
                  },
    'STREAMS' : [ 'Radiative' ],
    'WGs'    : [ 'BandQ' ]
    }

class Bc2Ds1GammaConf(LineBuilder):
    """
    Definition of Bc -> Ds1 Gamma stripping

    Constructs Bc -> Ds1 Gamma Selections and StrippingLines from
    a configuration dictionary.
    Usage:
    >>> config = { .... }
    >>> gammaConf = StrippingB2XGammaConf('StrippingB2XGammaTest',config)
    >>> gammaLines = gammaConf.lines
    >>> for line in line :
    >>>  print line.name(), line.outputLocation()
    The lines can be used directly to build a StrippingStream object.

    Exports as instance data members:
    selPhoton                    : Photon Selection object
    selD0                        : nominal D0 -> K pi Selection object
    selDs1                       : nominal Ds1 -> D0 K Selection object
    selDs1WS                     : nominal Ds1 -> D~0 K Selection object
    selBc2Ds1Gamma               : Bc -> Ds1 Gamma Selection object
    selBc2Ds1GammaWS             : Bc -> Ds1 Gamma Selection object
    lines                  : List of lines

    Exports as class data member:
    StrippingB2XGammaConf.__configuration_keys__ : List of required configuration parameters.
    """
    __configuration_keys__ = (#'BcMassWin'
                              'MinBcMass'
                              ,'MaxBcMass'
                              ,'BcPVIPchi2'
                              ,'photonPT'
                              ,'KaonProbNN'
                              ,'pionProbNN'
                              ,'TrGhostProb'
                              ,'Ds1DeltaMassWin'
                              ,'MaxDs1VertChi2DOF'
                              ,'Bc_PT'
                              ,'CTAU_Bc'
                              # Pre- and postscales
                              ,'Bc2Ds1GammaPreScale'
                              ,'Bc2Ds1GammaPostScale'
                              )

    def __init__(self, name, config):
        LineBuilder.__init__(self, name, config)

        # if name not set outside, set it to empty
        #if name == None:
        #    name = ""

        # Selection of Bc daughters: photon, D0, Ds1
        self.selPhoton = makePhoton('GammaFor%s' % name,
                                    config['photonPT'])

        self.selD0  = makeD0('D0For%s' % name,
                             config['KaonProbNN'],
                             config['pionProbNN'],
                             config['TrGhostProb'])

        self.selDs1 = makeDs1('Ds1For%s' % name,
                              self.selD0,
                              '[D_s1(2536)+ -> D0 K+]cc', #DecayDescriptor
                              config['KaonProbNN'],
                              config['TrGhostProb'],
                              config['Ds1DeltaMassWin'],
                              config['MaxDs1VertChi2DOF'])

        self.selDs1WS = makeDs1('Ds1WSFor%s' % name,
                              self.selD0,
                              '[D_s1(2536)+ -> D~0 K+]cc', #DecayDescriptor
                              config['KaonProbNN'],
                              config['TrGhostProb'],
                              config['Ds1DeltaMassWin'],
                              config['MaxDs1VertChi2DOF'])

        # Bc->Ds1 Gamma selections
        self.selBc2Ds1Gamma = makeBc2Ds1Gamma('Bc2Ds1GammaFor%s' % name,
                                              self.selDs1,
                                              self.selPhoton,
                                              config['BcPVIPchi2'],
#                                              config['BcMassWin'],
                                              config['MinBcMass'],
                                              config['MaxBcMass'],
                                              config['Bc_PT'],
                                              config['CTAU_Bc'])

        self.selBc2Ds1GammaWS = makeBc2Ds1Gamma('Bc2Ds1GammaWSFor%s' % name,
                                                self.selDs1WS,
                                                self.selPhoton,
                                                config['BcPVIPchi2'],
#                                                config['BcMassWin'],
                                                config['MinBcMass'],
                                                config['MaxBcMass'],
                                                config['Bc_PT'],
                                                config['CTAU_Bc'])

        # Create and register stripping lines
        self.Bc2Ds1GammaLine = StrippingLine("%s_Line" % name,
                                             prescale=config['Bc2Ds1GammaPreScale'],
                                             postscale=config['Bc2Ds1GammaPostScale'],
                                             selection=self.selBc2Ds1Gamma)
        self.registerLine(self.Bc2Ds1GammaLine)

        self.Bc2Ds1GammaLineWS = StrippingLine("%sWS_Line" % name,
                                               prescale=config['Bc2Ds1GammaPreScale'],
                                               postscale=config['Bc2Ds1GammaPostScale'],
                                               selection=self.selBc2Ds1GammaWS)
        self.registerLine(self.Bc2Ds1GammaLineWS)

def makePhoton(name, photonPT):
    """
    Create photon Selection object starting from DataOnDemand 'Phys/StdLooseAllPhotons'.

    @arg name: name of the Selection.
    @arg photonPT: PT of the photon
    @return: Selection object

    """

    _code = "(PT> %(photonPT)s*MeV)" % locals()
    _gammaFilter = FilterDesktop(Code=_code)
    _stdGamma = DataOnDemand(Location='Phys/StdLooseAllPhotons/Particles')
    return Selection(name, Algorithm=_gammaFilter, RequiredSelections=[_stdGamma])

def makeD0(name,  KaonProbNN, pionProbNN, TrGhostProb) :
    """
    Create and return a D0->Kpi Selection object, starting from DataOnDemand 'Phys/StdLooseD02KPi'.

    @arg name: name of the Selection.
    @arg KaonProbNN: PID of Kaon
    @arg pionProbNN: PID of pion
    @arg TrGhostProb: Ghost probability of pion/kaon
    @return: Selection object

    """

    _code = "(MAXTREE(ABSID=='K+',PROBNNk) > %(KaonProbNN)s) & (MAXTREE(ABSID=='pi+',PROBNNpi) > %(pionProbNN)s) & CHILDCUT( (TRGHOSTPROB<%(TrGhostProb)s) , 1 ) & CHILDCUT( (TRGHOSTPROB<%(TrGhostProb)s) , 2 )" % locals()
    _D0Filter = FilterDesktop(Code=_code)
    _stdD02Kpi = DataOnDemand(Location="Phys/StdLooseD02KPi/Particles")
    return Selection(name, Algorithm=_D0Filter, RequiredSelections=[_stdD02Kpi])

def makeDs1(name, D0Sel, DecDescr, KaonProbNN, TrGhostProb, Ds1DeltaMassWin, MaxDs1VertChi2DOF):
    """
    Create and return a Ds1+ -> D0/D~0 K+ Selection object, starting with the daughters' selections.

    @arg name: name of the Selection.
    @arg D0Sel: D0 selection.
    @arg DecDescr: Decay descriptor
    @arg KaonProbNN: PID of Kaon
    @arg TrGhostProb: Ghost probability of kaon
    @arg Ds1DeltaMassWin: Mass difference m(D0K) - m(D0)
    @arg MaxDs1VertChi2DOF: chi2/NDOF
    @return: Selection object
    """
    _daughterCut = "(TRGHOSTPROB<%(TrGhostProb)s) & (PROBNNk > %(KaonProbNN)s)" % locals()
    _combinationCut = "((AM-AM1) < 1.25*%(Ds1DeltaMassWin)s*MeV)" % locals()
    _motherCut = "((M-M1) < %(Ds1DeltaMassWin)s*MeV) & (VFASPF(VCHI2/VDOF) < %(MaxDs1VertChi2DOF)s)" % locals()
    _Ds1 = CombineParticles(DecayDescriptor = DecDescr,
                            DaughtersCuts = {"K+" : _daughterCut},
                            CombinationCut = _combinationCut,
                            MotherCut=_motherCut)

    _stdANNKaon = DataOnDemand(Location="Phys/StdLooseANNKaons/Particles")
    return Selection(name, Algorithm=_Ds1, RequiredSelections=[D0Sel, _stdANNKaon])

def makeBc2Ds1Gamma(name, Ds1Sel, gammaSel, BcPVIPchi2, MinBcMass, MaxBcMass, Bc_PT, CTAU_Bc):
    """
    Create and return a Bc+ -> Ds1+ Gamma Selection object, starting with the daughters' selections.

    @arg name: name of the Selection.
    @arg Ds1Sel: Ds1 -> D0/D~0 K selection
    @arg gammaSel: photon selection
    @arg BcPVIPchi2: IP chi2 of the Bc wrt the PV
    @arg MinBcMass: Lower bound of Bc mass
    @arg MaxBcMass: Upper bound of Bc mass
    @arg Bc_PT : PT of Bc
    @arg CTAU_Bc: lifetime*c of the Bc
    @return: Selection object

    """
#    _combinationCut = "ADAMASS('B_c+') < 1.5*%(BcMassWin)s*MeV" % locals()
#    _motherCut = "(ADMASS('B_c+')<%(BcMassWin)s*MeV) & (BPVIPCHI2() < %(BcPVIPchi2)s) & ((BPVLTIME()*c_light)>%(CTAU_Bc)s*micrometer) & (PT>%(Bc_PT)s*MeV)" % locals()

    _combinationCut = "(AM < %(MaxBcMass)s*MeV+500*MeV) & (AM > %(MinBcMass)s*MeV-500*MeV)" % locals()
    _motherCut = "(M < %(MaxBcMass)s*MeV) & (M > %(MinBcMass)s*MeV) & (BPVIPCHI2() < %(BcPVIPchi2)s) & ((BPVLTIME()*c_light)>%(CTAU_Bc)s*micrometer) & (PT>%(Bc_PT)s*MeV)" % locals()

    _Bc = CombineParticles(DecayDescriptor="[B_c+ -> D_s1(2536)+ gamma]cc",
                           CombinationCut=_combinationCut,
                           MotherCut=_motherCut,
                           ReFitPVs=False)#True)
    return Selection(name, Algorithm=_Bc, RequiredSelections=[Ds1Sel, gammaSel])

# EOF


from aionetworking.runners import run_server_default_tags
import pytest
import signal
import time
import os
from aionetworking.compatibility import supports_keyboard_interrupt, py38
from aionetworking.utils import wait_listening_on_sync, is_listening_on
from threading import Thread, Event

def raise_signal(signal_num, host, port):
    time.sleep(1)
    wait_listening_on_sync((host, port))
    if py38:
        signal.raise_signal(signal_num)
    else:
        os.kill(os.getpid(), signal_num)

@pytest.mark.parametrize('signal_num', [
    pytest.param(signal.SIGINT, marks=pytest.mark.skipif(not supports_keyboard_interrupt(), reason='Loop does not support keyboard interrupts')),
    pytest.param(signal.SIGTERM, marks=pytest.mark.skipif(os.name == 'nt', reason='POSIX only'))
])
def test_signal_runner(tmp_config_file, all_paths, server_port, signal_num, new_event_loop):
    thread = Thread(target=raise_signal, args=(signal_num, '127.0.0.1', server_port))
    thread.start()
    run_server_default_tags(tmp_config_file, paths=all_paths)
    thread.join(timeout=1)

def modify_config_file(tmp_config_file, old_host, new_host):
    with open(str(tmp_config_file), "rt") as f:
        data = f.read()
        data = data.replace(old_host, new_host)
    with open(str(tmp_config_file), 'wt') as f:
        f.write(data)

def assert_reload_ok(signal_num, host, port, tmp_config_file, event):
    event.wait()
    event.clear()
    new_host = '127.0.0.2'
    assert not is_listening_on((new_host, port))
    modify_config_file(tmp_config_file, host, new_host)
    raise_signal(signal_num, host, port)
    event.wait()
    assert not is_listening_on((host, port))
    raise_signal(signal.SIGTERM, new_host, port)
    modify_config_file(tmp_config_file, host, new_host)

@pytest.mark.parametrize('signal_num', [
    pytest.param(getattr(signal, 'SIGUSR1', None), marks=pytest.mark.skipif(os.name == 'nt', reason='POSIX only'))
])
def test_signal_runner_reload(tmp_config_file, all_paths, server_port, signal_num, new_event_loop):
    event = Event()
    thread = Thread(target=assert_reload_ok, args=(signal_num, '127.0.0.1', server_port, tmp_config_file, event))
    thread.start()

    def event_set(signum, frame):
        event.set()

    signal.signal(signal.SIGUSR2, event_set)
    run_server_default_tags(tmp_config_file, paths=all_paths, notify_pid=os.getpid())
    thread.join(timeout=1)


# ch16_9.py
from tkinter import *
from tkinter import messagebox
def minimizeIcon():                     # 縮小視窗為圖示
    root.iconify()
def showPopupMenu(event):               # 顯示彈出功能表
    popupmenu.post(event.x_root,event.y_root)

root = Tk()
root.title("ch16_9")
root.geometry("300x180")

popupmenu = Menu(root,tearoff=False)    # 建立彈出功能表物件
# 在彈出功能表內建立2個指令清單
popupmenu.add_command(label="Minimize",command=minimizeIcon)
popupmenu.add_command(label="Exit",command=root.destroy)
# 按滑鼠右鍵綁定顯示彈出功能表
root.bind("<Button-3>",showPopupMenu)

root.mainloop()

_4.python/__code/Python GUI 設計活用 tkinter之路/ch16/ch16_9.py


__author__ = "etseng@pacb.com"

"""
Lightweight filtering of SQANTI by using .classification.txt output

Only keep Iso-Seq isoforms if:
The isoform is FSM, ISM, or NIC and does not have intrapriming
The isoform is NNC, does not have intrapriming, not RT-switching, and all junctions are either all canonical or short-read-supported
The isoform is antisense, intergenic, genic, does not have intrapriming, not RT-switching, and all junctions are either all canonical or short-read-supported

"""

import os, sys, argparse
from csv import DictReader
from Bio import SeqIO

CATEGORY_DICT = {'full-splice_match': 'FSM',
                 'incomplete-splice_match': 'ISM',
                 'novel_in_catalog': 'NIC',
                 'novel_not_in_catalog': 'NNC',
                 'antisense': 'AS',
                 'intergenic': 'intergenic',
                 'genic_intron': 'intron',
                 'genic': 'genic'}

def sqanti_filter_lite(args):

    fafq_type = 'fasta'
    with open(args.isoforms) as h:
        if h.readline().startswith('@'): fafq_type = 'fastq'

    prefix = args.sqanti_class[:args.sqanti_class.rfind('.')]

    fcsv = open(prefix + '.filtered_lite_reasons.txt', 'w')
    fcsv.write("# classification: {0}\n".format(args.sqanti_class))
    fcsv.write("# isoform: {0}\n".format(args.isoforms))
    fcsv.write("# intrapriming cutoff: {0}\n".format(args.intrapriming))
    fcsv.write("# min_cov cutoff: {0}\n".format(args.min_cov))
    fcsv.write("filtered_isoform,reason\n")

    fout = open(prefix + '.filtered_lite.' + fafq_type, 'w')

    seqids_to_keep = []
    total_count = 0
    for r in DictReader(open(args.sqanti_class), delimiter='\t'):
        total_count += 1
        filter_flag, filter_msg = False, ""
        percA = float(r['perc_A_downstream_TTS']) / 100
        assert 0 <= percA <= 1
        min_cov = float(r['min_cov']) if r['min_cov']!='NA' else None
        num_exon = int(r['exons'])
        is_RTS = r['RTS_stage'] == 'TRUE'
        is_canonical = r['all_canonical']=='canonical'

        cat = CATEGORY_DICT[r['structural_category']]

        if cat in ['FSM', 'ISM', 'NIC']:
            if percA >= args.intrapriming:
                filter_flag, filter_msg = True, "IntraPriming"
        else:
            if percA >= args.intrapriming:
                filter_flag, filter_msg = True, "IntraPriming"
            elif is_RTS:
                filter_flag, filter_msg = True, "RTSwitching"
            elif (not is_canonical) and (min_cov is None or (min_cov is not None and min_cov < args.min_cov)):
                filter_flag, filter_msg = True, "LowCoverage"

        if not filter_flag:
            seqids_to_keep.append(r['isoform'])
        else:
            fcsv.write("{0},{1}\n".format(r['isoform'], filter_msg))

    print >> sys.stdout, "{0} isoforms read from {1}. {2} to be kept.".format(total_count, args.sqanti_class, len(seqids_to_keep))

    for r in SeqIO.parse(open(args.isoforms), fafq_type):
        if r.id in seqids_to_keep:
            SeqIO.write(r, fout, fafq_type)
    fout.close()
    print >> sys.stdout, "Output written to: {0}".format(fout.name)

def main():

    parser = argparse.ArgumentParser(description="Filtering of Isoforms based on SQANTI attributes")
    parser.add_argument('sqanti_class', help='\t\tSQANTI classification output file.')
    parser.add_argument('isoforms', help='\t\tFasta/Fastq isoform file to be filtered by SQANTI')
    parser.add_argument('-a',"--intrapriming", type=float, default=0.8, help='\t\tAdenine percentage at genomic 3\' end to flag an isoform as intra-priming (default: 0.8)')
    parser.add_argument("-c", "--min_cov", type=int, default=0, help="\t\tMinimum junction coverage for each isoform (only used if min_cov field is not 'NA'), default: 0")
    #parser.add_argument("--always_keep_canonical", default=False, action="store_true", help="Always keep isoforms with all canonical junctions, regardless of other criteria. (default: False)")

    args = parser.parse_args()

    assert 0 <= args.intrapriming <= 1

    args.sqanti_class = os.path.abspath(args.sqanti_class)
    if not os.path.isfile(args.sqanti_class):
        print >> sys.stderr, "ERROR: {0} doesn't exist. Abort!".format(args.sqanti_class)
        sys.exit(-1)

    if args.isoforms is not None and not os.path.isfile(args.isoforms):
        print >> sys.stderr, "ERROR: {0} doesn't exist. Abort!".format(args.isoforms)
        sys.exit(-1)

    # if args.dir is None:
    #     args.dir = os.getcwd() + "/Filter_out"
    #     if not os.path.exists(args.dir):
    #         os.makedirs(args.dir)
    # else:
    #     args.dir = os.path.abspath(args.dir)
    #     if not os.path.exists(args.dir):
    #         os.makedirs(args.dir)

    print >> sys.stdout, "\nRunning SQANTI filtering...\n"

    sqanti_filter_lite(args)

if __name__ == "__main__":
    main()


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

def compute_cost(x, y, theta):
    m = len(y)
    h = np.matmul(theta.T, x).T
    #print(h.shape)
    #print(y.shape)
    res = h - y
    #print(res.shape)
    J = 1 / (2 * m) * np.sum(res*res, axis=0)
    #print(J)
    return J

def gradientDescent(x, y, theta, alpha, iterations):
    m = len(y)
    y = y.reshape(m, 1)
    for iter in range(iterations):
        J = compute_cost(x, y, theta)
        J_history.append(J[0])
        temp = np.matmul(theta.T, x).T - y
        # print(x.shape)
        # print(temp.shape)
        res = alpha/m * np.matmul(x, temp)
        theta = theta - res
    return theta

J_history = []

if __name__ == '__main__':
    data = pd.read_csv('ex1data1.txt', sep=',', header=None)

    # print(data.head())
    #
    # print(data[0])
    length = data[0].size

    tx = np.array(data[0])
    ty = np.array(data[1])
    ty.reshape(ty.size, 1)
    one = np.ones(length)
    X = np.vstack((one, tx))
    theta = np.ones(shape=(2, 1))
    print(theta.shape)
    iterations = 1500
    alpha = 0.01
    theta = gradientDescent(X, ty, theta, alpha, iterations)
    #print(J_history.shape)

    #print(theta)
    min_x = min(tx)
    max_x = max(tx)
    x = np.arange(min_x, max_x, 0.1)
    one = np.ones(x.size)
    xx = np.vstack((one, x))
    y = np.matmul(theta.T, xx)
    y = y.T
    iters = np.arange(1, 1501, 1)

    plt.scatter(tx.T, ty.T, c='r', marker='x', s=12)
    plt.plot(x, y)
    plt.xlabel('Population of City in 10000s')
    plt.ylabel('Profit')
    plt.show()

    '''
    plt.plot(iters, J_history, c='r')
    plt.xlabel('Population of City in 10000s')
    plt.ylabel('Profit')
    plt.show()
    '''


import serial
import time
from threading import Thread

class Esp():
    def __init__(self, robot, espNum):
        self.robot = robot
        self.espNum = espNum
        self.espType = "unknown"
        self.messagesToSend = {"l": ["", True], "g":["",False]}
        self.device = False
        self.stopped = False

    def begin(self):
        try:
            self.device = serial.Serial(port='/dev/ttyUSB' + str(self.espNum), baudrate=115200, timeout=.1)
        except:
            return False
        time.sleep(0.5)
        self.rxThread = Thread(target=self.readSerial)
        self.txThread = Thread(target=self.sendSerial)
        self.rxThread.start()
        self.txThread.start()
        return True

    def endEsp(self):

        self.rxThread.join()

        self.txThread.join()

        self.device.write(bytes("s", 'utf-8'))

        return True

    def readSerial(self):
        while self.robot.notCtrlC:
            line = self.device.readline()
            self.processSerial(line)
            time.sleep(0.1)

    def processSerial(self, message_bin):
        message = str(message_bin)
        if len(message_bin) > 0:

            try:
                message = message[2:-5] # the binary message has some extra things at the beginning and end
                msgType = message[0] # first character shows message type

            except: # strange message format
                return

            if msgType == ".": # suppressed print statement
                return

            elif msgType == "-":

                keyName = message[1] # since the 1st character was a minus, the 2nd character is the ID character and the following characters are the value
              #  print(self.messagesToSend[keyName])
                try:
                    if self.messagesToSend[keyName][0] == "" or int(float(self.messagesToSend[keyName][0])) == int(float(message[2::])): # ESP correctly got the message we are trying to send
                        self.messagesToSend[keyName][1] = False
                        # print("got it right")

                    else: # esp incorrectly got the message we are trying to send
                        # print("wrong", self.messagesToSend[keyName][0], message[2::])
                        pass
                except:
                    pass
                    # print("wrong type", self.messagesToSend[keyName][0], message[2::])

                return
            if msgType == "s":
               print(self.espType, "stopped")
               self.stopped = True
               return

            try:
                res = float(message[1::])
            except:
                print("invalid message from " + self.espType + ": " + message)
                return

            if msgType == "x":  # compass latitude
                self.robot.coords[0] = res
                self.robot.lastUpdatedDist = self.robot.distanceTraveled

            elif msgType == "y":  # compass longitude
                self.robot.coords[1] = res
                self.robot.lastUpdatedDist = self.robot.distanceTraveled

            elif msgType == "w":  # wheel speed
                self.robot.wheelSpeed = res

            elif msgType == "d":  # distance
                self.robot.distanceTraveled = res
                self.robot.updateCoords()

            elif msgType == "a":  # steering angle
                self.robot.steeringAngle = res
                self.robot.steeringDirection = self.robot.heading + res

            elif msgType == "h": # heading from GPS
                self.robot.heading = res

            elif msgType == "c": # heading from compass
                pass
#                self.robot.heading = res

            elif msgType == "t": # accuracy of GPS
                self.robot.gpsAccuracy = res

            elif msgType == "s": # stopped
                self.stopped = res

            elif msgType == "o": # An error occured represented by a number. Deal with it elsewhere
                if [res, self] not in self.robot.errorList:
                    self.robot.errorList += [[res, self]]

            elif msgType == "e": # role of ESP
                espTypes = ["unknown", "steer", "speed", "access point"]
                if res < len(espTypes):
                    if espTypes[int(res)] != self.espType:
                        self.setESPType(espTypes[int(res)])

    def setESPType(self, espType):
        if espType == "steer":
            self.messagesToSend = {"p": ["0", False], "s": ["0", False], "g": ["", False], "r": ["", False], "l": ["", False]}

        if espType == "speed":
            self.messagesToSend = {"f": ["0", False], "m": ["0", False], "s": ["", False], "g": ["", False], "r": ["", False], "l": ["", False]}

        if espType == "access point":
            self.messagesToSend = {"l": ["", False], "s": ["", False], "g": ["", False], "r": ["", False]}

        print("set up esp " + espType)
        self.espType = espType

    def sendSerial(self):
        print("send serial")
        while self.robot.notCtrlC:
            if self.device != False:
                self.updateMessages()
                messagesSent = 0
                for i in self.messagesToSend:
                    if self.messagesToSend[i][1]:
                        msg = i + self.messagesToSend[i][0]
                        self.device.write(bytes(msg, 'utf-8'))
                        # print("sent", msg)
                        messagesSent+=1
                        time.sleep(0.2)

                if messagesSent == 0:
                    # send an empty message to prevent the ESP from assuming an error in communication
                    self.device.write(bytes(".", 'utf-8'))
                    time.sleep(0.2)
                    # print("sent empty")
              #      print(self.messagesToSend)

    def restart(self):
        self.device.write(bytes("r", 'utf-8'))

    def updateMessages(self):
        fullMessages = {"p": str(self.robot.targetWheelAngle), "f": str(self.robot.targetSpeed),
         "m": str(self.robot.targetMoveDist), "r": "", "s": "", "g": "", "l": ""}

        if self.robot.stopNow:
            self.messagesToSend["s"][1] = True

        elif self.stopped:
            self.stopped = False
            self.messagesToSend["g"][1] = True

        for i in self.messagesToSend:
            if self.messagesToSend[i][0] != fullMessages[i]:
                self.messagesToSend[i][0] = str(fullMessages[i])
                self.messagesToSend[i][1] = True


"""
Working with notifications
"""
from notifications.client import ProctorNotificator

def send_notification(data, channel, action=None):
    """
    Send message to subscribers
    """
    res = data.copy()
    res['course_event_id'] = int(channel)
    res['action'] = action if action else 'change_status'
    ProctorNotificator.notify(res)


from mallet import *
import pygame
import socket
import disc as d
import cv2
import numpy as np
import pygame
import threading
import cPickle as pickles
from Constant import *
import pickle
import winsound
from ConfigParser import SafeConfigParser

time = '00:00'
screen_c = 0
bg = pygame.image.load(BG_PATH)
score = [0, 0]
#player1 = player2 = disc = 0
clock = pygame.time.Clock()
player2_pos = PLAYER2_START
player1_pos = PLAYER1_START
PLAYER1_COLOR = [255, 0, 0]
PLAYER2_COLOR = [255, 0, 0]
PUCK_COLOR = [255, 0, 0]
MAX_TIME = -1
MAX_GOAL = -1
lower = np.array([10, 150, 0])
upper = np.array([30, 255, 255])
def init():
    global player2, player1, disc, clock, player2_pos, player1_pos, score, screen_c, font, font_small
    font = pygame.font.Font("../fonts/scoreboard.ttf", 60)
    font_small = pygame.font.Font("../fonts/scoreboard.ttf", 30)
    player1 = Mallet(PLAYER1_START, MALLET_SPEED, 0, MALLET_MASS, MALLET_RAD, 1, PLAYER1_COLOR)
    player2 = Mallet(PLAYER2_START, MALLET_SPEED, 0, MALLET_MASS, MALLET_RAD, 2, PLAYER2_COLOR)
    disc = d.Disc([-XMAX_SCALE/2, 0], DISC_START_SPEED, DISC_START_ANGLE, DISC_FRICTION, DISC_MASS, DISC_RAD, PUCK_COLOR)
    clock = pygame.time.Clock()
    player2_pos = PLAYER2_START
    player1_pos = PLAYER1_START
    score = [0, 0]

def capture(conn):
    global pos, lower, upper
    h = w = 0
    cap = cv2.VideoCapture(0)
    while True:
        _, frame = cap.read()
        # hue saturation value
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        if h == 0:
            (w, h) = hsv.shape[:2]
        cv2.flip(hsv, 1, hsv)

        mask = cv2.inRange(hsv, lower, upper)
        kernal = np.ones((15, 15), np.float32) / 225
        opening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernal)
        cnts = cv2.findContours(opening.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
        if len(cnts) > 0:
            c = max(cnts, key=cv2.contourArea)
            ((x, y), radius) = cv2.minEnclosingCircle(c)
            if radius > 10:
                temp = scale_opp([int(x), int(y)], [h, w])
                threading.Thread(name='send', target=send(conn, temp)).start()

def send(conn, data):
    data = pickle.dumps(data)
    conn.send(data)

def draw():
    global time, font
    screen_c.fill((0, 0, 0))
    screen_c.blit(bg, scale([-XMAX_SCALE/2 - 32, YMAX_SCALE/2 + 22]))
    disc.draw(screen_c)
    score1 = font.render(str(score[0]), 1, white)
    score2 = font.render(str(score[1]), 1, white)
    screen_c.blit(score1, scale([-XMAX_SCALE / 4 - XMAX_SCALE / 16, -YMAX_SCALE / 26]))
    screen_c.blit(score2, scale([XMAX_SCALE / 4, YMAX_SCALE / 8]))
    time_font = font_small.render(time, 1, white)

    screen_c.blit(time_font, scale([-XMAX_SCALE/12, YMAX_SCALE/46]))

    player1.draw(screen_c)
    player2.draw(screen_c)
    pygame.display.update()

def end_game(winner):
    # opposite scores ##top score 1 ##bottom score2
    if winner == 0:
        end_label = font.render("PLAYER 1 WINS!", 1, PLAYER1_COLOR)
        winsound.PlaySound(BOO_SOUND, winsound.SND_FILENAME)

    else:
        end_label = font.render("PLAYER 2 WINS!", 1, PLAYER2_COLOR)
        winsound.PlaySound(CLAP_SOUND, winsound.SND_FILENAME)

    screen_c.blit(end_label, (XMAX*0.5-end_label.get_width()*0.5 + 20, YMAX*0.5))
    pygame.display.update()
    pygame.time.wait(3000)
    clock.tick(500)

def recv_pos(conn):
    global score, screen_c, time
    while True:
        pygame.event.get()
        try:
            temp = conn.recv(110).strip()
        except:
            break
        try:
            data = pickle.loads(temp)
            player1.move_to(data[0])
            player2.move_to(data[1])
            disc.move_to(data[2])
            score = data[3]
            time = data[4]
            if str(data[5]) != '-1':
                end_game(data[5])
            draw()
        except:
            continue
    pygame.quit()
    quit()

def connect(ip):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((ip, 1234))
        return s
    except:
        return -1

def start(s):
    threading.Thread(name='capture', target=capture,kwargs=dict(conn=s)).start()
    recv_pos(s)

def main(ip):
    global PLAYER1_COLOR, PLAYER2_COLOR, MAX_GOAL, MAX_TIME, PUCK_COLOR, screen_c, lower, upper
    conn = connect(ip)
    if conn == -1:
        return -1
    list = pickle.loads(conn.recv(1024))
    MAX_TIME = int(list[0])
    MAX_GOAL = int(list[1])
    PLAYER1_COLOR = list[2:5]
    PUCK_COLOR = list[5:8]
    PLAYER1_COLOR = [int(word) for word in PLAYER1_COLOR]
    PUCK_COLOR = [int(word) for word in PUCK_COLOR]
    file = open('settings_c.txt', 'r')
    PLAYER2_COLOR = [int(word.strip()) for word in file.readlines()]
    try:
        config = SafeConfigParser()
        config.read('HSV_Config.ini')
        l1 = int(config.get('Lower Bound', 'H'))
        l2 = int(config.get('Lower Bound', 'S'))
        l3 = int(config.get('Lower Bound', 'V'))
        u1 = int(config.get('Upper Bound', 'H'))
        u2 = int(config.get('Upper Bound', 'S'))
        u3 = int(config.get('Upper Bound', 'V'))
    except:
        l1 = l2 = l3 = u1 = u2 = u3 = 50
    lower = np.array([int(l1), int(l2), int(l3)])
    upper = np.array([int(u1), int(u2), int(u3)])

    conn.send(pickle.dumps(PLAYER2_COLOR))
    pygame.init()
    screen_c = pygame.display.set_mode((XMAX, YMAX))
    pygame.display.set_caption("Client")
    pygame.display.set_icon(pygame.image.load(ICON))
    init()
    start(conn)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time, os,sys, TranspositionEncrypt, TranspositionDecrypt

def main():
    inputFilename='frankenstein.txt'
    outputFilename='frankenstein.encrypted.txt'
    myKey=10
    myMode='encrypt'

    #If the input file does not exist, then the program terminates early.
    if not os.path.exists(inputFilename):
        print('The file %s does not exist. Quitting...'%(inputFilename))
        sys.exit()

    #If the output file already exist give the user a chance to exit
    if os.path.exists(outputFilename):
        print('This will overwrite the file %s. (C)ontinue or (Q)uit'%
              (outputFilename))
        response=input('>')
        if not response.lower().startswith('c'):
            sys.exit()

    #Read in the message from the input file
    fileObj=open(inputFilename)
    content=fileObj.read()
    fileObj.close()

    print('%sing...' %(myMode.title()))

    #Measure how long the encryption/decryption takes.
    startTime=time.time()

    if myMode=='encrypt':
        translated= TranspositionEncrypt.encryptMessage(myKey, content)
    elif myMode=='decrypt':
        translated= TranspositionDecrypt.decryptMessage(myKey, content)
    totalTime=round(time.time()-startTime, 2)
    print('%sion time: % seconds' %(myMode.title(),totalTime))

    #Write out the translated message to the output file
    outputFileObj=open(outputFilename,'w')
    outFileobj.write(translated)
    outputFileObj.close()

    print('Done %sing %s (5s characters).' %(myMode, inputFilename,
          len(content)))
    print('%sed file is %s.' %(myMode.title(), outputFilename))

if __name__=='__main__':
    main()


from ftw.upgrade import UpgradeStep

class RemoveCustomCommitteeWorkflowActions(UpgradeStep):
    """Remove custom committee workflow actions.
    """

    workflow_actions_to_remove = [
        'deactivate-committee',
        'reactivate-committee',
    ]

    def __call__(self):
        for action_id in self.workflow_actions_to_remove:
            self.actions_remove_type_action(
                'opengever.meeting.committee', action_id)