Beispiel #1
0
 def parse_kornkraft(self,lines):
     self.date = None
     self.no = None
     for vat in self.vat_rates:
         self.vat[vat] = 0
         self.totals[vat] = 0
     vat_rate_strs = ["{:.2f}".format(r).replace(".",",") for r in self.vat_rates]
     for line in lines:
         words = line.split()
         if not self.date:
             for i in range(len(words)):
                 self.date = utils.convert_date4(words[i])
                 if self.date:
                     self.no = words[i-2]
                     break
         else:
             if len(words)>12:
                 words = [w.replace('*','') for w in words]
                 for vat in vat_rate_strs:
                     if vat in words[0:6]:
                         #print(list(zip(words,range(len(words)))))
                         vat = utils.read_float(vat)
                         self.vat[vat] = utils.read_float(words[-4])
                         self.totals[vat] = utils.read_float(words[-2]) - self.vat[vat]
                         break
     #print(self.date,self.no,self.vat,self.totals)
     self.items = []
     self.shipping = 0.0
     self.compute_total()
     self.assign_default_e_items(KORNKRAFT_ACCOUNTS)
Beispiel #2
0
 def read_sparda_ethik(self,infile,is_sparda=True):
     blz = None
     baccount_no = None
     r = 0 if is_sparda else 1
     for row in utils.get_csv('iso-8859-4',infile,replacenl=is_sparda):
         if not row:
             continue
         if row[0]=='BLZ:':
             blz = int(row[1])
             continue
         if row[0]=='Konto:':
             baccount_no = int(row[1])
             continue
         date = utils.convert_date4(row[0])
         if not date:
             continue
         if row[9+r]=='Anfangssaldo':
             self.sbal = utils.read_float(row[11+r],row[12+r])
             continue
         if row[9+r]=='Endsaldo':
             self.ebal = utils.read_float(row[11+r],row[12+r])
             continue
         be = BankStatementEntry(self)
         be.posting_date = date
         be.purpose = row[8+r]
         be.partner = row[3+r]
         be.partner_iban = row[5+r]
         be.amount = utils.read_float(row[11+r],row[12+r])
         be.cleanup()
         self.entries.append(be)
     if blz and baccount_no:
         self.iban = utils.iban_de(blz,baccount_no)
Beispiel #3
0
 def parse_pvxchange(self,lines):
     items = []
     item = []
     preamble = True
     self.date = None
     self.no = None
     for line in lines:
         if "Bremen, den" in line:
             self.date = utils.convert_date4(line.split()[2])
         elif "Bremen," in line:
             self.date = utils.convert_date4(line.split()[1])
         if line[0:8] == "Rechnung":
             if len(line.split())>1:
                 self.no = line.split()[2]
         if preamble:
             if len(line)>=4 and line[0:4]=="Pos.":
                 preamble = False
             continue
         if len(line)>=5 and line[0:5]=="Seite":
             preamble = True
             continue
         try:
             pos_no = int(line.split()[0])
         except Exception:
             pos_no = -1
         if pos_no == 28219:
             break
         if pos_no>=0 or 'Nettosumme' in line:
             items.append(item)
             item = [line]
         else:
             item.append(line)
     items.append(item)
     self.items = []
     mypos = 0
     for item_lines in items[1:-1]:
         parts = " ".join(map(lambda s: s.strip(),item_lines)).split()
         s_item = SupplierItem(self)
         s_item.qty = int(parts[1])
         s_item.rate = utils.read_float(parts[-4])
         s_item.amount = utils.read_float(parts[-2])
         s_item.qty_unit = "Stk"
         s_item.description = " ".join(parts[2:-4])
         s_item.long_description = s_item.description
         try:
             ind = parts.index('Artikelnummer:')
             s_item.item_code = parts[ind+1]
         except Exception:
             s_item.item_code = None
         if not (s_item.description=="Selbstabholer" and s_item.amount==0.0):
             self.items.append(s_item)
     self.shipping = 0.0
     vat_line = [line for line in items[-1] if 'MwSt' in line][0]
     self.vat[self.default_vat] = utils.read_float(vat_line.split()[-2])
     total_line = [line for line in items[-1] if 'Nettosumme' in line][0]
     self.totals[self.default_vat] = utils.read_float(total_line.split()[-2])
     self.compute_total()
