Exemple #1
0
def is_double(s):
    """
    判断是否是浮点数类型
    """
    try:
        double(s)
        return True
    except (TypeError, ValueError):
        return False
Exemple #2
0
def return_winner():
    sepal_length_cm = request.form['SepalLengthCm']
    sepal_width_cm = request.form['SepalWidthCm']
    petal_length_cm = request.form['PetalLengthCm']
    petal_width_cm = request.form['PetalWidthCm']
    print(sepal_length_cm,
          sepal_width_cm,
          petal_length_cm,
          petal_width_cm,
          file=sys.stderr)
    return get_predictions(double(sepal_length_cm), double(sepal_width_cm),
                           double(petal_length_cm), double(petal_width_cm))
Exemple #3
0
def fetch_from_db_amt(name1, name2):
    cur = mydb.cursor()
    # print(name_text)
    sql4 = "SELECT * FROM `details` WHERE `Trans_amt` BETWEEN %f AND %f"
    # print(type(name_text))
    name = []
    name.append(double(name1))
    name.append(double(name2))

    cur.execute(sql4, name)
    records = cur.fetchall()
    mydb.commit()
    return records
Exemple #4
0
def eps_1():
    eps_comp = single(1)
    eps = single(0.1)
    eps_old = single(0)
    while eps_comp + eps > eps_comp:
        eps_old = single(eps)
        eps = eps * single(0.5)
    print('Машинный эпсилон одинарной точности:', eps_old)

    eps_comp_2 = double(36)
    eps_2 = double(0.1)
    while eps_comp_2 + eps_2 > eps_comp_2:
        eps_old_2 = eps_2
        eps_2 = eps_2 * 0.5
    print('Машинный эпсилон двойной точности:', eps_old_2)
Exemple #5
0
    def setValue(self, strValue, nodeStruct):
        """
        Метод проверяет тип данных значения и устанавливает соответствующий тип данных

        :param: strValue: строка для парсера

        :return: nodeStruct: заполненная структура узла

        """
        i_status = self.OK
        if isinstance(strValue, int):
            nodeStruct.o_obj.i_typeData = self.dict_typeData["Integer"]
            nodeStruct.o_obj.d_value = int(strValue)
        elif isinstance(strValue, float):
            nodeStruct.o_obj.i_typeData = self.dict_typeData["Float"]
            nodeStruct.o_obj.d_value = float(strValue)
        elif isinstance(strValue, bool):
            nodeStruct.o_obj.i_typeData = self.dict_typeData["Boolean"]
            nodeStruct.o_obj.d_value = bool(strValue)
        elif isinstance(strValue, dict):
            nodeStruct.o_obj.i_typeData = self.dict_typeData["Dict"]
            nodeStruct.o_obj.d_value = dict()
        elif isinstance(strValue, str):
            nodeStruct.o_obj.i_typeData = self.dict_typeData["Double"]
            nodeStruct.o_obj.d_value = double(strValue.replace(',', '.'))
        else:
            nodeStruct.o_obj.i_typeData = self.dict_typeData["Object"]
            nodeStruct.o_obj.d_value = bytearray(strValue, "utf-8")

        return nodeStruct
