# -*- coding: utf-8 -*-
'''
    @author:赵晨卓
    @data:2021-06-15
    @dexc:对数据表的crud操作系统
'''
import os
import sys
import pymysql
#让程序输出更加美观
from prettytable import PrettyTable
#密码输入不回显
from getpass import getpass

# 创造goods表
def creategoods(conn):
    try:
        # 得到一个可以执行SQL语句的光标对象
        cursor = conn.cursor()  # 执行完毕返回的结果集默认以元组显示
        sql = "create table goods(gid int auto_increment primary key not null,gname varchar(20),gprice int,gnum int);"
        # 运行sql语句
        cursor.execute(sql)
        print("goods创造成功")
    # 发生异常报错
    except Exception as e:
        print(f"创造goods表失败，错误原因为{e}")
    finally:
        # 关闭cursor对象
        cursor.close()
# 对于goods表进行插入操作

def insert(conn, name, price, num):
    try:
        cursor = conn.cursor()
        sql = "insert into goods(gid,gname,gprice,gnum) value(null,%s,%s,%s);"
        # 运行sql语句
        cursor.execute(sql, (name, price, num))
        # 提交至服务器
        conn.commit()
        print("插入成功")
        # 发生异常报错
    except Exception as e:
        print(f"添加数据失败,错误原因为{e}")
    finally:
        # 关闭cursor对象
        cursor.close()
# 对于goods表中数据进行删除操作

def delete(conn, where, data):
    try:
        cursor = conn.cursor()
        sql = f"delete from goods where {where}={data};"
        # 运行sql语句
        cursor.execute(sql)
        # 提交至服务器
        conn.commit()
        print("成功删除")
        # 发生异常报错
    except Exception as e:
        print(f"删除数据失败,错误原因为{e}")
    finally:
        # 关闭cursor对象
        cursor.close()
# 读取数据表中的数据

def read(conn, str):
    try:
        cursor = conn.cursor()
        sql = f"select * from goods where {str};"
        # 运行sql语句
        number = cursor.execute(sql)
        x = PrettyTable()
        x.field_names = [
            "商品ID(gid)",
            "商品名称(gname)",
            "商品价格(gprice)",
            "商品数量(gnum)"]
        # 将结果全部导出
        for i in range(number):
            out = cursor.fetchone()
            x.add_row([out[0], out[1], out[2], out[3]])
        print(x)
    except Exception as e:
        print(f"查询数据失败,错误原因为{e}")
    finally:
        # 关闭cursor对象
        cursor.close()

def update(conn, searchwhere, searchdata, newwhere, newdata):
    try:
        cursor = conn.cursor()
        sql = f"update goods set {newwhere}={newdata} where {searchwhere}={searchdata}"
        cursor.execute(sql)
        conn.commit()
        print("修改成功")
    except Exception as e:
        print(f"修改数据失败,错误原因为{e}")
    finally:
        # 关闭cursor对象
        cursor.close()

# main
# 主函数模块，登陆mysql
print("请按照提示信息输入用户名，密码以及数据库名，请确保mysql已经安装完成(密码输入不回显)")
a = input("user=")
b = getpass("password=")
c = input("database=")
print("--------------------")
try:
    # 连接database
    conn = pymysql.connect(
        host="localhost",
        user=a,
        password=b,
        database=c,
        charset="utf8")
    print("登陆成功\n=========================================")
# 报错提示
except Exception as e:
    print(f"登陆失败,错误原因为{e}")
    sys.exit(0)
print()
print("欢迎来到goods数据表管理系统")
print("该系统所有的实现均在goods表中")
print("该数据表有四个内容，分别为gid(物品ID),gname(物品名称),gprice(物品价格),gnum(物品数量)")
print("除物品名称为字符串型数据之外的都为整型数据\n")
print("----------------------------------------")
print("\n现在会检测goods表是否存在，若不存在将会创造相应表格，若存在则会提示创造表格失败,对后续操作无影响")
creategoods(conn)
print("下面开始操作\n\n=========================================\n")
# 死循环，可以对于数据进行多次修改
while(1):
    print("您可以使用四种操作方式，请输入相应字母点击回车，请注意不要输入多余字母\na.添加数据	b.删除数据	c.更新数据	d.查看数据	e.退出程序")
    str = input()
    if(str == 'a'):
        print("请输入新增的物品名称，物品价格与物品数量，中间以一个空格分隔")
        name, price, num = input().split()
        insert(conn, name, price, num)
    if(str == 'b'):
        print("请输入删除的商品属性与数值，中间以一个空格分隔，如 gid 2")
        where, data = input().split(" ")
        delete(conn, where, data)
    if(str == 'c'):
        print("请输入原始的数据的商品属性与数值，以及修改的熟悉与数值，如 gid 2 gprice 100 表示把gid=2的商品grice修改为100")
        searchwhere, searchdata, newwhere, newdata = input().split(" ")
        update(conn, searchwhere, searchdata, newwhere, newdata)
    if(str == 'd'):
        print("请输入查看商品的字符代码，如查询gid=2的商品请输入gid=2,如显示所有数据请输入1")
        str = input()
        read(conn, str)
    if(str == 'e'):
        break
conn.close()
sys.exit(0)

大一下/信息技术认知实践/ch03.py