Beispiel #4
0
def choose_section():
    left = utils.read_float(-sys.float_info.max, sys.float_info.max,
                            "Введите левую границу а")
    while True:
        right = utils.read_float(-sys.float_info.max, sys.float_info.max,
                                 "Введите правую границу b")
        if right < left:
            print("Извините, правая граница не может быть левее левой границы")
            continue
        else:
            break
    return left, right
def decode_line_foreign_wild(line):
  """Decode the line to tensor. Foreign shadow generation using images in the wild. Each line has 7 fields."""
  data_dict = {}
  record_defaults = [''] * 7
  items = tf.io.decode_csv(line, record_defaults, field_delim=',')
  data_dict['image_path'] = items[0]
  data_dict['silhouette_path'] = items[2]
  data_dict['bbox'] = [tf.strings.to_number(items[3], tf.float32),
                       tf.strings.to_number(items[4], tf.float32),
                       tf.strings.to_number(items[5], tf.float32),
                       tf.strings.to_number(items[6], tf.float32)]

  data_dict['shadowed_before'] = utils.read_float(items[0], channel=3, itype='jpg', is_linear=True)
  data_dict['segmentation'] = utils.read_float(items[1], channel=1, itype='png', is_linear=False)
  data_dict['silhouette'] = utils.read_float(items[2], channel=1, itype='png', is_linear=False)

  return data_dict
Beispiel #6
0
 def parse_nkk(self,lines):
     self.date = None
     self.no = None
     for line in lines:
         words = line.split()
         if not self.date:
             for i in range(len(words)):
                 self.date = utils.convert_date4(words[i])
                 if self.date:
                     self.no = words[i-1]
                     break
         elif words:
             for vat in self.vat_rates:
                 vatstr = "{:.2f}%".format(vat).replace(".",",")
                 if words[0]==vatstr:
                     self.vat[vat] = utils.read_float(words[5])
                     self.totals[vat] = utils.read_float(words[1])+\
                                        utils.read_float(words[3])
     self.items = []
     self.shipping = 0.0
     self.compute_total()
     self.assign_default_e_items(NKK_ACCOUNTS)
Beispiel #7
0
 def read_sparkasse(self,infile):
     first_row = True
     for row in utils.get_csv('iso-8859-4',infile):
         if not row:
             continue
         if first_row:
             first_row = False
             continue
         be = BankStatementEntry(self)
         self.iban = row[0]
         be.posting_date = utils.convert_date2(row[1])
         be.purpose = row[4]
         be.partner = row[11]
         be.partner_iban = row[12]
         be.amount = utils.read_float(row[14])
         be.cleanup()
         self.entries.append(be)
Beispiel #8
0
def show(x, y, b, c, d, function):
    points = []
    while True:
        k = 1
        spline_y = []
        fun_x = np.arange(x[0], x[len(x) - 1], (x[len(x) - 1] - x[0]) / 1000)
        fun_y = function(fun_x)
        plt.plot(fun_x, fun_y, label="Выбранная функция")
        for i in fun_x:
            if i <= x[k]:
                spline_value = y[k] + b[k] * (i - x[k]) + c[k] * (
                    i - x[k])**2 + d[k] * (i - x[k])**3
                spline_y.append(spline_value)
            else:
                spline_value = y[k] + b[k] * (i - x[k]) + c[k] * (
                    i - x[k])**2 + d[k] * (i - x[k])**3
                spline_y.append(spline_value)
                k = k + 1
        for i in range(len(x)):
            plt.scatter(x[i], y[i])
        for point in points:
            plt.scatter(point[0], point[1])
        plt.plot(fun_x, spline_y, label='Вычисленная функция')
        plt.grid()
        plt.legend()
        plt.hlines(0, x[0], x[len(x) - 1], color="black")
        if x[0] * x[1] <= 0:
            plt.vlines(0, min(fun_y), max(fun_y), color="black")
        plt.show()
        x_i = utils.read_float(
            x[0], x[len(x) - 1],
            "Введите х в котором хотите подсчитать значение функции интерполяции"
        )
        for k in range(1, len(x)):
            if x[k - 1] <= x_i <= x[k]:
                y_i = y[k] + b[k] * (x_i - x[k]) + c[k] * (
                    x_i - x[k])**2 + d[k] * (x_i - x[k])**3
                print("Значение функции интерполяции в указанной точке: " +
                      str(y_i))
                points.append((x_i, y_i))
                break