Exemple #6
0
    def setValueNodeStruct(self, strValue):
        """
        Метод проверяет тип данных значения и устанавливает соответсвующий тип данных

        :param: strValue: строка для парсера

        :return: * i_typeData: тип данных описание см. в классификаторе
                * d_value: значение тэга узла

        """
        i_typeData = 0
        d_value = 0
        if isinstance(strValue, int):
            i_typeData = self.dict_typeData["Integer"]
            d_value = int(strValue)
        elif isinstance(strValue, float):
            i_typeData = self.dict_typeData["Float"]
            d_value = float(strValue)
        elif isinstance(strValue, bool):
            i_typeData = self.dict_typeData["Boolean"]
            d_value = bool(strValue)
        elif isinstance(strValue, dict):
            i_typeData = self.dict_typeData["Dict"]
            d_value = dict()
        elif isinstance(strValue, str):
            i_typeData = self.dict_typeData["Double"]
            d_value = double(strValue.replace(',', '.'))
        else:
            i_typeData = self.dict_typeData["Object"]
            d_value = bytearray(strValue, "utf-8")

        return i_typeData, d_value
    def delete_patient(self):
        mydb = mysql.connector.connect(
            host="localhost",
            user="******",
            password="",
            database="petctdb"
        )
        mycursor = mydb.cursor()
        pat_id = self.patientIdEdit.text()

        qm = QMessageBox()
        qm.setWindowTitle("Delete patient")
        ret = qm.question(self, '', "Are you sure you want to delete this patient?", qm.Yes | qm.No)
        if ret == qm.Yes:
            if (self.patientIdEdit.text() != ''):
                sql = "update patient set active=0 where pat_id =" + pat_id
                mycursor.execute(sql)
                mydb.commit()
                msg = QMessageBox()
                msg.setWindowTitle("Successful delete")
                msg.setWindowIcon(QIcon("icons8-system-task-40.png"))
                msg.setText("Patient successfully deleted!")
                msg.setIcon(QMessageBox.Information)
                msg.exec_()

        self.surnameEdit.setText(str(""))
        self.nameEdit.setText(str(""))
        self.ssnEdit_2.setText(str(""))
        self.ssnEdit.setText(str(""))
        self.maleRadioButton.setChecked(False)
        self.femaleRadioButton.setChecked(False)

        bdate = '01/01/2000'
        format_str = '%d/%m/%Y'
        datetime_obj = datetime.datetime.strptime(bdate, format_str)

        weightd = '0.0'
        heightd = '0.0'

        self.bdateEdit.setDate(datetime_obj)
        self.weightSpinBox.setValue(double(weightd))
        self.heightSpinBox.setValue(double(heightd))
        self.adressEdit.setText(str(""))
        self.phoneEdit.setText(str(""))
        self.emailEdit.setText(str(""))
        self.patientIdEdit.setText(str(""))
Exemple #8
0
def create_custom_tiling_node(tile_mode,
                              tile_level=TileLevel.C1,
                              tensor_name=DEFAULT_STRING,
                              tile_pos=DEFAULT_VALUE,
                              tile_band=DEFAULT_VALUE,
                              tile_axis=DEFAULT_VALUE,
                              tile_min=DEFAULT_VALUE,
                              tile_max=DEFAULT_VALUE,
                              tile_mod=DEFAULT_VALUE,
                              tile_factor=DEFAULT_VALUE,
                              tile_candidate=DEFAULT_VALUE,
                              forbid_isolate=DEFAULT_VALUE,
                              axis_info=DEFAULT_STRING,
                              priority=DEFAULT_VALUE,
                              expansion=DEFAULT_VALUE,
                              mem_ratio=double(DEFAULT_VALUE),
                              thread_min=[],
                              thread_max=[],
                              thread_mod=[],
                              block_min=[],
                              block_max=[],
                              block_mod=[]):
    """default method to create custom tiling node, all values are default except tile mode."""

    tile_min = to_tvm_type(tile_min, "tile_min")
    tile_max = to_tvm_type(tile_max, "tile_max")
    tile_mod = to_tvm_type(tile_mod, "tile_mod")
    tile_factor = to_tvm_type(tile_factor, "tile_factor")
    tile_candidate = to_tvm_type(tile_candidate, "tile_candidate")
    return akg.tvm.make.node(NODE_TYPE,
                             tile_level=akg.tvm.expr.StringImm(
                                 tile_level.value),
                             tile_mode=akg.tvm.expr.StringImm(tile_mode.value),
                             tensor_name=akg.tvm.expr.StringImm(tensor_name),
                             tile_pos=tile_pos,
                             tile_band=tile_band,
                             tile_axis=tile_axis,
                             tile_min=tile_min,
                             tile_max=tile_max,
                             tile_mod=tile_mod,
                             tile_factor=tile_factor,
                             tile_candidate=tile_candidate,
                             forbid_isolate=forbid_isolate,
                             axis_info=akg.tvm.expr.StringImm(axis_info),
                             priority=priority,
                             expansion=expansion,
                             mem_ratio=mem_ratio,
                             thread_min=thread_min,
                             thread_max=thread_max,
                             thread_mod=thread_mod,
                             block_min=block_min,
                             block_max=block_max,
                             block_mod=block_mod)