"""moving subgroup var

Revision ID: 6d154dc9fa83
Revises: d09ee853c6fa
Create Date: 2021-05-20 22:54:32.100983

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '6d154dc9fa83'
down_revision = 'd09ee853c6fa'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('dashboard_source', sa.Column('subgroup_var', sa.String(), nullable=True))
    op.drop_column('research_source', 'subgroup_var')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('research_source', sa.Column('subgroup_var', sa.VARCHAR(), autoincrement=False, nullable=True))
    op.drop_column('dashboard_source', 'subgroup_var')
    # ### end Alembic commands ###


from data.InputRow import InputRow
from typing import List
from .OutputRow import OutputRow
import csv

class CsvHelper(object):
    """CsvHelper is a class that facilitates writing and reading  to/from CSV files"""
    def __init__(self):
        super(CsvHelper, self).__init__()

    """ Write all objects of test results in the specified array into a CSV format at the specified file"""
    @staticmethod
    def write_results_to_csv(filename:str, output_rows:List[OutputRow]):
        csvcolumns=["inputimagefile","outputimagefile","threshold","thresholdfactor","nearest_neighbour","time"]
        with open(filename, mode='w', newline='') as csv_file:
            testimage_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
            testimage_writer.writerow(csvcolumns)
            for output_row in output_rows:
                testimage_writer.writerow([output_row.imagefile,output_row.outputimagefile,output_row.actualthreshold,output_row.thresholdfactor,output_row.nearest_neighbour_distance_statistic,output_row.elapsed_time])
        pass

    def write_input_rows_to_csv(filename:str,input_rows:List[InputRow]):
        with open(filename, mode='w', newline='') as csv_file:
            testimage_writer=csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
            testimage_writer.writerow(["imagefile","salt_pepper","max_distance","line_count","total_pixels","black_pixels"])
            for row in input_rows:
                testimage_writer.writerow([row.imagefile,row.salt_pepper,row.max_distance,row.line_count,row.total_pixels,row.black_pixels])
        pass

    """Read all input images from the specified CSV file and creates a data object for every line"""
    @staticmethod
    def read_input_rows_from_csv(filename:str)->List[InputRow]:
        input_file=csv.DictReader(open(filename))
        results=[]
        for row_dict in input_file:
            input_row=InputRow()
            input_row.imagefile=row_dict["imagefile"]
            input_row.salt_pepper=float(row_dict["salt_pepper"])
            input_row.line_count=int(row_dict["line_count"])
            input_row.total_pixels=int(row_dict["total_pixels"])
            input_row.black_pixels=int(row_dict["black_pixels"])
            input_row.max_distance=float(row_dict["max_distance"])

            results.append(input_row)
        return results

    @staticmethod
    def read_result_rows_from_csv(filename:str)->List[OutputRow]:
        output_file=csv.DictReader(open(filename))
        results=[]
        for row_dict in output_file:
            output_row=OutputRow()
            output_row.imagefile=row_dict["inputimagefile"]
            output_row.outputimagefile=row_dict["outputimagefile"]
            output_row.thresholdfactor=float(row_dict["thresholdfactor"])
            output_row.actualthreshold=float(row_dict["threshold"])
            output_row.elapsed_time=float(row_dict["time"])
            output_row.nearest_neighbour_distance_statistic=float(row_dict["nearest_neighbour"])
            results.append(output_row)
        return results


import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from io import BytesIO

class Lithology():
    def lithology_classification(self, file, boreholeName, dictionaryLitho):
        data_lithology = pd.read_csv(file)
        gb = data_lithology.groupby('Borehole Name')
        [gb.get_group(x) for x in gb.groups]

        for z in gb.groups:
            keep = gb.get_group(z)

        lithology_numbers = dictionaryLitho
        df_lith = pd.DataFrame.from_dict(lithology_numbers, orient='index')
        df_lith.index.name = 'LITHOLOGY'
        result = data_lithology.replace(
            dict(zip(df_lith.lith, df_lith.index)))
        keep = pd.DataFrame(result)
        test = keep[keep["Borehole Name"] ==
                    boreholeName].reset_index(drop=True)
        test = test[::-1]
        return self.makeplot(test, lithology_numbers)

    def makeplot(self, well, lithology_numbers):
        fig, ax = plt.subplots(figsize=(50, 20))

        # Set up the plot axes
        ax4 = plt.subplot2grid((1, 3), (0, 2), rowspan=1, colspan=1)

        # Lithology track
        ax4.plot(well['To'], color="black", linewidth=0.5)
        ax4.set_xlabel("Lithology")
        ax4.set_xlim(0, 1)
        ax4.xaxis.label.set_color("black")
        ax4.tick_params(axis='x', colors="black")
        ax4.spines["top"].set_edgecolor("black")

        for x in range(well.shape[0]):
            key = well['Lithology'][x]
            selectColor = lithology_numbers[key]['color']
            hatch = lithology_numbers[key]['hatch']
            ax4.fill_betweenx(y=[well['From'][x], well["To"][x]],
                              x1=0, x2=2, facecolor=selectColor, hatch=hatch)

        plt.tight_layout()
        yticks = np.arange(well["From"].min(), well["To"].max()+10, 10)
        plt.yticks(yticks)
        plt.gca().invert_yaxis()
        fig.subplots_adjust(wspace=0.15)
        buf = BytesIO()
        plt.savefig(buf, bbox_inches='tight', format='png')
        return buf


from eos.tests import TestBase
from eos.types import Fit, Character, Slot, Module, Ship, User, State, Drone, Implant, Booster, Hardpoint, DamagePattern
from eos import db
import eos.db.saveddata.queries
import sqlalchemy.orm
from copy import deepcopy
from itertools import count

class Test(TestBase):
    def setUp(self):
        TestBase.setUp(self)
        self.m = Module(db.getItem("Heat Sink I"))

    def test_tankNumbers(self):
        f = Fit()
        f.ship = Ship(db.getItem("Erebus"))
        f.modules.append(Module(db.getItem("Small Shield Booster II")))
        f.modules.append(Module(db.getItem("Small Armor Repairer II")))
        f.modules.append(Module(db.getItem("Small Hull Repairer II")))
        f.modules.append(Module(db.getItem("Damage Control II")))
        f.damagePattern = DamagePattern(25, 25, 25, 25)
        for m in f.modules:
            m.state = State.ACTIVE
        f.calculateModifiedAttributes()

        self.assertEquals(len(f.effectiveTank), len(f.tank))
        for k in f.effectiveTank.iterkeys():
            self.assertGreater(f.effectiveTank[k], f.tank[k])

        self.assertEquals(len(f.effectiveSustainableTank), len(f.sustainableTank))
        for k in f.effectiveSustainableTank.iterkeys():
            self.assertGreater(f.effectiveSustainableTank[k], f.sustainableTank[k])

    def test_addDrain(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        f.addDrain(5, 500, 0)
        self.assertEquals(f.capUsed, 100000)

    def test_setCharacter(self):
        f = Fit()
        f.character = Character("Testety")

    def test_addNotAModule(self):
        try:
            self.f.addModule(1302)
        except:
            return
        self.fail("Added an invalid module, was expecting a ValueError")

    def test_addValidModule(self):
        f = Fit()
        f.modules.append(self.m)

    def test_importEft(self):
        f = Fit.importEft('''[Rifter, Test]
                             Salvager I
                             Hobgoblin I x4''')

        self.assertEquals(f.name, "Test")
        self.assertEquals(f.ship.item.name, "Rifter")
        self.assertEquals(f.modules[0].item.name, "Salvager I")
        self.assertEquals(f.drones[0].amount, 4)
        self.assertEquals(f.drones[0].item.name, "Hobgoblin I")

    def test_importXml(self):
        fits = Fit.importXml('''<?xml version="1.0" ?>
                            <fittings>
                                <fitting name="Test">
                                    <description value=""/>
                                    <shipType value="Rifter"/>
                                    <hardware slot="hi slot 0" type="Salvager II"/>
                                </fitting>
                            </fittings>''')

        f = fits[0]
        self.assertEquals(f.name, "Test")
        self.assertEquals(f.ship.item.name, "Rifter")
        self.assertEquals(f.modules[0].item.name, "Salvager II")

    def test_removeModuleNotExists(self):
        f = Fit()
        self.assertRaises(ValueError, f.modules.remove, self.m)

    def test_removeModuleExists(self):
        f = Fit()
        f.modules.append(self.m)
        f.modules.remove(self.m)

    def test_removeInvalidModule(self):
        f = Fit()
        self.assertRaises(ValueError, f.modules.remove, 1302)

    def test_setShip(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))

    def test_extraAttributesClear(self):
        f = Fit()
        f.extraAttributes["cloaked"] = True
        f.clear()
        self.assertEqual(f.extraAttributes["cloaked"], False)

    def test_databaseConsistency(self):
        oldSession = db.saveddata_session
        oldSession.commit()
        try:
            f = Fit()
            f.ship = Ship(db.getItem("Rifter"))
            f.name = "test fit 1"
            u = User("fittest", "testy", False)
            f.owner = u

            f2 = Fit()
            f2.ship = Ship(db.getItem("Thrasher"))
            f2.name = "test fit 2"
            f2.owner = u
            db.saveddata_session.add(f)
            db.saveddata_session.add(f2)
            db.saveddata_session.flush()

            f.projectedFits.append(f2)

            #Hack our way through changing the session temporarly
            oldSession = eos.db.saveddata.queries.saveddata_session
            eos.db.saveddata.queries.saveddata_session = sqlalchemy.orm.sessionmaker(bind=db.saveddata_engine)()

            newf = db.getFit(f.ID)

            self.assertNotEquals(id(newf), id(f))
            self.assertEquals(f.name, newf.name)
            for fit in newf.projectedFits:
                self.assertNotEqual(id(fit), id(f2))
                self.assertEquals(f2.name, fit.name)

        except:
            db.saveddata_session.rollback()
            raise
        finally:
            #Undo our hack as to not fuck up anything
            eos.db.saveddata.queries.saveddata_session = oldSession

    def test_projectedFit(self):
        f1 = Fit()
        f1.ship = Ship(db.getItem("Rifter"))
        f2 = Fit()
        m1 = Module(db.getItem("Stasis Webifier I"))
        m2 = Module(db.getItem("Stasis Webifier I"))
        m1.state = State.ACTIVE
        m2.state = State.ACTIVE
        f2.modules.append(m1)
        f2.modules.append(m2)
        f1.projectedFits.append(f2)
        f1.calculateModifiedAttributes()
        self.assertAlmostEquals(99.800, f1.ship.getModifiedItemAttr("maxVelocity"), 3)

    def test_projectSelf(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        m1 = Module(db.getItem("Stasis Webifier I"))
        m2 = Module(db.getItem("Stasis Webifier I"))
        m1.state = State.ACTIVE
        m2.state = State.ACTIVE
        f.modules.append(m1)
        f.modules.append(m2)
        f.projectedFits.append(f)
        f.calculateModifiedAttributes()
        self.assertAlmostEquals(99.800, f.ship.getModifiedItemAttr("maxVelocity"), 3)

    def test_capacitorNoMods(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        self.assertEquals(f.capStable, True)
        self.assertAlmostEquals(f.capState, 100, 1)

    def test_capacitorUnstable(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        m = Module(db.getItem("100MN Afterburner I"))
        m.state = State.ACTIVE
        f.modules.append(m)
        self.assertFalse(f.capStable)
        self.assertTrue(f.capState < 15)

    def test_capacitorSingleCycleKill(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        for _ in xrange(5):
            m = Module(db.getItem("100MN Afterburner I"))
            m.state = State.ACTIVE
            f.modules.append(m)

        self.assertFalse(f.capStable)
        self.assertEquals(f.capState, 0)

    def test_copy(self):
        f = Fit()
        f.name = "Testety"
        f.character = Character("TEST")
        f.owner = User("moo")
        testm = Module(db.getItem("Heat Sink I"))
        f.modules.append(testm)
        tests = Ship(db.getItem("Rifter"))

        f.ship = tests

        testpm = Module(db.getItem("Stasis Webifier I"))
        f.projectedModules.append(testpm)

        testd = Drone(db.getItem("Hobgoblin I"))
        f.drones.append(testd)

        testi = Implant(db.getItem("Halo Omega"))
        f.implants.append(testi)

        testb = Booster(db.getItem("Strong Drop Booster"))
        f.boosters.append(testb)

        testpd = Drone(db.getItem("Warrior TP-300"))
        f.projectedDrones.append(testpd)

        testpf = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        f.name = "Projected"
        f.projectedFits.append(testpf)

        newf = deepcopy(f)
        self.assertEquals(newf.name, "%s copy" % f.name)
        self.assertEquals(newf.character, f.character)
        self.assertEquals(newf.owner, f.owner)

        newm = newf.modules[0]
        self.assertNotEquals(id(newm), id(testm))
        self.assertEquals(len(newf.modules), len(f.modules))

        newpm = newf.projectedModules[0]
        self.assertNotEquals(id(newpm), id(testpm))
        self.assertEquals(len(newf.projectedModules), len(f.projectedModules))

        newd = newf.drones[0]
        self.assertNotEquals(id(newd), id(testd))
        self.assertEquals(len(newf.drones), len(f.drones))

        newb = newf.boosters[0]
        self.assertNotEquals(id(newb), id(testb))
        self.assertEquals(len(newf.boosters), len(f.boosters))

        newi = newf.implants[0]
        self.assertNotEquals(id(newi), id(testi))
        self.assertEquals(len(newf.implants), len(f.implants))

        newpd = newf.projectedDrones[0]
        self.assertNotEquals(id(newpd), id(testpd))
        self.assertEquals(len(newf.projectedDrones), len(f.projectedDrones))

        newpm = newf.projectedModules[0]
        self.assertNotEquals(id(newpm), id(testpm))
        self.assertEquals(len(newf.projectedModules), len(f.projectedModules))

        newpf = newf.projectedFits[0]
        self.assertEquals(id(newpf), id(testpf))
        self.assertEquals(len(newf.projectedFits), len(f.projectedFits))

    def test_repperSustainability(self):
        f = Fit()
        f.ship = Ship(db.getItem("Raven"))
        m = Module(db.getItem("Small Shield Booster I"))
        m.state = State.ACTIVE
        f.modules.append(m)
        f.calculateModifiedAttributes()
        s = f.calculateSustainableTank()
        self.assertEquals(s["armorRepair"], f.extraAttributes["armorRepair"])

    def test_zeroSustainable(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        for i in count(1):
            if i == 5: break
            m = Module(db.getItem("Heavy Energy Neutralizer I"))
            m.state = State.ACTIVE
            f.modules.append(m)

        m = Module(db.getItem("Small Shield Booster I"))
        m.state = State.ACTIVE
        f.modules.append(m)
        f.calculateModifiedAttributes()
        s = f.calculateSustainableTank()
        self.assertEquals(s["armorRepair"], 0)

    def test_sustainabilityConsistency(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        for i in count(1):
            if i == 3: break
            m = Module(db.getItem("Small Shield Booster I"))
            m.state = State.ACTIVE
            f.modules.append(m)

        f.calculateModifiedAttributes()
        s = f.sustainableTank
        self.assertAlmostEquals(s["shieldRepair"], 3.8, 1)

    def test_capCalcs(self):
        f = Fit()
        f.ship = Ship(db.getItem("Reaper"))
        f.ship.itemModifiedAttributes["capacitorCapacity"] = 125.0
        f.ship.itemModifiedAttributes["rechargeRate"] = 93250
        m = Module(db.getItem("Small Shield Booster I"))
        m.state = State.ACTIVE
        f.modules.append(m)
        self.assertAlmostEquals(f.capState, 14.0, 1)

    def test_weaponDPS(self):
        f = Fit()
        m = Module(db.getItem("Heavy Modulated Energy Beam I"))
        m.state = State.ACTIVE
        m.charge = db.getItem("Multifrequency M")
        f.modules.append(m)
        expected = 0
        for type in ("emDamage", "thermalDamage", "kineticDamage", "explosiveDamage"):
            expected += m.getModifiedChargeAttr(type)

        expected *= m.getModifiedItemAttr("damageMultiplier") / (m.getModifiedItemAttr("speed") / 1000.0)
        self.assertAlmostEquals(f.weaponDPS, expected)

    def test_weaponVolley(self):
        f = Fit()
        m = Module(db.getItem("Heavy Modulated Energy Beam I"))
        m.state = State.ACTIVE
        m.charge = db.getItem("Multifrequency M")
        f.modules.append(m)
        expected = 0
        for type in ("emDamage", "thermalDamage", "kineticDamage", "explosiveDamage"):
            expected += m.getModifiedChargeAttr(type)

        expected *= m.getModifiedItemAttr("damageMultiplier")
        self.assertAlmostEquals(f.weaponVolley, expected)

    def test_droneDPS(self):
        f = Fit()
        d = Drone(db.getItem("Hammerhead II"))
        d.active = True
        d.amount = 3
        d.amountActive = 3
        f.drones.append(d)
        expected = 0
        for type in ("emDamage", "thermalDamage", "kineticDamage", "explosiveDamage"):
            expected += d.getModifiedItemAttr(type)

        expected *= d.getModifiedItemAttr("damageMultiplier") / (d.getModifiedItemAttr("speed") / 1000.0)
        self.assertAlmostEquals(f.droneDPS, expected * 3)

    def test_missileDroneDPS(self):
        f = Fit()
        d = Drone(db.getItem("Cyclops"))
        d.active = True
        d.amount = 2
        d.amountActive = 2
        f.drones.append(d)
        expected = 0
        for type in ("emDamage", "thermalDamage", "kineticDamage", "explosiveDamage"):
            expected += d.getModifiedChargeAttr(type)

        expected /= d.getModifiedItemAttr("missileLaunchDuration") / 1000.0
        self.assertAlmostEquals(f.droneDPS, expected * 2)

    def test_hardpointCount(self):
        f = Fit()
        f.modules.append(Module(db.getItem("Heavy Modulated Energy Beam I")))
        f.modules.append(Module(db.getItem("Standard Missile Launcher I")))
        f.modules.append(Module(db.getItem("Salvager I")))
        self.assertEquals(f.getHardpointsUsed(Hardpoint.MISSILE), 1)
        self.assertEquals(f.getHardpointsUsed(Hardpoint.TURRET), 1)

    def test_fill(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        f.fill()
        self.assertEquals(len(f.modules), 13)

    def test_fillT3(self):
        f = Fit()
        f.ship = Ship(db.getItem("Tengu"))
        f.modules.append(Module(db.getItem("Tengu Defensive - Adaptive Shielding")))
        f.clear()
        f.calculateModifiedAttributes()
        f.fill()
        self.assertEquals(len(f.modules), 10)

    def test_fillTooMuchDummies(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        for _ in xrange(5):
            f.modules.append(Module.buildEmpty(Slot.LOW))

        f.fill()
        self.assertEquals(len(f.modules), 13)

    def test_fillOrdering(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        f.fill()
        for i, mod in enumerate(f.modules):
            self.assertEquals(i, mod.position)

    def test_getSlotsUsed(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        f.modules.append(Module(db.getItem("Salvager I")))
        f.fill()
        self.assertEquals(f.getSlotsUsed(Slot.HIGH), 1)

    def test_getCalibrationUsed(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        f.modules.append(Module(db.getItem("Large Trimark Armor Pump I")))
        self.assertEquals(f.calibrationUsed, 50)

    def test_pgUsed(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        f.modules.append(Module(db.getItem("Salvager I")))
        self.assertEquals(f.pgUsed, 1)

    def test_cpuUsed(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        f.modules.append(Module(db.getItem("Salvager I")))
        self.assertEquals(f.cpuUsed, 20)

    def test_droneBandwidthUsed(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        d = Drone(db.getItem("Hobgoblin I"))
        d.amount = 1
        d.amountActive = 1
        f.drones.append(d)
        self.assertEquals(f.droneBandwidthUsed, 5)

    def test_droneBayUsed(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        f.drones.appendItem(db.getItem("Hobgoblin I"))
        self.assertEquals(f.droneBayUsed, 5)

    def test_addRemoveFit(self):
        f = Fit()
        rifter = db.getItem("Rifter")
        f.ship = Ship(rifter)
        f.fill()
        db.saveddata_session.add(f)
        db.saveddata_session.flush()
        db.saveddata_session.delete(f)
        db.saveddata_session.flush()

    def test_removeDrone(self):
        f = Fit()
        gob = db.getItem("Hobgoblin I")
        f.drones.appendItem(gob)
        f.drones.removeItem(gob, 1)

    def test_scanStr(self):
        f = Fit()
        f.ship = Ship(db.getItem("Rifter"))
        self.assertEquals("Ladar", f.scanType)


#!/usr/bin/env python3
"""Asynchronous Advantage Actor-Critic (A3C).
A Fork from: https://github.com/gabrieledcjr/DeepRL
"""
import logging
import numpy as np
import os
import pathlib
import signal
import sys
import threading
import time
import pandas as pd
import math
import tensorflow as tf
import csv

from threading import Event, Thread
from common_worker import CommonWorker
from a3c_training_thread import A3CTrainingThread
from common.game_state import GameState
from common.util import prepare_dir
from common.util import transform_h
from common.util import transform_h_inv
from game_ac_network import GameACFFNetwork
from queue import Queue
from copy import deepcopy
from setup_functions import *

logger = logging.getLogger("a3c")

try:
    import cPickle as pickle
except ImportError:
    import pickle

def run_a3c(args):
    """Run A3C experiment."""
    GYM_ENV_NAME = args.gym_env.replace('-', '_')
    GAME_NAME = args.gym_env.replace('NoFrameskip-v4','')

    # setup folder name and path to folder
    folder = pathlib.Path(setup_folder(args, GYM_ENV_NAME))

    # setup GPU options
    # (NOTE: no gpu support in aeolus)
    import tensorflow as tf
    gpu_options = None

    ######################################################
    # setup default device: cpu
    device = "/cpu:0"

    global_t = 0
    rewards = {'train': {}, 'eval': {}}
    best_model_reward = -(sys.maxsize)

    stop_req = False

    game_state = GameState(env_id=args.gym_env)
    action_size = game_state.env.action_space.n
    game_state.close()
    del game_state.env
    del game_state

    input_shape = (args.input_shape, args.input_shape, 4)

    #######################################################
    # setup global A3C
    GameACFFNetwork.use_mnih_2015 = args.use_mnih_2015
    global_network = GameACFFNetwork(
        action_size, -1, device, padding=args.padding,
        in_shape=input_shape)
    logger.info('A3C Initial Learning Rate={}'.format(args.initial_learn_rate))

    time.sleep(2.0)

    ############## Setup Thread Workers BEGIN ################
    # 16 total number of local threads for all experiments
    assert args.parallel_size ==16

    startIndex = 0
    all_workers = []

    # a3c learning rate and optimizer
    learning_rate_input = tf.placeholder(tf.float32, shape=(), name="opt_lr")
    grad_applier = tf.train.RMSPropOptimizer(
        learning_rate=learning_rate_input,
        decay=args.rmsp_alpha,
        epsilon=args.rmsp_epsilon)

    # setup common workers
    setup_common_worker(CommonWorker, args, action_size)

    # setup a3c workers
    setup_a3c_worker(A3CTrainingThread, args, startIndex)

    for i in range(startIndex, args.parallel_size):
        local_network = GameACFFNetwork(
            action_size, i, device=device,
            padding=args.padding,
            in_shape=input_shape)

        a3c_worker = A3CTrainingThread(
            i, global_network, local_network,
            args.initial_learn_rate, learning_rate_input, grad_applier,
            device=device, no_op_max=30)

        all_workers.append(a3c_worker)
    ############## Setup Thread Workers END ################

    # setup config for tensorflow
    config = tf.ConfigProto(
        gpu_options=gpu_options,
        log_device_placement=False,
        allow_soft_placement=True)

    # prepare sessions
    sess = tf.Session(config=config)
    sess.run(tf.global_variables_initializer())

    # summary writer for tensorboard
    summ_file = args.save_to+'log/a3c/{}/'.format(GYM_ENV_NAME) + str(folder)[12:]
    summary_writer = tf.summary.FileWriter(summ_file, sess.graph)

    # init or load checkpoint with saver
    root_saver = tf.train.Saver(max_to_keep=1)
    saver = tf.train.Saver(max_to_keep=3)
    best_saver = tf.train.Saver(max_to_keep=1)

    checkpoint = tf.train.get_checkpoint_state(str(folder)+'/model_checkpoints')
    if checkpoint and checkpoint.model_checkpoint_path:
        root_saver.restore(sess, checkpoint.model_checkpoint_path)
        logger.info("checkpoint loaded:{}".format(
            checkpoint.model_checkpoint_path))
        tokens = checkpoint.model_checkpoint_path.split("-")

        # restore global step
        global_t = int(tokens[-1])
        logger.info(">>> global step set: {}".format(global_t))

        # restore wall time
        wall_t_fname = folder / 'wall_t'
        with wall_t_fname.open('r') as f:
            wall_t = float(f.read())

        # restore reward files
        best_reward_file = folder / 'model_best/best_model_reward'
        with best_reward_file.open('r') as f:
            best_model_reward = float(f.read())
        reward_file = folder / '{}-a3c-rewards.pkl'.format(GYM_ENV_NAME)
        rewards = pickle.load(reward_file.open('rb'))
    else:
        logger.warning("Could not find old checkpoint")
        # set wall time
        wall_t = 0.0
        prepare_dir(folder, empty=True)
        prepare_dir(folder / 'model_checkpoints', empty=True)
        prepare_dir(folder / 'model_best', empty=True)
        prepare_dir(folder / 'frames', empty=True)

    lock = threading.Lock()

    def next_t(current_t, freq):
        return np.ceil((current_t + 0.00001) / freq) * freq

    next_global_t = next_t(global_t, args.eval_freq)
    next_save_t = next_t(
        global_t, args.eval_freq*args.checkpoint_freq)

    step_t = 0

    last_temp_global_t = global_t

    def train_function(parallel_idx, th_ctr):
        nonlocal global_t, step_t, rewards, lock, next_global_t, \
            next_save_t, last_temp_global_t

        parallel_worker = all_workers[parallel_idx]
        parallel_worker.set_summary_writer(summary_writer)

        with lock:
            # Evaluate model before training
            if not stop_req and global_t == 0 and step_t == 0:
                # Log the reward, and the transformed reward
                reward_t = parallel_worker.testing(sess, args.eval_max_steps, global_t, folder, worker=all_workers[-1])[0]
                trans_reward_t = transform_h(reward_t + 0.99 * transform_h_inv(reward_t))
                rewards['eval'][step_t] = [reward_t, trans_reward_t]
                # save checkpoint
                checkpt_file = folder / 'model_checkpoints'
                checkpt_file /= '{}_checkpoint'.format(GYM_ENV_NAME)
                saver.save(sess, str(checkpt_file), global_step=global_t)
                save_best_model(rewards['eval'][global_t][0])
                # dump reward pickle
                reward_fname = folder / '{}-a3c-rewards.pkl'.format(GYM_ENV_NAME)
                pickle.dump(rewards, reward_fname.open('wb'), pickle.HIGHEST_PROTOCOL)
                logger.info('Dump pickle at step {}'.format(global_t))

                step_t = 1

        # set start_time
        start_time = time.time() - wall_t
        parallel_worker.set_start_time(start_time)

        while True:
            if stop_req:
                return

            if global_t >= (args.max_time_step * args.max_time_step_fraction):
                return

            # a3c training thread worker
            th_ctr.get()

            train_out = parallel_worker.train(sess, global_t, rewards)
            diff_global_t, episode_end, part_end = train_out

            th_ctr.put(1)

            # ensure only one thread is updating global_t at a time
            with lock:
                global_t += diff_global_t
                # if during a thread's update, global_t has reached a evaluation interval
                if global_t > next_global_t:
                    next_global_t = next_t(global_t, args.eval_freq)
                    step_t = int(next_global_t - args.eval_freq)
                    # wait 30min max for all threads to finish before testing,
                    # in case one thread fails
                    time_waited = 0
                    while not stop_req and th_ctr.qsize() < len(all_workers):
                        time.sleep(0.01)
                        time_waited += 0.01
                        if time_waited > 1800:
                            sys.exit('Exceed waiting time, exiting...')

                    step_t = int(next_global_t - args.eval_freq)
                    # test A3C agent
                    reward_t = parallel_worker.testing(sess, args.eval_max_steps, global_t, folder, worker=all_workers[-1])[0]
                    trans_reward_t = transform_h(reward_t + 0.99 * transform_h_inv(reward_t))
                    rewards['eval'][step_t] = [reward_t, trans_reward_t]
                    #print("\n\n\nGLOBAL_T: {}\nREWARD: {}\nTRANS REWARD: {}\ R[EVAL]: {}\n\n\n".format(global_t, reward_t, trans_reward_t, rewards['eval'][step_t]))
                    save_best_model(rewards['eval'][step_t][0])

                if global_t > next_save_t:
                    next_save_t = next_t(global_t, args.eval_freq*args.checkpoint_freq)
                    # save a3c
                    checkpt_file = folder / 'model_checkpoints'
                    checkpt_file /= '{}_checkpoint'.format(GYM_ENV_NAME)
                    saver.save(sess, str(checkpt_file), global_step=global_t,
                            write_meta_graph=False)
                    # dump pickle
                    reward_fname = folder / '{}-a3c-rewards.pkl'.format(GYM_ENV_NAME)
                    pickle.dump(rewards, reward_fname.open('wb'), pickle.HIGHEST_PROTOCOL)
                    logger.info('Dump pickle at step {}'.format(global_t))

    def signal_handler(signal, frame):
        nonlocal stop_req
        logger.info('You pressed Ctrl+C!')
        stop_req = True
        if stop_req and global_t == 0:
            sys.exit(1)

    def save_best_model(test_reward):
        nonlocal best_model_reward
        if test_reward > best_model_reward:
            best_model_reward = test_reward
            best_reward_file = folder / 'model_best/best_model_reward'

            with best_reward_file.open('w') as f:
                f.write(str(best_model_reward))

            best_checkpt_file = folder / 'model_best'
            best_checkpt_file /= '{}_checkpoint'.format(GYM_ENV_NAME)
            best_saver.save(sess, str(best_checkpt_file))

    train_threads = []
    th_ctr = Queue()
    for i in range(args.parallel_size):
        th_ctr.put(1)

    for i in range(args.parallel_size):
        worker_thread = Thread(
            target=train_function,
            args=(i, th_ctr, ))
        train_threads.append(worker_thread)

    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    # set start time and start threads
    start_time = time.time() - wall_t
    for t in train_threads:
        t.start()

    print('Press Ctrl+C to stop')

    # end of training
    for t in train_threads:
        t.join()

    logger.info('Now saving data. Please wait')

    # write wall time
    wall_t = time.time() - start_time
    wall_t_fname = folder / 'wall_t'
    with wall_t_fname.open('w') as f:
        f.write(str(wall_t))

    checkpoint_file = str(folder / '{}_checkpoint_a3c'.format(GYM_ENV_NAME))
    root_saver.save(sess, checkpoint_file, global_step=global_t)

    reward_fname = folder / '{}-a3c-rewards.pkl'.format(GYM_ENV_NAME)
    pickle.dump(rewards, reward_fname.open('wb'), pickle.HIGHEST_PROTOCOL)
    logger.info('Data saved!')

    sess.close()


from datetime import datetime
from dateutil.relativedelta import relativedelta
from itertools import groupby
import json

from django.conf import settings
from django.db.models import Count, Sum
from django.views.generic import DetailView

from healthmeter.hmeter_frontend import models
from ...metrics.constants import get_score_constants
from ...utils.cache import (djcached, cached_property,
                            project_cache_key_template)

from healthmeter.btinfo import models as btmodels
from healthmeter.mlinfo import models as mlmodels
from healthmeter.vcsinfo import models as vcsmodels

class ProjectDetail(DetailView):
    template_name = 'hmeter_frontend/project/detail.html'
    context_object_name = 'project'
    model = models.Project

    month_periods = (3, 6, 9, 12, 24)

    @cached_property
    def projects(self):
        return self.object.all_projects

    @cached_property
    def repositories(self):
        return self.object.all_vcs_repositories.select_related('type') \
                                               .order_by('type__name')

    @cached_property
    def commits(self):
        return vcsmodels.Commit.objects \
                               .filter(repository__in=self.repositories)

    @cached_property
    def bug_namespaces(self):
        return self.object.all_bug_trackers.all() \
                          #.prefetch_related('bug_tracker__bt_type__name')

    @cached_property
    def bugs(self):
        return btmodels.Bug.objects \
                           .filter(tracker_info__in=self.bug_namespaces)

    @cached_property
    def bug_comments(self):
        return btmodels.Comment.objects \
                               .filter(bug__in=self.bugs)

    @cached_property
    def mailing_lists(self):
        return self.object.all_mailing_lists \
                          .order_by('posting_address') \
                          .distinct()

    @cached_property
    def posts(self):
        return mlmodels.Post.objects \
                            .filter(mailing_lists__in=self.mailing_lists)

    @cached_property
    def blogs(self):
        return self.object.all_blogs

    @cached_property
    def limits(self):
        today = datetime.utcnow()
        return [(x, (today - relativedelta(months=x)))
                for x in self.month_periods]

    @staticmethod
    def gen_type_with_count(iterable):
        return ["%s(%d)" % (key, len(list(group)))
                for key, group in groupby(iterable)]

    def gen_periodic_data(self, *fns):
        return [
            [months] + [fn(limit) for fn in fns]
            for months, limit in self.limits
        ]

    def populate_vcsdata(self):
        repositories = self.repositories
        self.data['vcs_repository_types'] = self.gen_type_with_count(
            x.type.name for x in repositories)

        self.data['vcs_repository_urls'] = [x.url for x in repositories]

        commits = self.commits
        self.data['commit_count_period'] = self.gen_periodic_data(
            lambda limit: commits.filter(timestamp__gte=limit).count(),
            lambda limit: (commits.filter(timestamp__gte=limit)
                           .distinct('author').count()))

        head_commits = commits.filter()
        current_sloc = (head_commits.aggregate(sloc=Sum('line_count'))['sloc']
                        or 0)
        ancestors_lists = []
        sloc_count_period = self.data['sloc_count_period'] = []
        for months, limit in self.limits:
            total_sloc_at_limit = 0
            for ancestors in ancestors_lists:
                if not ancestors:
                    continue
                try:
                    sloc_at_limit = vcsmodels.Commit.objects \
                        .filter(id__in=ancestors, timestamp__gte=limit) \
                        .order_by('timestamp')[:1][0].line_count

                except IndexError:
                    # no commits later than limit, so pick latest commit
                    try:
                        sloc_at_limit = vcsmodels.Commit.objects \
                                                 .filter(id__in=ancestors) \
                                                 .latest('timestamp') \
                                                 .line_count
                    except:
                        continue

                total_sloc_at_limit += sloc_at_limit
            sloc_count_period.append([months,
                                      current_sloc - total_sloc_at_limit])

        committer_domains = models.EmailDomain.objects \
            .filter(addresses__owner__committer_ids__commits__in=commits) \
            .with_commit_count() \
            .filter(commit_count__gt=0)

        self.data['commit_domain_breakdown'] = [
            (x['domain'], x['commit_count'], x['address_count'])
            for x in committer_domains
        ]

    def populate_releases(self):
        try:
            self.data['latest_release'] = self.object.all_releases \
                                                     .order_by('-date')[:1][0]
        except IndexError:
            pass

    def populate_btdata(self):
        bugnamespaces = self.bug_namespaces

        self.data['bug_tracker_types'] = self.gen_type_with_count(
            x.bug_tracker.bt_type.name for x in bugnamespaces)

        self.data['bug_tracker_namespaces'] = list(bugnamespaces)

        # Subquery needed to avoid capturing comments 2..N, because we only
        # want the first comment of each bug.
        firstcomments = btmodels.Comment.objects.filter(
            id__in=self.bug_comments.distinct('bug'))
        bugs = self.bugs

        self.data['bugs_opened_count_period'] = self.gen_periodic_data(
            lambda limit: firstcomments.filter(timestamp__gte=limit).count())
        self.data['severe_bugs_count_period'] = self.gen_periodic_data(
            lambda limit: firstcomments.filter(
                timestamp__gte=limit,
                bug__severity__level__gte=3).count())
        self.data['bugs_closed_count_period'] = self.gen_periodic_data(
            lambda limit: bugs.filter(close_date__gte=limit).count())

        domains = models.EmailDomain.objects \
            .filter(addresses__owner__bug_comments__in=firstcomments) \
            .with_btcomment_count() \
            .filter(btcomment_count__gt=0)
        self.data['bug_reports_domain_breakdown'] = [
            (x['domain'], x['btcomment_count'], x['address_count'])
            for x in domains
        ]

    def populate_mldata(self):
        mailing_lists = self.mailing_lists
        self.data['mailing_lists'] = mailing_lists
        self.data['mailing_list_count'] = len(mailing_lists)

        posts = self.posts
        self.data['mail_count_period'] = self.gen_periodic_data(
            lambda limit: posts.filter(timestamp__gte=limit).count(),
            lambda limit: (posts.filter(timestamp__gte=limit)
                           .distinct('author').count()))

        domains = models.EmailDomain.objects \
            .filter(addresses__owner__mailing_list_posts__in=posts) \
            .with_mlpost_count() \
            .filter(mlpost_count__gt=0)
        self.data['mlpost_domain_breakdown'] = [
            (x['domain'], x['mlpost_count'], x['address_count'])
            for x in domains
        ]

    def populate_miscdata(self):
        self.data['start_date'] = self.object.smart_start_date
        self.data['end_date'] = self.object.last_updated
        self.data['hldomain'] = ''

    def _populate_listdata_with_count(self, basename, items):
        self.data[basename + 's'] = items
        self.data[basename + '_count'] = len(items)

    def populate_blogdata(self):
        self._populate_listdata_with_count('blog', self.blogs)

    def populate_metricinfo(self):
        score_constants = get_score_constants()

        self.data['metric_score_constants'] = json.dumps({
            'yg_boundary': score_constants.yg_boundary,
            'ry_boundary': score_constants.ry_boundary
        })

        # TODO: Pull this out of MetricCache instead
        self.data['score_tree'] = self.object.score

    def __gen_detail_cache_key(self):
        return project_cache_key_template.format(id=self.object.id,
                                                 key='detail_data')

    @djcached(__gen_detail_cache_key, 24 * 3600)
    def get_projdata(self):
        self.data = {
            'project': self.object,
            'subprojects_count': self.projects.count() - 1,
            'pending_subprojects_count': 0,  # FIXME
        }

        self.populate_releases()
        self.populate_vcsdata()
        self.populate_btdata()
        self.populate_mldata()
        self.populate_miscdata()
        self.populate_blogdata()
        self.populate_metricinfo()

        return self.data

    def get_context_data(self, **kwargs):
        data = super(ProjectDetail, self).get_context_data(**kwargs)
        data.update(self.get_projdata())

        return data


import argparse

from download_tiktok_url import download_tiktok_url
from urls_finder import getUrlsFromUserName

parser = argparse.ArgumentParser(description='Download all tiktok videos from a user OR Download a single video from a tiktok url')
parser.add_argument('-u','--user',
                    help='user to download videos from', default=None)
parser.add_argument('-v','--videoUrl',
                    help='url of the video to download', default=None)
parser.add_argument('-o','--output',
                    help='name convention of the ouput, for example : `-o video` will name the videos `video_1.mp4, video_2.mp4, ..., default is \'video\'',
                    default='video')
parser.add_argument('--destination', '-d',
                    default='.',
                    help='destination folder, default is \'.\' (current folder)')

args = parser.parse_args()

USER = args.user
DESTINATION_FOLDER = args.destination
OUTPUT_NAME = args.output
VIDEO_URL = args.videoUrl

# 1 - Retrieve the list of urls from the user page
if USER and VIDEO_URL:
    raise Exception("You can't use -u and -v at the same time")
if USER is not None:
    urls = getUrlsFromUserName(USER, DESTINATION_FOLDER)
elif VIDEO_URL is not None:
    urls = [VIDEO_URL]
else:
    raise Exception("You must specify either a user or a video url")

# 2 - Download the videos from the list of urls and store them in the destination folder

for i in range(len(urls)):
    download_tiktok_url(urls[i], i, DESTINATION_FOLDER, OUTPUT_NAME)


import numpy as np

COMET_MODEL = "wmt20-comet-da"
COMET_BATCH_SIZE = 64

BLEURT_BATCH_SIZE = 64

def comet(hyps, refs, srcs, comet_dir=None):
    from comet import download_model, load_from_checkpoint

    # download comet and load
    comet_path = download_model(COMET_MODEL, comet_dir)
    comet_model = load_from_checkpoint(comet_path)
    comet_input = [
        {"src": src, "mt": mt, "ref": ref} for src, mt, ref in zip(srcs, hyps, refs)
    ]
    # sentence-level and corpus-level COMET
    return comet_model.predict(
        comet_input, batch_size=COMET_BATCH_SIZE, sort_by_mtlen=True
    )

def bleurt(hyps, refs, srcs=None, bleurt_dir=None):
    from bleurt import score

    bleurt_scorer = score.LengthBatchingBleurtScorer(bleurt_dir)
    bleurt_scores = bleurt_scorer.score(
        references=refs, candidates=hyps, batch_size=BLEURT_BATCH_SIZE
    )
    assert type(bleurt_scores) == list
    return bleurt_scores, np.array(bleurt_scores).mean()

def bleu(hyps, refs, srcs=None):
    import sacrebleu

    sentence_scores = [
        sacrebleu.sentence_bleu(ref, [hyp]).score for hyp, ref in zip(hyps, refs)
    ]
    corpus_score = sacrebleu.corpus_bleu(refs, [hyps]).score
    return sentence_scores, corpus_score


import multiprocessing, os, threading

def receptor():
    x = 0
    with open(fifo_1, "r") as fifo:
        lineas = fifo.readlines()
        lineas = [linea.strip() for linea in lineas]
        for linea in lineas:
            hilo = threading.Thread(target=funcion_del_hilo, args=(linea,))
            hilo.start()
            x += 1
            if x != 1:
                hilo.join()

def funcion_del_hilo(linea):
    numero_de_caracteres = len(linea)
    print(f"La linea {linea} tiene {numero_de_caracteres} caracteres")

if __name__ == '__main__':

    fifo_1 = "mi_fifo"

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

    os.mkfifo(fifo_1)

    proceso_2 = multiprocessing.Process(target=receptor)
    proceso_2.start()


import pytest
from selenium import webdriver
from .settings import console_logger

@pytest.fixture(scope="function")
def browser():
    try:
        console_logger.debug('Start browser')
        browser = webdriver.Chrome()
        browser.maximize_window()
        browser.implicitly_wait(10)
        yield browser
        console_logger.debug('Quit browser')
        browser.quit()
    except:
        console_logger.exception('Something wrong this browser fixture')

class ValueStorage:
    remembered_phone = None
    remembered_phone_rating = None