Beispiel #9
0
 def parse_krannich(self,lines):
     items = []
     item = []
     for line in lines:
         if line[0].isdigit():
             items.append(item)
             item = [line]
         else:
             item.append(line)
     items.append(item)
     self.date = None
     self.no = None
     for line in items[0]:
         if "Rechnung" in line:
             self.no = line.split()[1]
             self.date = utils.convert_date4(line.split()[2])
     self.items = []
     mypos = 0
     rounding_error = 0
     for item_lines in items[1:]:
         item_str = item_lines[0]
         clutter = ['Einzelpreis','Krannich','IBAN','Rechnung','Übertrag']
         s_item = SupplierItem(self)
         long_description_lines = \
             [l for l in item_lines[1:] \
                if utils.no_substr(clutter,l) and l.strip()]
         s_item.description = " ".join(long_description_lines[0][0:82].split())
         s_item.long_description = ""
         for l in long_description_lines:
             if "Zwischensumme" in l:
                 break
             s_item.long_description += l
         pos = int(item_str[0:7].split()[0])
         if not (pos in [mypos,mypos+1,mypos+2]):
             break
         if "Vorkasse" in s_item.description:
             continue
         mypos = pos
         #print(item_str)
         s_item.item_code = item_str.split()[1]
         q=re.search("([0-9]+) *([A-Za-z]+)",item_str[80:99])
         s_item.qty = int(q.group(1))
         s_item.qty_unit = q.group(2)
         price = utils.read_float(item_str[130:142].split()[0])
         try:
             discount = utils.read_float(item_str[142:152].split()[0])
         except Exception:
             discount = 0
         s_item.amount = utils.read_float(item_str[157:].split()[0])
         if s_item.qty_unit=="Rol":
             try:
                 r1 = re.search('[0-9]+ *[mM]', s_item.description)
                 r2 = re.search('[0-9]+', r1.group(0))
                 s_item.qty_unit = "Meter"
                 s_item.qty = int(r2.group(0))
             except Exception:
                 pass
         s_item.rate = round(s_item.amount/s_item.qty,2)
         rounding_error += s_item.amount-s_item.rate*s_item.qty
         self.items.append(s_item)
     vat_line = ""
     for i in range(-1,-len(items),-1):
         vat_lines = [line for line in items[i] if 'MwSt' in line]
         if vat_lines:
             vat_line = vat_lines[0]
             self.shipping = PurchaseInvoice.get_amount_krannich\
                 ([line for line in items[i]\
                    if 'Insurance' in line or 'Freight' in line\
                        or 'Neukundenrabatt' in line])
             break
     self.totals[self.default_vat] = utils.read_float(vat_line[145:157])
     self.vat[self.default_vat] = PurchaseInvoice.get_amount_krannich([vat_line])
     self.shipping += rounding_error
     self.compute_total()
Beispiel #10
0
 def get_amount_krannich(cls,lines):
     return sum(map(lambda line: utils.read_float(line[-9:-1]),lines))
Beispiel #11
0
    if x == 1:
        return 0
    return (x**3 - x**2) / (x - 1)