Exemple #9
0
def modify_common_constraints(value, constraint, level=TileLevel.C1):
    """api for dsl to modify some default constraint used in auto tiling."""
    if constraint not in TileConstraint:
        raise ValueError(
            "Tile constraints must be chosen from {0}".format(TileConstraint))
    if constraint == TileConstraint.SET_MEM_RATIO:
        return create_custom_tiling_node(TileMode.COMMON,
                                         tile_level=level,
                                         mem_ratio=double(value))
    raise TypeError(
        "Constraint {} is not supported in this api, please use other api".
        format(constraint.value))
Exemple #10
0
def mult_1():
    #for alfa in range(-10, 10):
    for beta in range(-10, 20):
        alfa = -10
        mas_a = massive_1(alfa)
        mas_b = massive_2(beta)
        result_1 = single(0)
        result_2 = double(0)
        for i in range(1, len(mas_a)):
            result_1 = single(result_1 + (single(mas_a[i]) * single(mas_b[i])))
            result_2 = double(result_2 + (double(mas_a[i]) * double(mas_b[i])))
        #print(result_1, result_2)
        if result_1 != single(8779):
            print('Одинарная точность:')
            print(f'{beta}//{single(8779) - result_1}')
        else:
            print(f'{beta}//{single(8779) - result_1}')
        if result_2 != double(8779):
            print('Двойная точность:')
            print(f'{beta} // {double(8779) - result_2}')
        else:
            print(f'{beta} //{double(8779) - result_2}')
    def patient_table_cell_was_clicked(self , row_number):
        try:
            patient_id = self.patientTable.item(row_number, 0).text()
            lastname = self.patientTable.item(row_number ,1).text()
            name = self.patientTable.item(row_number ,2).text()
            amka = self.patientTable.item(row_number ,3).text()
            sex = self.patientTable.item(row_number, 4).text()
            if sex=='male':
                self.maleRadioButton.setChecked(True)
            if sex == 'female':
                self.femaleRadioButton.setChecked(True)

            datebirth = self.patientTable.item(row_number, 5).text()
            weight = self.patientTable.item(row_number, 6).text()
            height = self.patientTable.item(row_number, 7).text()
            bmi = self.patientTable.item(row_number, 8).text()
            address =   self.patientTable.item(row_number, 9).text()
            phone =   self.patientTable.item(row_number, 10).text()
            email  = self.patientTable.item(row_number, 11).text()
        except AttributeError:
            pass

        try:
            self.patientIdEdit.setText(str(patient_id))
            self.surnameEdit.setText(str(lastname))
            self.nameEdit.setText(str(name))
            self.ssnEdit_2.setText(str(amka))
            format_str = '%d/%m/%Y'
            datetime_obj = datetime.datetime.strptime(datebirth, format_str)
            self.bdateEdit.setDate(datetime_obj)
            self.weightSpinBox.setValue(double(weight))
            self.heightSpinBox.setValue(double(height))
            self.adressEdit.setText(str(address))
            self.phoneEdit.setText(str(phone))
            self.emailEdit.setText(str(email))
            self.ssnEdit_3.setText(str(amka))
        except UnboundLocalError:
            pass
    def clear_fields(self):
        self.surnameEdit.setText(str(""))
        self.nameEdit.setText(str(""))
        self.ssnEdit_2.setText(str(""))
        self.ssnEdit.setText(str(""))

        self.maleRadioButton.setChecked(False)
        self.femaleRadioButton.setChecked(False)

        bdate = '01/01/2000'
        format_str = '%d/%m/%Y'
        datetime_obj = datetime.datetime.strptime(bdate, format_str)

        weightd = '0.0'
        heightd = '0.0'

        self.bdateEdit.setDate(datetime_obj)
        self.weightSpinBox.setValue(double(weightd))
        self.heightSpinBox.setValue(double(heightd))
        self.adressEdit.setText(str(""))
        self.phoneEdit.setText(str(""))
        self.emailEdit.setText(str(""))
        self.patientIdEdit.setText(str(""))
Exemple #13
0
    def set_val_obj_old(self, list_objs, id_Obj, name_field, value=0):
        """
        метод присваивает значения объектам внустри узла

        :param: * list_obj: список объектов внутри узла
                * id_Obj: идентификатор объекта внутри узла
                * name_filed: имя поля в словаре которое указывает на переменную
                * value: значение является необязательныйм параметром

        :return: * i_status: код ошибки
                * list_objs-список объектов

        """
        i_status = PLCGlobals.SET_VAL_FAIL
        length = len(list_objs)
        for i in range(length):
            if list_objs[i]['h_idObj'] == id_Obj:
                for case in switch(name_field):
                    if case("h_idObj"):
                        # i_status меняет свое предназначение на индекс в списке
                        i_status = i
                        return i_status, list_objs
                    if case("h_idSubObj"):
                        list_objs[i]["h_idSubObj"] = int(value)
                        i_status = PLCGlobals.SET_VAL_OK
                        break
                    if case("i_typeData"):
                        list_objs[i]["i_typeData"] = int(value)
                        i_status = PLCGlobals.SET_VAL_OK
                        break
                    if case("d_value"):
                        list_objs[i]["d_value"] = double(value)
                        i_status = PLCGlobals.SET_VAL_OK
                        break
                    if case("b_message"):
                        length, list_objs[i]["b_message"] = \
                            self.mesPacked.setB_message(self.mesPacked.OK,
                                                        self.mesPacked.nodeStruct)
                        i_status = PLCGlobals.SET_VAL_OK
                        break
                    if case("i_check"):
                        list_objs[i]["i_check"] = self.mesPacked.set_CRC(self.mesPacked.nodeStruct)
                        i_status = PLCGlobals.SET_VAL_OK
                        break
        if i_status == PLCGlobals.SET_VAL_FAIL and "h_idObj" in name_field:
            self.set_dict_val_obj("h_idObj", value)
            list_objs=self.add_item_objs(self.dict_objs,list_objs)
        return i_status, list_objs
Exemple #14
0
def modify_common_constraints(value, constraint, level=TileLevel.C1):
    """api for dsl to modify some default constraint used in auto tiling."""
    _check_constraint(constraint)
    if constraint == TileConstraint.SET_MEM_RATIO:
        return create_custom_tiling_node(TileMode.COMMON,
                                         tile_level=level,
                                         mem_ratio=double(value))
    if constraint == TileConstraint.THREAD_MIN:
        return create_custom_tiling_node(TileMode.COMMON, thread_min=value)
    if constraint == TileConstraint.THREAD_MAX:
        return create_custom_tiling_node(TileMode.COMMON, thread_max=value)
    if constraint == TileConstraint.THREAD_MOD:
        return create_custom_tiling_node(TileMode.COMMON, thread_mod=value)
    if constraint == TileConstraint.BLOCK_MIN:
        return create_custom_tiling_node(TileMode.COMMON, block_min=value)
    if constraint == TileConstraint.BLOCK_MAX:
        return create_custom_tiling_node(TileMode.COMMON, block_max=value)
    if constraint == TileConstraint.BLOCK_MOD:
        return create_custom_tiling_node(TileMode.COMMON, block_mod=value)
    raise TypeError(
        "Constraint {} is not supported in this api, please use other api".
        format(constraint.value))
Exemple #15
0
from numpy.core import double

i = 4
d = 4.0
s = 'HackerRank '
a = int(input())
b = double(input())
c = input()
print(i+a)
print(d+b)
print(s+c)
Exemple #16
0
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
# ==========================================================================*/

import itk
from numpy.core import double

Dimension = 3
CoordType = itk.D