integral = u'\u222b'
integrals = ((integral + " x^2 dx", lambda x: x**2),
             (integral + " x^3 dx", lambda x: x**3), (integral + " sin(x) dx",
                                                      lambda x: np.sin(x)),
             (integral + " x^3-x^2+3 dx", lambda x: x**3 - x**2 + 3),
             (integral + " 1/x dx", lambda x: one_for_x(x)),
             (integral + " ln(x) dx", lambda x: lnx(x)),
             (integral + " sin(x)/x dx",
              lambda x: sinx_x(x)), (integral + " (x^3-x^2)/(x-1) dx",
                                     lambda x: x3_x2_div_x1(x)))
print("Выберите какой интеграл посчитать")
integral_num = ut.choose_from_map(integrals)
section = ut.read_section("Введите интервал используя разделитель ;", ";")
epsilon = ut.read_float(0, 100, "Введите эпсилон")
try:
    result, inaccuracy, new_n = integral_solve_symp.solve_with_eps_sympson(
        section[0], section[1], 5, integrals[integral_num][1], epsilon)
    print("Результат работы метода Симпсона: " + str(result))
    print("Погрешность вычисления метода Симпсона: " + str(inaccuracy))
    print("n: " + str(new_n))
except ValueError as e:
    print(
        "Произошла ошибка при вычислении значения функции на промежутке, Adios"
    )
    sys.exit()
Beispiel #12
0
def choose_epsilon():
    return utils.read_float(0, sys.float_info.max, "Введите эпсилон")
Beispiel #13
0
        plt.scatter(x[i], y[i])
    for point in points:
        plt.scatter(point[0], point[1])
    plt.plot(fun_x, spline_y, label='Вычисленная функция')
    plt.grid()
    plt.legend()
    plt.hlines(0, x[0], x[len(x) - 1], color="black")
    if x[0] * x[1] <= 0:
        plt.vlines(0, plt.ylim()[0], plt.ylim()[1], color="black")
    plt.show()


if __name__ == '__main__':
    func_num = utils.choose_from_map(functions)
    x0, x_last = utils.read_section("Введите промежуток используя ;", ";")
    inaccuracy = utils.read_float(
        0, 100, "Введите точность, с которой будет вычислено значение")
    y0 = utils.read_float(-1000.0, 1000.0,
                          "Введите значение у0 в левой границе отрезка")
    try:
        c_integral = functions_c[func_num][1](x0, y0)
        x, y = runge.calculate_data_set(x0, y0, x_last, functions[func_num][1],
                                        functions_integral[func_num][1],
                                        c_integral, 0.1)
        # print(x)
        # print(y)
        a, b, c, d = spline.get_coefficients(x, y)
        show(x, y, b, c, d, functions_integral[func_num][1], c_integral)
    except Exception:
        print(
            "Произошла ошибка при вычислении функции либо не хватает данных для использования метода сплайнов"
        )
Beispiel #14
0
 def __read_columns(self, head, null_bitmap, column_schemas):
     columns = []
     for i in xrange(0, len(columns)):
         schema = column_schemas[i]
         type = schema["REAL_TYPE"]
         column = {"type":type, "value":None}
         null = True if (null_bitmap[i/8]>>(i%8))&0x01 else False
         unsigned = column_schemas[i]["IS_UNSIGNED"]
         if null:
             column["value"] = None
         elif type == FieldType.TINY:
             if unsigned:
                 head, columns["value"] = utils.read_unsigned_int(head, 1, False)
             else:
                 head, columns["value"] = utils.read_signed_int(head, 1, False)
         elif type == FieldType.SHORT:
             if unsigned:
                 head, columns["value"] = utils.read_unsigned_int(head, 2, False)
             else:
                 head, columns["value"] = utils.read_signed_int(head, 2, False)
         elif type == FieldType.LONG:
             if unsigned:
                 head, columns["value"] = utils.read_unsigned_int(head, 4, False)
             else:
                 head, columns["value"] = utils.read_signed_int(head, 4, False)
         elif type == FieldType.INT24:
             if unsigned:
                 head, columns["value"] = utils.read_unsigned_int(head, 3, False)
             else:
                 head, columns["value"] = utils.read_signed_int(head, 3, False)
         elif type == FieldType.FLOAT:
             head, columns["value"] = utils.read_float(head)
         elif type == FieldType.DOUBLE:
             head, columns["value"] = utils.read_double(head)
         elif type == FieldType.VARCHAR or column.type == FieldType.STRING:
             if schema["MAX_LENGTH"] > 255:
                 head, columns["value"] = utils.read_lc_pascal_string(head, 2)
             else:
                 head, columns["value"] = utils.read_lc_pascal_string(head, 1)
         elif type == FieldType.NEWDECIMAL:
             head, columns["value"] = self.__read_new_decimal(column)
         elif type == FieldType.BLOB:
             length_size = schema["LENGTH_SIZE"]
             charset = schema["CHARACTER_SET_NAME"]
             head, columns["value"] = utils.read_lc_pascal_string(head, length_size, charset)
         elif type == FieldType.DATETIME:
             head, columns["value"] = utils.read_datetime(head)
         elif type == FieldType.TIME:
             head, columns["value"] = utils.read_time(head)
         elif type == FieldType.DATE:
             head, columns["value"] = utils.read_date(head)
         elif type == FieldType.TIMESTAMP:
             head, timestamp = utils.read_unsigned_int(head, 4)
             columns["value"] = datetime.datetime.fromtimestamp(timestamp)
         elif type == FieldType.LONGLONG:
             if unsigned:
                 head, columns["value"] = utils.read_unsigned_int(head, 8, False)
             else:
                 head, columns["value"] = utils.read_signed_int(head, 8, False)
         elif type == FieldType.YEAR:
             head, year = utils.read_unsigned_int(head, 1, False)
             columns["value"] = year + 1900
         elif type == FieldType.ENUM:
             size = schema["SIZE"]
             head, index = utils.read_unsigned_int(head, size, False) - 1
             columns["value"] = schema["ENUM_VALUES"][index]
         elif type == FieldType.SET:
             size = schema["SIZE"]
             head, index = utils.read_unsigned_int(head, size, False) - 1
             columns["value"] = schema["SET_VALUES"][index]
         elif type == FieldType.BIT:
             bytes = schema["BYTES"]
             bits = schema["BITS"]
             head, columns["value"] = utils.read_bits(head, bytes, bits)
         elif type == FieldType.GEOMETRY:
             length_size = schema["LENGTH_SIZE"]
             head, columns["value"] = utils.read_lc_pascal_string(head, length_size)
         else:
             raise NotImplementedError("Unknown MySQL column type: %d" % (type))
         columns.append(column)
     return columns
Beispiel #15
0
def show_system(functions, section, point):
    plots = []
    x = np.arange(section[0], section[1], (section[1] - section[0]) / 1000)
    for f in functions:
        plots.append(x)
        plots.append(f(x))
    plt.plot(*plots)
    plt.scatter(point[0], point[1])
    plt.grid()
    plt.hlines(0, x.min(), x.max(), color="black")
    plt.show()


choose = ut.choose_from_list(types)
if choose == 0:
    epsilon = ut.read_float(0.00000000001, 10000000000, "Укажите точность")
    results = []
    equation_num = ut.choose_from_map(equations)
    equation_as_str = equations[equation_num][0]
    equation_section = equations_sections[equation_as_str]
    bisection_result = bisection.bisection_method(equations[equation_num][1],
                                                  equation_section[0],
                                                  equation_section[1], epsilon)
    simple_iter_result = simple_iter.iter_method(
        equations_equals[equation_as_str], epsilon,
        equations_x[equation_as_str])
    results.append(bisection_result)
    results.append(simple_iter_result)
    print("Результат выполнения метода бисекции: " + str(bisection_result))
    print("Результат выполнения метода простых итераций: " +
          str(simple_iter_result))