VectorType = itk.Vector[CoordType, Dimension]

u = VectorType()
u[0] = -1.0
u[1] = 1.0
u[2] = -1.0

v = VectorType()
v[0] = 1.0
v[1] = 2.0
v[2] = 3.0

print("u: " + str(u))
print("v: " + str(v))
print("DotProduct( u, v ) = " + str(u * v))
print("DotProduct( u, v ) = " + str(u - double(u * v) * v))
Exemple #17
0
def query():
    """
    price = request.form.get("price")
    discount = request.form.get("discount")
    name_id = request.form.get("name_id")
    #user = Users.query.filter(Users.id == name_id).all()
    """
    # 接收前端发来的数据
    # data = json.loads(request.form.get('data'))
    # 接收http发送来的数据
    data = request.get_json()

    buy = False
    account = None
    try:
        if data['name_id'] is None or data['price'] is None:
            '''参数缺失'''
            result = "10"
        else:
            '''a、b参数均不缺失'''
            name_id = data['name_id']
            if name_id == "":
                '''c参数为空'''
                result = "40"
                # error_msg = "empty params"
            elif type(name_id) == str:
                '''c参数参数是字符串类型'''
                if 32 >= len(name_id) >= 3:
                    '''c参数长度符合条件'''
                    user = User.query.filter(User.name_id == name_id).first()
                    if user is None:
                        '''c用户不存在'''
                        result = "90"
                        # error_msg = "not exist"
                    else:
                        '''c用户存在'''
                        balance = user.balance
                        if data["price"] == "":
                            '''a参数值为空'''
                            result = "40"
                            account = user.balance
                            # error_msg = "empty params"
                        elif is_double(data['price']):
                            '''a参数为double类型'''
                            price = Decimal.from_float(data['price'])
                            if price > decimal.MAX_PREC or price < 0.0:
                                '''a参数超过范围'''
                                result = "60"
                                account = balance
                                return jsonify({
                                    'result': result,
                                    'buy': buy,
                                    'account': double(account)
                                })
                            else:
                                '''a参数正常'''
                                if data["discount"] == "":
                                    '''b参数为空'''
                                    discount = Decimal.from_float(1.0)
                                elif data["discount"] is None:
                                    '''b参数缺失'''
                                    result = "10"
                                    account = balance
                                    return jsonify({
                                        'result': result,
                                        'buy': buy,
                                        'account': double(account)
                                    })
                                elif is_double(data["discount"]):
                                    '''b参数为double类型'''
                                    discount = Decimal.from_float(
                                        data["discount"])
                                    if discount < 0.0 or discount > 1.0:
                                        '''b参数取值不在范围内'''
                                        result = "70"
                                        account = balance
                                        return jsonify({
                                            'result':
                                            result,
                                            'buy':
                                            buy,
                                            'account':
                                            double(account)
                                        })
                                else:
                                    '''b参数为非double类型'''
                                    result = "50"
                                    account = balance
                                    return jsonify({
                                        'result': result,
                                        'buy': buy,
                                        'account': double(account)
                                    })

                                if is_enough(price, discount, balance):
                                    '''余额足够'''
                                    result = "0"
                                    buy = True
                                    account = price.fma(-discount, balance)
                                    # error_msg = 'success'
                                else:
                                    '''余额不足'''
                                    result = '100'
                                    account = balance
                                    # error_msg = "not enough"
                        else:
                            '''a参数类型错误,非double类型'''
                            result = "50"
                            account = balance
                else:
                    '''c参数长度越界'''
                    result = "80"
                    # error_msg = "out of range"
            else:
                '''c参数非字符串类型'''
                result = "50"
    except KeyError:
        result = "10"
    return jsonify({'result': result, 'buy': buy, 'account': double(account)})
from numpy.core import double
from pip._vendor.distlib.compat import raw_input

Celsius = double(raw_input("Enter a temperature in Celsius: "))
Fahrenheit = 9.0 / 5.0 * Celsius + 32
print("Temperature:", Celsius, "Celsius = ", Fahrenheit, " F")