Ejemplo n.º 1
0
    def myinfo(self):
        user = api.user.get_current()
        fullname = user.getProperty('fullname')
        if type(fullname).__name__ == 'object':
            fullname = None

        portrait = user.portal_memberdata.getPersonalPortrait()

        #import pdb;pdb.set_trace()
        info = {'name': fullname, 
                'clubs': ['BB', 'CC', 'DD'], 
                'portrait': portrait}



        if self.megabankisinstalled:
            from hejasverige.megabank.bank import Bank
            pid = api.user.get_current().getProperty('personal_id')

            # if field is not defined as a personal property it becomes an object and the bank fails to load
            if type(pid).__name__ == 'object':
                info['balance'] = 'error'
                info['amount_pending'] = 'error'
            else:
                import locale
                locale.setlocale(locale.LC_ALL, 'sv_SE.utf-8')
                try:
                    accountinfo = Bank().getAccount(personalid=pid, context=self)
                    info['balance'] = locale.currency(accountinfo.get('Balance', None), grouping=True)
                    info['amount_pending'] = locale.currency(accountinfo.get('AmountPending', None), grouping=True)
                except:
                    info['balance'] = 'conerror'
                    info['amount_pending'] = 'conerror'
        #import pdb; pdb.set_trace()
        return info        
Ejemplo n.º 2
0
 def salesAnalysisGoBtn_triggered(self, switch):
     start_date, end_date = self.getDates(switch)
     if switch == "Customers":
         orders = [
             order
             for order in self.orders
             if order.customer.name == self.current_customer[0].name
             and order.date >= start_date
             and order.date <= end_date
         ]
         gross_sales, average_sales = self.salesInDateRange(orders, start_date, end_date)
         self.writeDataToDisplay(self.current_customer, orders)
         self.cust_date_sales_display.setText(locale.currency(gross_sales))
         self.cust_date_average_sale_display.setText(locale.currency(average_sales))
     elif switch == "Group":
         customers_filtered = list(filter(lambda c: c.group == self.current_group, self.customers))
         orders = [
             order
             for order in self.orders
             for customer in customers_filtered
             if order.customer.name == customer.name and order.date >= start_date and order.date <= end_date
         ]
         gross_sales, average_sales = self.salesInDateRange(orders, start_date, end_date)
         customers_with_orders = [order.customer for order in orders]
         self.writeDataToDisplay(customers_with_orders, orders)
         self.group_date_sales_display.setText(locale.currency(gross_sales))
         self.group_date_average_sale_display.setText(locale.currency(average_sales))
Ejemplo n.º 3
0
def test_prettify(project_1_fixture):
    def colored_side_effect(v, c='', **kwargs):
        return '{}: {}{}'.format(c, v, kwargs)
    with patch('srmlf.project.colored',
               side_effect=colored_side_effect):
        with patch('prettytable.PrettyTable') as pt:
            with LocaleMock(('en_US', 'UTF-8'), [locale.LC_TIME,
                                                 locale.LC_MONETARY]):
                table = project_1_fixture.prettify()
                pt.assert_any_call(['red: Description{}',
                                    'red: Date{}',
                                    'red: Alice{}',
                                    'red: Bob{}'])

                assert isinstance(table, MagicMock)
                assert table.add_row.call_count == 4
                table.add_row.assert_any_call(
                    ['',
                     ': TOTAL{\'attrs\': [\'bold\']}',
                     ': %s{\'attrs\': [\'bold\']}'
                     % locale.currency(10.0),
                     ': %s{\'attrs\': [\'bold\']}'
                     % locale.currency(5.0)
                     ])
                table.add_row.assert_any_call(
                    ['',
                     '',
                     ': 66.67%{\'attrs\': [\'bold\']}',
                     ': 33.33%{\'attrs\': [\'bold\']}'
                     ])
Ejemplo n.º 4
0
def currency3(value):
    curr = None
    if value:
        curr = locale.currency(value, grouping=True)
    else:
        curr = locale.currency(0, grouping=True)
    return curr
Ejemplo n.º 5
0
def budget(): # Create the budget function
	import locale
	locale.setlocale( locale.LC_ALL, '' )

	budget = float(input("Please enter your total budget for the month: "))
	question = input("Would you like to enter an expense? ('y' or 'n') ")
	total = 0 # Keep track of your total spending
	num_of_purch = 0 # Keep track of the number of purchases

	while question != 'n':
		expense = float(input("Please enter the dollar amount of the expense: "))
		total = total + expense
		num_of_purch = num_of_purch + 1
		question = input("Would you like to enter another expense? ('y' or 'n') ")

	print("")
	print("The total that you spent during the month is", 
		locale.currency(total, grouping = True))
	print("You made a total of", num_of_purch, "purchases during the month!")
	print("You spent an average of",
		locale.currency(total / num_of_purch, grouping = True),
		"on each purchase!")

	# Check whether your spending is under or over budget (or on budget)
	if budget > total: 
		print("You are under budget by a total of", 
			locale.currency(budget - total, grouping = True))

	elif budget == total:
		print("You spent all of your budget (exactly)!")

	else:
		print("You are over budget by a total of",
			locale.currency(total - budget, grouping = True))
Ejemplo n.º 6
0
def fetch_user_context(user):
    if user.is_authenticated:
        locale.setlocale(locale.LC_ALL, '')
        try:
            user_account = Account.objects.get(user_id=user.id, account_type=account_type.savings)
            savings_text = locale.currency(user_account.balance, grouping=True)
        except:
            savings_text = '$0'

        try:
            user_account = Account.objects.get(user_id=user.id, account_type=account_type.checking)
            checking_text = locale.currency(user_account.balance, grouping=True)
            debit_activated = user_account.card_activated
            debit_pin = user_account.card_pin
        except:
            checking_text = '$0'
            debit_activated = False
            debit_pin = ''

        try:
            user_account = Account.objects.get(user_id=user.id, account_type=account_type.credit)
            credit_text = locale.currency(user_account.balance, grouping=True)
            credit_exists = True
            credit_pin = user_account.card_pin
        except:
            credit_text = '$0'
            credit_exists = False
            credit_pin = ''

    context = {'savings_text': savings_text, 'checking_text': checking_text, 'credit_text': credit_text, 'credit_exists': credit_exists, 'debit_activated': debit_activated, 'credit_pin': credit_pin, 'debit_pin': debit_pin}
    return context
Ejemplo n.º 7
0
    def ltc(self):
        url = 'https://btc-e.com/api/2/ltc_usd/ticker'

        request = Browser(url)
        if not request:
            return "Couldn't retrieve LTC data."

        try:
            json = request.json()
        except:
            return "Couldn't parse LTC data."

        locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
        last = locale.currency(json['ticker']['last'])
        low = locale.currency(json['ticker']['low'])
        high = locale.currency(json['ticker']['high'])

        if self.values:
            try:
                value = locale.currency(float(json['ticker']['last']) * float(self.values[0]))
            except:
                return "Couldn't compute LTC value."

            return 'Value of %s LTC is %s' % (self.values[0], value)
        else:
            return 'Litecoin, Last: %s, Low: %s, High: %s' % (last, low, high)
Ejemplo n.º 8
0
def update_exchange_rates(ui, total):
    rates = coinbase.exchange_rates()
    global btc_to_usd
    global usd_to_btc
    btc_to_usd = float(rates["btc_to_usd"])
    usd_to_btc = float(rates["usd_to_btc"])
    ui.display_exchange_rate(locale.currency(btc_to_usd), locale.currency(total), total * usd_to_btc)
Ejemplo n.º 9
0
def output_transactions(sheet,  label, transactions, column):
    totals = {}

    for transaction in transactions:
        category = transaction.category

        if category.name not in totals:
            totals[category.name] = { 'amount': 0.00, 'category': category }

        totals[category.name]['amount'] += transaction.calculate_amount()

    row = 2
    grand_total = 0

    for category_name, data in iter(sorted(totals.iteritems())):
        total = data['amount']
        category = data['category']

        # Skip categories with 0
        if total == 0:
            continue

        category_cell = Cell(output_sheet, row, column)
        total_cell = Cell(output_sheet, row, column + 1)
        reimbursable_cell = Cell(output_sheet, row, column + 2)

        category_cell.value = category.description()
        total_cell.value = locale.currency(total)
        reimbursable_cell.value = reimbursable.name

        grand_total += total
        row += 1

    Cell(output_sheet, 1, column).value = label
    Cell(output_sheet, 1, column + 1).value = locale.currency(grand_total)
Ejemplo n.º 10
0
    def print_barcode(self, code, artist, title, price, genre, new_used):
        c = canvas.Canvas(self.file, pagesize=(62 * mm, 29 * mm))
        code_copy = code #this is terrible i hate myself
        
        if code.isdigit():
            code = '%013d' % int(code)
            code = reportlab.graphics.barcode.createBarcodeDrawing('EAN13',value=code,barHeight=8*mm,width=49*mm)
        else:
            code = reportlab.graphics.barcode.createBarcodeDrawing('Code128',value=code,barHeight=5*mm,width=49*mm,humanReadable=True)
        
        code.drawOn(c,12*mm, 3*mm)
        c.drawImage(BABY_LOGO_FILE_NAME, 2*mm,-24*mm,width=9*mm,preserveAspectRatio=True)
        #c.drawImage(BABY_LOGO_FILE_NAME, 1*mm,-14*mm,preserveAspectRatio=True)
        c.setFont('Courier', 8)
        artist = artist[0:22]
        title = title[0:22]
        c.drawString(2*mm, 19*mm,artist)#19
        c.drawString(2*mm, 16*mm,title)#16
        #if new_used == 'Used':
        filtered_genre = genre.replace("Folk, World, & Country", "FWC")
        c.drawString(2*mm, 13*mm,filtered_genre)#13
        c.setFont('Courier',16)
        if 'PRRGC' not in code_copy:
            if price > 99.99:
                c.drawString(37*mm, 17*mm, locale.currency(price))
            else:
                c.drawString(40*mm, 17*mm, locale.currency(price))
        c.showPage()
        c.save()

        #make call to subprocess to talk to CUPS to print this shiz on the printer
        command = 'lp -d Brother_QL_700 -o media=Custom.62x25mm /Users/plaidroomrecords/Desktop/barcode_test.pdf'
        subprocess.call(command, shell=True)
Ejemplo n.º 11
0
def format_value(value, type_desc, str_format=None):
	type_desc = str(type_desc).lower()
	if value is not None:
		if type_desc == 'integer' or type_desc == 'int' or type_desc == 'bigint' or type_desc == 'seconds':
			return locale.format('%d', value, grouping=True)
		elif type_desc == 'float' or type_desc == 'decimal' or type_desc == 'numeric':
			return locale.format('%.4f', Decimal(str(value).replace(',', '')), grouping=True).rstrip('0').rstrip('.')
		elif type_desc == 'percent':
			value = value * 100
			s = str(value)
			return '{}%'.format(locale.format('%g', Decimal(s.rstrip('0').rstrip('.')), grouping=True) if '.' in s else locale.format('%g', Decimal(s), grouping=True))
		elif type_desc == 'money':
			if value < 0:
				result = '-{}'.format(locale.currency(abs(value), grouping=True))
			else:
				result = locale.currency(value, grouping=True)
			return result
		elif type_desc == 'date':
			if 'month' in type_desc:
				return value.strftime('%m/%Y')
			elif 'quarter' in type_desc:
				return datetime_to_quarter(value)
			else:
				return value.strftime('%m/%d/%Y')
		elif type_desc == 'timestamp' or type_desc == 'time' or type_desc == 'interval':
			return value.strftime(str_format)
	return str(value)
Ejemplo n.º 12
0
    def test_can_create_an_invoice_with_multiple_pages(self):
        rows = []
        subtotal = 0

        for i in range(0, 27):
            description = fake.sentence(nb_words=5, variable_nb_words=True)
            unit_price = fake.pydecimal(left_digits=3, right_digits=2, positive=True)
            amount = fake.random_int(min=1, max=15)
            unit_total = unit_price * amount

            subtotal += unit_total

            rows.append([description, unit_price, amount, unit_total])

        vat = subtotal * 21 / 100
        total_invoice = subtotal + vat

        data = CustomData()
        data.customer = Customer(
            code='CUS1', name=fake.name(), vat=fake.bothify(text="#########?").upper(),
            address=fake.address(), city=fake.city(),
            postal_code=fake.postcode(), province=fake.state(), country=fake.country(),
            contact_name=fake.name(), contact_phone=fake.phone_number(), contact_email=fake.free_email()
        )
        data.metadata = Metadata(doc_type='FACTURA', code='FRA SER 14-2014', serie='SER', date='01/12/2014', subtotal=subtotal)
        data.footer_a = [locale.currency(subtotal), 'I.V.A.', '21%', locale.currency(vat), locale.currency(total_invoice)]
        data.footer_b = ['TRANSFER', 'MY ENTITY', 'ER 19281 12 1234567889', '30 días']
        data.rows = rows

        destination_file = os.path.join(get_output_folder(), "mutiple_pages.pdf")

        self.invoice_generator.data = data
        self.invoice_generator.generate(destination_file)

        self.assertIsFile(destination_file)
Ejemplo n.º 13
0
def main ():
    # Set locale to US
    locale.setlocale( locale.LC_ALL, '' )

    # Seperator
    print()

    # User input
    amount = float(input("Enter amount: $"))

    # List of cash options
    options_list = []
    options_list.append(locale.currency(amount, grouping=True))
    options_list.append(locale.currency(math.ceil(amount), grouping=True))
    options_list.append(locale.currency((int(5 * math.ceil(amount / 5))), grouping=True))
    options_list.append(locale.currency((int(20 * math.ceil(amount / 20))), grouping=True))

    # Remove duplicates
    options_list = list(OrderedDict.fromkeys(options_list))

    # Output
    print()
    print("Cash options:")

    for option in options_list:
        print(option)

    print()
Ejemplo n.º 14
0
    def form_valid(self, form):
        self.object.aprobacion_lider = timezone.localtime(timezone.now())
        self.object = form.save()
        valores = self.object.desplazamientos.all().values_list('valor',flat=True)
        valor_aprobado = 0

        for valor in valores:
            valor_aprobado += valor

        if self.object.estado == 'aprobado_lider':
            self.object.valor_aprobado_lider = valor_aprobado
            self.object.save()

        elif self.object.estado == 'rechazado':
            self.object.valor_aprobado_lider = 0
            self.object.save()
            send_mail_templated.delay('email/desplazamiento.tpl',
                                      {
                                          'url_base':'http://sican.asoandes.org/',
                                          'fullname':self.object.formador.get_full_name(),
                                          'nombre_solicitud': self.object.nombre,
                                          'fecha_solicitud': self.object.creacion.strftime('%d/%m/%Y'),
                                          'valor_solicitado': locale.currency(self.object.valor,grouping=True),
                                          'valor_aprobado': locale.currency(valor_aprobado,grouping=True),
                                          'observacion': form.cleaned_data['observacion'],
                                          'estado': 'Solicitud rechazada'
                                      },
                                      DEFAULT_FROM_EMAIL, [self.object.formador.correo_personal])

        else:
            self.object.valor_aprobado_lider = 0
            self.object.save()

        return super(ModelFormMixin,self).form_valid(form)
Ejemplo n.º 15
0
    def dump_section(sheet,start_row,cols,col_heads):
        # If there is no data in the row, return
        for i in range(0,3):
            print(start_row,i,sheet.row(start_row)[i].value)

        if sheet.row(start_row)[cols[0]].value=="": return
        ncols = len(cols)
        f.write(r"\begin{tabular}{l|" + "r"*ncols + r"}" + nl)
        if col_heads: f.write("&".join(col_heads) + r"\\" + nl)
        f.write(r"\hline"+nl)
        sum = 0
        while sheet.row(start_row)[cols[0]].value!="":
            for c in cols:
                v = sheet.row(start_row)[c].value
                if not v:
                    continue
                if c!=cols[-1]:
                    f.write(str(v) + " & ")
                else:
                    try:
                        f.write("\\" + locale.currency(v,True,True) + r"\\" + nl)
                        sum += float(v)
                    except TypeError:
                        continue
            start_row+=1
        f.write("\hline\multicolumn{%d}{l}{Total} &" % (ncols-1))
        f.write("\\" + locale.currency(sum,True,True) + r"\\" + nl)
        f.write(r"\end{tabular}" + nl + nl)
Ejemplo n.º 16
0
 def get_context_data(self, **kwargs):
     kwargs['valor_solicitado'] = locale.currency(self.object.valor,grouping=True)
     if self.object.valor_aprobado != None:
         kwargs['valor_aprobado'] = locale.currency(self.object.valor_aprobado,grouping=True)
     kwargs['archivo_url'] = self.object.get_archivo_url()
     kwargs['archivo_filename'] = self.object.archivo_filename()
     return super(TransportesEliminarView,self).get_context_data(**kwargs)
Ejemplo n.º 17
0
    def print_aux(self, start, end, name, date):
        doc = open(os.path.join(self.path, 'documentos', name + '.html'), 'w')
        doc.write("""<style type="text/css">
                    <!--
                    @import url("style.css");
                    -->
                    </style>""")
        print date.Month, date.Year

        sep = [10, 10, 10, 20]

        saldo = 0
        cur_cta = ''
        acum = []
        for cuenta, fecha, tipopol, numpol, referencia, tipomov, importe in self.get_records(start, end):

            saldo += importe * (-1 if tipomov == 'True' else 1)
            fecha = fecha + " " * (sep[0] - len(fecha))
            tipopol = self.movs[tipopol] + " " * (sep[1] - len(self.movs[tipopol]))
            numpol = str(numpol) + " " * (sep[2] - len(str(numpol)))
            referencia = referencia + " " * (sep[3] - len(referencia))
            importe = (" " * (7 if tipomov == 'True' else 0)) + locale.currency(importe, grouping=True) + " " * (7 if tipomov == 'True' else 12)
            if cur_cta != cuenta:
                acum.append(['Saldo','','','','','', locale.currency(saldo, grouping=True)])
                acum.append(['','','','','','', ''])
                saldo = 0
                cur_cta = cuenta
            acum.append([cuenta, fecha, tipopol, numpol, referencia, importe, locale.currency(saldo, grouping=True)])

        htmlcode = HTML.table(acum, attribs={'id':"hor-minimalist-b"}, border=0,
                        header_row=['Cuenta', 'Fecha', 'Tipo', '#Poliza', 'Ref', 'Importe', 'Saldo'])

        doc.write(htmlcode)
Ejemplo n.º 18
0
    def get_all_csv(self, days):
        """get csv export of all sent invoices"""

        import locale
        locale.setlocale(locale.LC_ALL, 'nl_NL.UTF-8')


        csv_data=""

        invoices=self.get_all(
            match={ "sent": True },
            gte={ "sent_date": time.time()- ( int(days)*24*3600)},
            sort=[ [ "sent_date" ,1 ] ]
            )

        for invoice in invoices:
            cols=[]
            cols.append(invoice["to_copy"]["customer_nr"])
            cols.append(invoice["to_copy"]["company"])
            cols.append(invoice["invoice_nr"])
            cols.append(time.strftime("%Y-%m-%d", time.localtime(invoice['sent_date'])))
            cols.append(locale.currency(invoice["calc_total_tax"], symbol=False, grouping=False))
            cols.append(locale.currency(invoice["calc_total_tax"]-invoice["calc_total"], symbol=False, grouping=False))

            stripped_cols=[]
            for col in cols:
                stripped_cols.append(str(col).replace(";","_"))
            csv_data+=";".join(stripped_cols)+"\n"


        response=bottle.HTTPResponse(body=csv_data)
        response.set_header('Content-Type', 'text/plain')

        return(response)
Ejemplo n.º 19
0
def calculator(wall, price):
	import locale
	locale.setlocale( locale.LC_ALL, '' )

	gallons = (wall / 115) * 1 # Calculate the number of gallons required
	hours = (wall / 115) * 8 # Calculate the number of gallons required
	labor_cost = 20 * hours # Calculate the labor cost
	paint_cost = price * hours # Calculate the paint cost
	total_cost = paint_cost + labor_cost

	print("You will require a total of", 
		format(gallons, '.2f'),
		"gallons of paint to paint your wall!")

	print("It will take a total of", 
		format(hours, '.2f'),
		"hours of labor to paint your wall!")

	print("It will cost a total of", 
		locale.currency(labor_cost, grouping=True ),
		"dollars in labor to paint your wall!")

	print("It will cost a total of", 
		locale.currency(paint_cost, grouping=True ),
		"dollars in paint to finish painting your wall!")

	print("The total cost of the paint job will be", 
		locale.currency(total_cost, grouping=True ),
		"dollars!")
Ejemplo n.º 20
0
    def btc(self):
        url = 'https://btc-e.com/api/2/btc_usd/ticker'

        response = pageopen(url)
        if not response:
            self.chat("Couldn't retrieve BTC data.")
            return

        try:
            json = response.json()
        except:
            self.chat("Couldn't parse BTC data.")
            return

        locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
        last = locale.currency(json['ticker']['last'])
        low = locale.currency(json['ticker']['low'])
        high = locale.currency(json['ticker']['high'])

        if self.values:
            try:
                value = locale.currency(float(json['ticker']['last']) * float(self.values[0]))
            except:
                self.chat("Couldn't compute BTC value.")
                return

            return 'Value of %s BTC is %s' % (self.values[0], value)
        else:
            return 'Bitcoin, Last: %s, Low: %s, High: %s' % (last, low, high)
Ejemplo n.º 21
0
 def get_representation(self, doc_field, data):
     import locale
     locale.setlocale(locale.LC_ALL, '')        
     if doc_field:
         if doc_field.df_type == 'link':
             return data
             document = self.META.property('type', 'document')
             label = self.META.property('type', 'label')
             row = self.META.db[document](data)
             if row and label in row:
                 return row[label]
         elif doc_field.df_type == 'currency':
             return locale.currency(data, doc_field.property('type', 'symbol') or get_default(types.currency.options, 'symbol'), True, False)
         elif doc_field.df_type == 'money':
             return locale.currency(data, doc_field.property('type', 'international') or get_default(types.currency.options, 'symbol'), True, True)
         elif doc_field.df_type == 'filelink':
             document = self.db.File(data)
             if document and self.document.META.property('allow_file_links'):
                 label = document['title']
                 return A(URL('download', args=document.id), cid=self.request.cid if self.request.ajax else None)
             elif document:
                 return document['title']
         elif doc_field.df_type in ('blob', 'property'):
             return 'DATA'
         elif doc_field.df_type == 'smalltext' and data and len(data)>255:
             return 'DATA'
         elif isinstance(data, (list, tuple, dict)):
             return 'DATA'
         return data
     return data
Ejemplo n.º 22
0
 def create_report_window(self, report, other=False):
     
     reporte = self.builder.get_object("reporte")
     
     vistaCuentas = self.builder.get_object("vistaReporte")
     column = gtk.TreeViewColumn("Cuenta", gtk.CellRendererText(), text=0)
     vistaCuentas.append_column(column)
     column.set_sort_column_id(0)
     
     column = gtk.TreeViewColumn("Aportantes", gtk.CellRendererText(), text=1)
     vistaCuentas.append_column(column)
     column.set_sort_column_id(1)
     
     column = gtk.TreeViewColumn("Cantidad", gtk.CellRendererText(), text=2)
     vistaCuentas.append_column(column)
     column.set_sort_column_id(2)
     
     cuentas = gtk.ListStore(str, int, str)
     vistaCuentas.set_model(cuentas)
     
     if not other:
         for ra in report.reportAccounts:
             cuentas.append([ra.name, ra.quantity, locale.currency(ra.amount, True, True)])
     else:
         for ra in report.otherAccounts:
             cuentas.append([ra.account.name, ra.quantity, locale.currency(ra.amount, True, True)])
     
     reporte.show_all()
Ejemplo n.º 23
0
def display_results(container):
    total_positions = len(list(filter(lambda x: not x.is_open(), container.context.positions)))
    locale.setlocale(locale.LC_ALL, "en_GB.UTF-8")

    if total_positions == 0:
        print("=========================================================")
        print("Algo: %s" % (container.algo.identifier(),))
        print("No Positions taken")
    else:
        closed = list(
            map(
                lambda x: "\t%s%s  --> %.2fpts (%s)\x1B[;0m"
                % ("\x1B[;31m" if x.points_delta() < 0.0 else "\x1B[;32m", x, x.points_delta(), x.position_time()),
                filter(lambda x: not x.is_open(), container.context.positions),
            )
        )
        open = list(map(lambda x: "\t%s" % (x), filter(lambda x: x.is_open(), container.context.positions)))
        winning = list(
            filter(lambda x: x.points_delta() > 0.0, filter(lambda x: not x.is_open(), container.context.positions))
        )

        print("=========================================================")
        print("Algo:             %s" % (container.algo.identifier(),))
        print("Winning Ratio:    %.2f%%" % ((len(winning) / total_positions * 100),))
        print(
            "Total Pts:        %.2f"
            % (sum([x.points_delta() for x in filter(lambda x: not x.is_open(), container.context.positions)]),)
        )
        print("Starting Capital: %s" % (locale.currency(container.starting_capital, grouping=True),))
        print("Current Capital:  %s" % (locale.currency(container.context.working_capital, grouping=True),))
        print("Capital Change:  %s" % (locale.currency(container.context.working_capital, grouping=True),))
        print("---------------------------------------------------------")
        print("Completed:\n%s" % ("\n".join(closed),))
        print("Open:\n%s" % ("\n".join(open),))
Ejemplo n.º 24
0
    def send_request_notification(self):
        '''
        Sends a notification to all eligible tutors that job is available
        '''
        from apps.tutor.models import TutorCourse, TutorDepartment
        import locale

        locale.setlocale(locale.LC_ALL, '')

        merge_vars = {
            "CLOCK_SAYING": "🕒",
            "RATE_SAYING": "💵",
            "EST_TIME": self.est_time,
            "HOURLY_RATE": locale.currency(self.hourly_rate),
            "ESTIMATED_WAGE": locale.currency(self.get_estimated_wage()),
            "COURSE_NAME": self.course.get_readable_name()
        }
        data = {
            'request_id': self.id
        }

        blocked_tutors = BlockedTutor.objects.filter(student=self.student)
        tutor_courses = TutorCourse.objects.filter(course=self.course).exclude(tutor__in=blocked_tutors.values('tutor_id'))
        tutors = [tc.tutor for tc in tutor_courses]
        tutor_departments = TutorDepartment.objects.filter(department=self.course.department).exclude(Q(tutor_id__in=tutor_courses.values('tutor_id')) | Q(tutor__in=blocked_tutors.values('tutor_id')))
        tutors.extend([td.tutor for td in tutor_departments])

        notification_type = NotificationType.objects.get(identifier="NEW_REQUEST")
        for tutor in tutors:
            if tutor.user == self.student.user:
                continue
            OpenNotification.objects.create(tutor.user, notification_type, data, merge_vars, None)
Ejemplo n.º 25
0
def monte_carlo():
    form = MonteCarloForm()
    if form.rate.data is not None:
        rate = float(form.rate.data)
    else:
        rate = 0.07
    if form.sigma.data is not None:
        sigma = float(form.sigma.data)
    else:
        sigma = 0.15
    if form.time.data is not None:
        time = int(form.time.data)
    else:
        time = 10
    if form.start_val.data is not None:
        start_value = float(form.start_val.data)
    else:
        start_value = all_accounts_sum()
    paths = gen_monte_carlo_paths(start_value, r=rate, sigma=sigma, time=time)
    session['paths'] = paths[:, :20]
    session['final_prices'] = paths[-1]
    stats = stats_from_paths(paths)
    mean = locale.currency(paths[-1].mean(), grouping=True)
    return render_template("monte_carlo.html",
                           paths=paths,
                           stats=stats,
                           start_value=("{:.2f}".format(start_value)),
                           start_val_for=locale.currency(start_value, grouping=True),
                           rate=rate,
                           sigma=sigma,
                           time=time,
                           mean=mean,
                           form=form)
Ejemplo n.º 26
0
 def probability_cmd(ctx, cmd, arg, *args):
     if args != 0:
         if args == 1:
             args[0] = arg.split(' ')[0]
             if len(args[0]) <= 7:
                 probability = lentoperm[len(args[0])]
                 probability = str(locale.currency(probability, grouping=True))
                 ctx.reply(u'The probability of "%s" compared to all other possible words of its length is`B %s`B to `B1`B against.' % (args[0], probability[1:len(probability)-3]), 'probability')
             else:
                 ctx.reply(u'The probability of "%s" compared to all other possible words of its length is `Bvery unlikely`B to `B1`B against.' % args[0], 'probability')
         else:
             probability = 0
             veryunlikely = False
             for word in arg.split(' '):
                 #This is a sentence, so getting the probability of the /entire/ string would be incorrect. Instead we do (permutation of letters/numbers for length of word) * (permutation for arrangements of words in sentence) to get the total possible number of sentences that could result from arranging every possible word for each word's length.
                 if len(word) <= 7:
                     probability += lentoperm[len(word)] * len(args)
                 else:
                     veryunlikely = True
             if veryunlikely == False:
                 probability = str(locale.currency(probability, grouping=True))
                 ctx.reply(u'The probability of this sentence, taking into account all the possible arrangements of all the possible words of all the given words\' lengths is`B %s`B to `B1`B against.' % probability[1:len(probability)-3], 'probability')
             else:
                 ctx.reply(u'The probability of this sentence, taking into account all the possible arrangements of all the possible words of all the given words\' lengths is `Bvery unlikely`B to `B1`B against.', 'probability')
     else:
         ctx.reply(u'The probability of nothing, compared to every character you could have typed, assuming "nothing" is a character is`B %s`B to `B1`B against. Please provide input next time.' % (len(numbers) + len(letters) + len(nothing)), 'probability')
Ejemplo n.º 27
0
def tax(total_sales): # Function will be used to calculated the various tax rates
	import locale # Import the locale
	locale.setlocale( locale.LC_ALL, '' ) # Set the locale for use within the function (locally)

	county_sales = total_sales * 0.02
	state_sales = total_sales * 0.04
	total_county_state = county_sales + state_sales

	print("")
	
	print("You spent a total of", 
		locale.currency(total_sales, grouping=True ), 
		" last month!")
	
	print("The total county sales tax that you owe is",
		locale.currency(county_sales, grouping=True ),
		"dollars!")

	print("The total state sales tax that you owe is",
		locale.currency(state_sales, grouping=True ),
		"dollars!")

	print("The total sales tax that you owe is",
		locale.currency(total_county_state, grouping=True ),
		"dollars!")
Ejemplo n.º 28
0
def to_html( startups ):
	c = 0
	html = ""

	# Ehh.... its diff on 2 computers
	try:
		locale.setlocale(locale.LC_ALL, 'en_US.utf8' )
	except:
		locale.setlocale(locale.LC_ALL, 'en_US.UTF-8' )

	for startup in startups:
		c = c + 1
		
		n = startup.get( "name" )
		hc = startup.get( "short_description" )
		url = startup.get( "url" )
		loc = startup.get( "location" )
		updated = startup.get( "updated" ).strftime( '%m-%d-%Y')

		html = html + "<p><b>" + str( c ) + ". %s (%s)</b><br/>%s, updated %s" % ( n, loc, hc, updated )
		html = html + "<br/>" + "<a href='%s' target='_blank'>URL</a>" % ( url )

		aurl = startup.get( "angel_list_url" )
		if aurl is not None:
			q = str( angel_list.property( startup, "quality" ) )
			f = str( angel_list.property( startup, "follower_count" ) )
			html = html + "  |  <a href='%s' target='_blank'>AngelList (q=%s, f=%s)</a>" % ( str( aurl ), q, f )

		cburl = startup.get( "crunchbase_url" )
		if cburl is not None:
			html = html + "  |  <a href='%s' target='_blank'>CrunchBase</a>" % ( str( cburl ) )		

		phurl = startup.get( "product_hunt_url" )
		if phurl is not None:
			v = str( startup.get( "product_hunt_votes" ) )
			cm = str( startup.get( "product_hunt_comments" ) )
			html = html + "  |  <a href='%s' target='_blank'>ProductHunt (v=%s, c=%s)</a>" % ( str( phurl ), v, cm )
		
		total_funding = startup.get( "total_funding" )
		if total_funding is not None and total_funding != 0 :
			html = html + "<br/>" + "Funding: %s" % ( str( locale.currency( total_funding, grouping=True ) )[:-3] )

		last_round = startup.get( "last_round" )
		if last_round is not None:
			round_str = "%s: %s" % ( str( startup.get( "last_round_type" ) ),
				str( locale.currency( last_round, grouping=True ) )[:-3] )

			last_round_url = startup.get( "last_round_url" )
			if last_round_url is not None and len( last_round_url ) > 0:
				html = html + ('   <a href="%s">%s</a>' % 
							     ( str( startup.get( "last_round_url" ) ), round_str ) )
			else:					
				html = html + '   %s' % round_str

		tags = startup.get( "tags" )
		if len( tags ) != 0:
			html = html + "<br/>Tags: " + ', '.join( tags )

	return html
Ejemplo n.º 29
0
	def printProgression(self, monthly, m, M):
		prog = self.progression(monthly, m, M)
		s = ''
		print 'Upphafsstada: %s' %(locale.currency(prog[0][0], grouping=True))
		for i in range(1,len(prog)):
			amount = locale.currency(prog[i][0], grouping = True)
			collectedInt = locale.currency(prog[i][1], grouping = True)
			print 'Manudur %d: \n Stada: %s Uppsafnadir vextir: %s' %(i, amount, collectedInt)
Ejemplo n.º 30
0
 def format_currency(self, amount, min):
     price = amount / 100
     locale.setlocale(locale.LC_ALL, '')
     formatted = locale.currency(price, symbol=False, grouping=True)
     if price < min:
         return '{}<span style="color: red;"> (低于{})</span>'.format(formatted, locale.currency(min, symbol=False, grouping=True))
     else:
         return formatted
Ejemplo n.º 31
0
    def fit(self,
            num_epoches=1000,
            max_memory=60,
            balance=10000000,
            discount_factor=0,
            start_epsilon=.5,
            learning=True):
        logging.info(
            "\n\nLR: {lr}, DF: {discount_factor}, "
            "TU: [{min_trading_unit}, {max_trading_unit}], "
            "DRT: {delayed_reward_threshold}, Tax: {tax}".format(
                lr=self.policy_network.lr,
                discount_factor=discount_factor,
                min_trading_unit=self.agent.min_trading_unit,
                max_trading_unit=self.agent.max_trading_unit,
                delayed_reward_threshold=self.agent.delayed_reward_threshold,
                tax=self.tax))

        # Visualization Preparation
        # Pre-visualization the chart data as it does not change
        self.visualizer.prepare(self.environment.chart_data)

        # Prepare the folders to store visualization results
        epoch_summary_dir = os.path.join(
            settings.BASE_DIR, 'epoch_summary/%s/epoch_summary_%s' %
            (self.stock_code, settings.timestr))
        if not os.path.isdir(epoch_summary_dir):
            os.makedirs(epoch_summary_dir)

        # Set agent's initial balance
        self.agent.set_balance(balance)

        # Initialize the information about training
        max_portfolio_value = 0
        epoch_win_cnt = 0

        # Training repetition
        for epoch in range(num_epoches):
            # Initialize the information about epoch
            loss = 0.
            itr_cnt = 0
            win_cnt = 0
            exploration_cnt = 0
            batch_size = 0
            pos_learning_cnt = 0
            neg_learning_cnt = 0

            # Initialize the memory
            memory_sample = []
            memory_action = []
            memory_reward = []
            memory_prob = []
            memory_pv = []
            memory_num_stocks = []
            memory_exp_idx = []
            memory_learning_idx = []

            # Initialize the environment, agent and policy nerual network
            self.environment.reset()
            self.agent.reset()
            self.policy_network.reset()
            self.reset()

            # Initialize the visualizer
            self.visualizer.clear([0, len(self.chart_data)])

            # Exploration rate decreases as you progress
            if learning:
                epsilon = start_epsilon * (1. - float(epoch) /
                                           (num_epoches - 1))
            else:
                epsilon = 0

            while True:
                # Sample generation
                next_sample = self._build_sample()
                if next_sample is None:
                    break

                # Actions decided by policy neural network or exploration
                action, confidence, exploration = self.agent.decide_action(
                    self.policy_network, self.sample, epsilon)

                # Perform the action you decided and earn immediate and delayed rewards
                immediate_reward, delayed_reward = self.agent.act(
                    action, confidence)

                # Store the actions and the consequences for the actions
                memory_sample.append(next_sample)
                memory_action.append(action)
                memory_reward.append(immediate_reward)
                memory_pv.append(self.agent.portfolio_value)
                memory_num_stocks.append(self.agent.num_stocks)
                memory = [
                    (memory_sample[i], memory_action[i], memory_reward[i])
                    for i in list(range(len(memory_action)))[-max_memory:]
                ]
                if exploration:
                    memory_exp_idx.append(itr_cnt)
                    memory_prob.append([np.nan] * Agent.NUM_ACTIONS)
                else:
                    memory_prob.append(self.policy_network.prob)

                # Update the information about iterations
                batch_size += 1
                itr_cnt += 1
                exploration_cnt += 1 if exploration else 0
                win_cnt += 1 if delayed_reward > 0 else 0

                # Update policy neural network when in training mode and delay rewards exist
                if delayed_reward == 0 and batch_size >= max_memory:
                    delayed_reward = immediate_reward
                    self.agent.base_portfolio_value = self.agent.portfolio_value
                if learning and delayed_reward != 0:
                    # Size of batch traning data
                    batch_size = min(batch_size, max_memory)
                    # Generate batch training data
                    x, y = self._get_batch(memory, batch_size, discount_factor,
                                           delayed_reward)
                    if len(x) > 0:
                        if delayed_reward > 0:
                            pos_learning_cnt += 1
                        else:
                            neg_learning_cnt += 1
                        # Update Policy neural network
                        loss += self.policy_network.train_on_batch(x, y)
                        memory_learning_idx.append([itr_cnt, delayed_reward])
                    batch_size = 0
            # Visualize the information about epoches
            num_epoches_digit = len(str(num_epoches))
            epoch_str = str(epoch + 1).rjust(num_epoches_digit, '0')

            self.visualizer.plot(epoch_str=epoch_str,
                                 num_epoches=num_epoches,
                                 epsilon=epsilon,
                                 action_list=Agent.ACTIONS,
                                 actions=memory_action,
                                 num_stocks=memory_num_stocks,
                                 outvals=memory_prob,
                                 exps=memory_exp_idx,
                                 learning=memory_learning_idx,
                                 initial_balance=self.agent.initial_balance,
                                 pvs=memory_pv)
            self.visualizer.save(
                os.path.join(
                    epoch_summary_dir,
                    'epoch_summary_%s_%s.png' % (settings.timestr, epoch_str)))

            # Record the information about epoches in log
            if pos_learning_cnt + neg_learning_cnt > 0:
                loss /= pos_learning_cnt + neg_learning_cnt
            logging.info(
                "[Epoch %s/%s]\tEpsilon:%.4f\t#Expl.:%d/%d\t"
                "#Buy:%d\t#Sell:%d\t#Hold:%d\t"
                "#Stocks:%d\tPV:%s\t"
                "POS:%s\tNEG:%s\tLoss:%10.6f" %
                (epoch_str, num_epoches, epsilon, exploration_cnt, itr_cnt,
                 self.agent.num_buy, self.agent.num_sell, self.agent.num_hold,
                 self.agent.num_stocks,
                 locale.currency(self.agent.portfolio_value, grouping=True),
                 pos_learning_cnt, neg_learning_cnt, loss))

            # Update the information about training
            max_portfolio_value = max(max_portfolio_value,
                                      self.agent.portfolio_value)
            if self.agent.portfolio_value > self.agent.initial_balance:
                epoch_win_cnt += 1

        # Record the information about training in log
        logging.info("Max PV: %s, \t # Win: %d" % (locale.currency(
            max_portfolio_value, grouping=True), epoch_win_cnt))
Ejemplo n.º 32
0
def usd(aNumber):
    return locale.currency(aNumber, grouping=True)
Ejemplo n.º 33
0
def int_to_dollar(x):
    return locale.currency(x, grouping=True)
Ejemplo n.º 34
0
def currency_default(value, decimals=True):
    if decimals:
        return locale.currency(value, symbol=True,
                               grouping=True).decode('utf8')
    else:
        return currency_symbol() + locale.format("%d", value, grouping=True)
Ejemplo n.º 35
0
def run(base_dir, start_gunicorn_app=True, options=None):
    options = options or {}

    # Store a pidfile before doing anything else
    store_pidfile(base_dir)

    # For dumping stacktraces
    register_diag_handlers()

    # Capture warnings to log files
    logging.captureWarnings(True)

    # Start initializing the server now
    os.chdir(base_dir)

    try:
        import pymysql
        pymysql.install_as_MySQLdb()
    except ImportError:
        pass

    # We're doing it here even if someone doesn't use PostgreSQL at all
    # so we're not suprised when someone suddenly starts using PG.
    # TODO: Make sure it's registered for each of the subprocess
    psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
    psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)

    # We know we don't need warnings because users may explicitly configure no certificate validation.
    # We don't want for urllib3 to warn us about it.
    import requests as _r
    _r.packages.urllib3.disable_warnings()

    repo_location = os.path.join(base_dir, 'config', 'repo')

    # Configure the logging first, before configuring the actual server.
    logging.addLevelName('TRACE1', TRACE1)
    logging_conf_path = os.path.join(repo_location, 'logging.conf')

    with open(logging_conf_path) as f:
        logging_config = yaml.load(f)
        dictConfig(logging_config)

    logger = logging.getLogger(__name__)
    kvdb_logger = logging.getLogger('zato_kvdb')

    crypto_manager = ServerCryptoManager(repo_location,
                                         secret_key=options['secret_key'],
                                         stdin_data=read_stdin_data())
    secrets_config = ConfigObj(os.path.join(repo_location, 'secrets.conf'),
                               use_zato=False)
    server_config = get_config(repo_location,
                               'server.conf',
                               crypto_manager=crypto_manager,
                               secrets_conf=secrets_config)
    pickup_config = get_config(repo_location, 'pickup.conf')
    sio_config = get_config(repo_location,
                            'simple-io.conf',
                            needs_user_config=False)
    sso_config = get_config(repo_location, 'sso.conf', needs_user_config=False)
    normalize_sso_config(sso_config)

    server_config.main.token = server_config.main.token.encode('utf8')

    # Do not proceed unless we can be certain our own preferred address or IP can be obtained.
    preferred_address = server_config.preferred_address.get('address')

    if not preferred_address:
        preferred_address = get_preferred_ip(server_config.main.gunicorn_bind,
                                             server_config.preferred_address)

    if not preferred_address and not server_config.server_to_server.boot_if_preferred_not_found:
        msg = 'Unable to start the server. Could not obtain a preferred address, please configure [bind_options] in server.conf'
        logger.warn(msg)
        raise Exception(msg)

    # Create the startup callable tool as soon as practical
    startup_callable_tool = StartupCallableTool(server_config)

    # Run the hook before there is any server object created
    startup_callable_tool.invoke(SERVER_STARTUP.PHASE.FS_CONFIG_ONLY,
                                 kwargs={
                                     'server_config': server_config,
                                     'pickup_config': pickup_config,
                                     'sio_config': sio_config,
                                     'sso_config': sso_config,
                                 })

    # New in 2.0 - Start monitoring as soon as possible
    if server_config.get('newrelic', {}).get('config'):
        import newrelic.agent
        newrelic.agent.initialize(server_config.newrelic.config,
                                  server_config.newrelic.environment or None,
                                  server_config.newrelic.ignore_errors or None,
                                  server_config.newrelic.log_file or None,
                                  server_config.newrelic.log_level or None)

    # New in 2.0 - override gunicorn-set Server HTTP header
    gunicorn.SERVER_SOFTWARE = server_config.misc.get('http_server_header',
                                                      'Zato')

    # Store KVDB config in logs, possibly replacing its password if told to
    kvdb_config = get_kvdb_config_for_log(server_config.kvdb)
    kvdb_logger.info('Main process config `%s`', kvdb_config)

    # New in 2.0 hence optional
    user_locale = server_config.misc.get('locale', None)
    if user_locale:
        locale.setlocale(locale.LC_ALL, user_locale)
        value = 12345
        logger.info('Locale is `%s`, amount of %s -> `%s`', user_locale, value,
                    locale.currency(value, grouping=True).decode('utf-8'))

    # Makes queries against Postgres asynchronous
    if asbool(server_config.odb.use_async_driver
              ) and server_config.odb.engine == 'postgresql':
        make_psycopg_green()

    if server_config.misc.http_proxy:
        os.environ['http_proxy'] = server_config.misc.http_proxy

    # Basic components needed for the server to boot up
    kvdb = KVDB()
    odb_manager = ODBManager(well_known_data=ZATO_CRYPTO_WELL_KNOWN_DATA)
    sql_pool_store = PoolStore()

    service_store = ServiceStore()
    service_store.odb = odb_manager
    service_store.services = {}

    server = ParallelServer()
    server.odb = odb_manager
    server.service_store = service_store
    server.service_store.server = server
    server.sql_pool_store = sql_pool_store
    server.service_modules = []
    server.kvdb = kvdb
    server.user_config = Bunch()

    # Assigned here because it is a circular dependency
    odb_manager.parallel_server = server

    zato_gunicorn_app = ZatoGunicornApplication(server, repo_location,
                                                server_config.main,
                                                server_config.crypto)

    server.has_fg = options.get('fg')
    server.crypto_manager = crypto_manager
    server.odb_data = server_config.odb
    server.host = zato_gunicorn_app.zato_host
    server.port = zato_gunicorn_app.zato_port
    server.repo_location = repo_location
    server.user_conf_location = os.path.join(server.repo_location, 'user-conf')
    server.base_dir = base_dir
    server.logs_dir = os.path.join(server.base_dir, 'logs')
    server.tls_dir = os.path.join(server.base_dir, 'config', 'repo', 'tls')
    server.static_dir = os.path.join(server.base_dir, 'config', 'repo',
                                     'static')
    server.json_schema_dir = os.path.join(server.base_dir, 'config', 'repo',
                                          'schema', 'json-schema')
    server.fs_server_config = server_config
    server.fs_sql_config = get_config(repo_location,
                                      'sql.conf',
                                      needs_user_config=False)
    server.pickup_config = pickup_config
    server.logging_config = logging_config
    server.logging_conf_path = logging_conf_path
    server.sio_config = sio_config
    server.sso_config = sso_config
    server.user_config.update(server_config.user_config_items)
    server.preferred_address = preferred_address
    server.sync_internal = options['sync_internal']
    server.jwt_secret = server.fs_server_config.misc.jwt_secret.encode('utf8')
    server.startup_callable_tool = startup_callable_tool
    server.is_sso_enabled = server.fs_server_config.component_enabled.sso
    if server.is_sso_enabled:
        server.sso_api = SSOAPI(server, sso_config, None,
                                crypto_manager.encrypt, crypto_manager.decrypt,
                                crypto_manager.hash_secret,
                                crypto_manager.verify_hash, new_user_id)

    # Remove all locks possibly left over by previous server instances
    kvdb.component = 'master-proc'
    clear_locks(kvdb, server_config.main.token, server_config.kvdb,
                crypto_manager.decrypt)

    # New in 2.0.8
    server.return_tracebacks = asbool(
        server_config.misc.get('return_tracebacks', True))
    server.default_error_message = server_config.misc.get(
        'default_error_message', 'An error has occurred')

    # Turn the repo dir into an actual repository and commit any new/modified files
    RepoManager(repo_location).ensure_repo_consistency()

    # New in 2.0 so it's optional.
    profiler_enabled = server_config.get('profiler', {}).get('enabled', False)

    # New in 2.0 so it's optional.
    sentry_config = server_config.get('sentry')

    dsn = sentry_config.pop('dsn', None)
    if dsn:

        from raven import Client
        from raven.handlers.logging import SentryHandler

        handler_level = sentry_config.pop('level')
        client = Client(dsn, **sentry_config)

        handler = SentryHandler(client=client)
        handler.setLevel(getattr(logging, handler_level))

        logger = logging.getLogger('')
        logger.addHandler(handler)

        for name in logging.Logger.manager.loggerDict:
            if name.startswith('zato'):
                logger = logging.getLogger(name)
                logger.addHandler(handler)

    if asbool(profiler_enabled):
        profiler_dir = os.path.abspath(
            os.path.join(base_dir, server_config.profiler.profiler_dir))
        server.on_wsgi_request = ProfileMiddleware(
            server.on_wsgi_request,
            log_filename=os.path.join(profiler_dir,
                                      server_config.profiler.log_filename),
            cachegrind_filename=os.path.join(
                profiler_dir, server_config.profiler.cachegrind_filename),
            discard_first_request=server_config.profiler.discard_first_request,
            flush_at_shutdown=server_config.profiler.flush_at_shutdown,
            path=server_config.profiler.url_path,
            unwind=server_config.profiler.unwind)

    # New in 2.0 - set environmet variables for servers to inherit
    os_environ = server_config.get('os_environ', {})
    for key, value in os_environ.items():
        os.environ[key] = value

    # Run the hook right before the Gunicorn-level server actually starts
    startup_callable_tool.invoke(SERVER_STARTUP.PHASE.IMPL_BEFORE_RUN,
                                 kwargs={
                                     'zato_gunicorn_app': zato_gunicorn_app,
                                 })

    # Run the app at last
    if start_gunicorn_app:
        zato_gunicorn_app.run()
    else:
        return zato_gunicorn_app.zato_wsgi_app
Ejemplo n.º 36
0
def ctpdf(request):
    id = request.GET["id"]
    contrato = Contratos.objects.get(pk=id)
    im = contrato.inmueble
    cp = contrato.cliente_propietario
    ca = contrato.cliente_arrendatario
    ar = cp.asesor
    cd1 = contrato.codeudor1
    cd2 = contrato.codeudor2
    cd3 = contrato.codeudor3

    fecha_inicio = contrato.fecha_inicio
    fecha_vigencia = contrato.fecha_vigencia

    locale.setlocale(locale.LC_ALL, '')

    parte_arrendadora = ar.nombre + ", " + ar.tipo_identificacion + " " + ar.identificacion
    parte_arrendadora = parte_arrendadora + "<br />"

    if ar.telefono_movil and ar.telefono_movil != "0":
        parte_arrendadora = parte_arrendadora + "TELEFONO MOVIL: " + ar.telefono_movil + "<br />"
    if ar.telefono_fijo and ar.telefono_fijo != "0":
        parte_arrendadora = parte_arrendadora + "TELEFONO FIJO: " + ar.telefono_fijo + "<br />"

    parte_arrendataria = ca.nombre + ", " + ca.tipo_identificacion + " " + ca.identificacion
    parte_arrendataria = parte_arrendataria + "<br />"

    if ca.telefono_movil and ca.telefono_movil != "0":
        parte_arrendataria = parte_arrendataria + "TELEFONO MOVIL: " + ca.telefono_movil + "<br />"
    if ca.telefono_fijo and ca.telefono_fijo != "0":
        parte_arrendataria = parte_arrendataria + "TELEFONO FIJO: " + ca.telefono_fijo + "<br />"

    sar = "" + contrato.servicios_arrendador

    sar = sar.replace("'", "")
    sar = sar.replace("[", "")
    sar = sar.replace("]", "")

    sa = "" + contrato.servicios_arrendatario

    sa = sa.replace("'", "")
    sa = sa.replace("[", "")
    sa = sa.replace("]", "")

    codeudor1 = None
    codeudor2 = None
    codeudor3 = None

    if cd1:
        codeudor1 = "{}, {} {}".format(cd1.nombre, cd1.tipo_identificacion,
                                       cd1.identificacion)
    if cd2:
        codeudor2 = "{}, {} {}".format(cd2.nombre, cd2.tipo_identificacion,
                                       cd2.identificacion)
    if cd3:
        codeudor3 = "{}, {} {}".format(cd3.nombre, cd3.tipo_identificacion,
                                       cd3.identificacion)

    context = {
        'ar':
        ar,
        'ca':
        ca,
        'arrendador':
        ar.nombre + ", " + ar.tipo_identificacion + " " + ar.identificacion,
        'arrendatario':
        ca.nombre + ", " + ca.tipo_identificacion + " " + ca.identificacion,
        'inmueble':
        im,
        'direccion_inmueble':
        im.direccion + ", " + im.ciudad + ", " + im.departamento + ", " +
        im.pais,
        'precio_canon':
        '{} ({})'.format(
            numero_a_moneda(contrato.precio_canon).upper(),
            locale.currency(contrato.precio_canon,
                            grouping=True).replace('+', ' '),
        ),
        'termino_contrato':
        int(round((fecha_vigencia - fecha_inicio).days / 30, 0)),
        'fecha_inicio':
        str(fecha_inicio),
        'fecha_vencimiento':
        str(fecha_vigencia),
        'servicios_arrendador':
        sar,
        'servicios_arrendatario':
        sa,
        'parte_arrendadora':
        parte_arrendadora,
        'parte_arrendataria':
        parte_arrendataria,
        'cd1':
        cd1,
        'cd2':
        cd2,
        'cd3':
        cd3,
        'codeudor1':
        codeudor1,
        'codeudor2':
        codeudor2,
        'codeudor3':
        codeudor3
    }

    rp = render_to_string("contrato/contrato2.html", context)

    file = os.path.join(tempfile.gettempdir(), "contrato{}.pdf".format(im.id))

    tipo_vivienda = 'VIVIENDA URBANA'

    if im.tipo_inmueble == 'LOCAL':
        tipo_vivienda = 'LOCAL COMERCIAL'

    id_im = str(im.id).zfill(4)

    pdfkit.from_string(
        rp, file, {
            'title':
            'CONTRATO DE ARRENDAMIENTO DE {} N° {}-2'.format(
                tipo_vivienda, id_im),
            '--header-html':
            'http://127.0.0.1:{}/lsb/header.php'.format(80),
            '--header-spacing':
            '10',
            '--footer-html':
            'http://127.0.0.1:{}/lsb/footer.php'.format(80),
            '--footer-spacing':
            '5'
        })

    return FileResponse(open(file, "rb"),
                        as_attachment=True,
                        filename="contrato - {}.pdf".format(id_im),
                        content_type="application/pdf")
Ejemplo n.º 37
0
def index():
    # print(request.headers.get('User-Agent'))
    isMobile = (request.headers.get('User-Agent').find('Mobile') > 0)

    dataHoje = datetime.date.today()
    mes = dataHoje.month
    ano = dataHoje.year
    ultimoDiaMes = calendar.monthrange(ano, mes)[1]

    dataInicioMes = datetime.date(year=ano, month=mes, day=1)
    dataFimMes = datetime.date(year=ano, month=mes, day=ultimoDiaMes)

    # Valore usados no Tiles.html
    lucroDia = getValLucroPeriodo(dataHoje)
    lucroMes = getValLucroPeriodo(dataInicioMes, dataFinal=dataHoje)
    lucratividade = {'dia': lucroDia, 'mes': lucroMes}

    # VERIFICADO
    vendasDia = getTotalVendido(dataHoje)
    vendasDia = locale.currency(vendasDia, grouping=True)
    vendasMes = getTotalVendido(dataInicioMes, dataFinal=dataHoje)
    vendasMes = locale.currency(vendasMes, grouping=True)
    valVendido = {'dia': vendasDia, 'mes': vendasMes}

    # VERIFICADO
    notasDia = getQtdadeNotas(dataHoje)
    notasMes = getQtdadeNotas('{}-{}-01'.format(dataHoje.year, dataHoje.month),
                              dataFinal=dataHoje)
    qtdNotas = {'dia': notasDia, 'mes': notasMes}

    # VERIFICADO
    receberDia = getTotalContasReceberPeriodo(dataHoje)
    receberDia = locale.currency(receberDia, grouping=True)
    receberMes = getTotalContasReceberPeriodo(dataInicioMes, dataHoje)
    receberMes = locale.currency(receberMes, grouping=True)
    receber = {'dia': receberDia, 'mes': receberMes}

    # VERIFICADO
    pagarDia = getTotalContasPagarPeriodo(dataHoje)
    pagarDia = locale.currency(pagarDia, grouping=True)
    pagarMes = getTotalContasPagarPeriodo(dataInicioMes, dataHoje)
    pagarMes = locale.currency(pagarMes, grouping=True)
    pagar = {'dia': pagarDia, 'mes': pagarMes}

    # VERIFICADO
    estoqueBaixoTipoA = getProdutosEstoqueBaixo(tipoGiro='A')
    estoqueBaixoTipoAZerados = getProdutosEstoqueBaixo(tipoGiro='A',
                                                       somenteZerados=True)
    estoqueBaixo = {
        'todos': estoqueBaixoTipoA.count(),
        'zerados': estoqueBaixoTipoAZerados.count()
    }

    # Valor Vendido por periodo
    metaTitulo = "Não existe Meta cadastrada para o período"
    maxValue = 1.0
    vendas = getTotalVendido(dataInicioMes, dataFinal=dataFimMes)
    meta = getValMeta(12)
    if meta:
        metaTitulo = meta.descricao.capitalize()
        maxValue = float(meta.valTotalMeta)
        vendas = getTotalVendido(meta.dataInicial, dataFinal=meta.dataFinal)
    gauge = getHalfPie(
        metaTitulo,
        {'Total': {
            'value': vendas,
            'max_value': maxValue,
            'label': maxValue
        }})

    # Qtdade de Notas por periodo
    qtdNotasGauge = getHalfPie(
        'Qtdade de Notas Faturadas',
        {'Qtdade': {
            'value': notasDia,
            'max_value': 30000
        }})

    # Valor Vendido por ano agrupado por mês
    anoPassado = ano - 1
    anoRetrasado = ano - 2
    vendasAnoAtual = getTotalVendasDoAnoPorMes(ano)
    vendasAnoPassado = getTotalVendasDoAnoPorMes(anoPassado)
    vendasAnoRetrasado = getTotalVendasDoAnoPorMes(anoRetrasado)
    listaDeValores = [(str(ano), vendasAnoAtual),
                      (str(anoPassado), vendasAnoPassado),
                      (str(anoRetrasado), vendasAnoRetrasado)]
    comparativoAnual = getChartVendasAnoMes(listaDeValores, isMobile=isMobile)

    # Vendas Externas por periodo
    # VERIFICADO
    vendasExternas = getVendasVendedores(dataInicioMes, dataFimMes, tipo='E')
    dataExternos = {}
    for vendedor in vendasExternas:
        dataExternos[vendedor.nome] = vendedor.total
    barChartsExternos = getHorizontalBar('Vendas por Vendedores Externos',
                                         dataExternos,
                                         isMobile=isMobile)

    # Vendas Internas por periodo
    # VERIFICADO
    vendasInternos = getVendasVendedores(dataInicioMes, dataFimMes, tipo='I')
    dataInternos = {}
    for vendedor in vendasInternos:
        dataInternos[vendedor.nome] = vendedor.total
    barChartsInternos = getHorizontalBar('Vendas por Vendedores Internos',
                                         dataInternos,
                                         isMobile=isMobile)

    meta_mes = locale.currency(maxValue, grouping=True)
    total_vendas = locale.currency(vendas, grouping=True)

    # Tabelas de Informações do Dashboard
    top10Produtos = getProdutosPorQtdSaida(dataInicioMes,
                                           dataFinal=dataHoje,
                                           limit=10)
    top10Clientes = getTotalCompraClientes(dataInicioMes,
                                           dataFinal=dataHoje,
                                           limit=10,
                                           convertToList=True)

    result = {
        'gauge': gauge,
        'notas': qtdNotasGauge,
        'barChartsExternos': barChartsExternos,
        'barChartsInternos': barChartsInternos,
        'total_vendas': total_vendas,
        'meta_mes': meta_mes,
        'qtdNotas': qtdNotas,
        'lucratividade': lucratividade,
        'valVendido': valVendido,
        'receber': receber,
        'pagar': pagar,
        'top10Produtos': top10Produtos,
        'top10Clientes': top10Clientes,
        'estoqueBaixo': estoqueBaixo,
        'comparativoAnual': comparativoAnual
    }
    return render_template('dashboard/main.html', **result)
Ejemplo n.º 38
0
def currency(value):
    if value:
        return locale.currency(value, grouping=True)
    else:
        return locale.currency(0.00, grouping=True)
Ejemplo n.º 39
0
def pretty_money(m):
    locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
    return locale.currency(m, grouping=True)
Ejemplo n.º 40
0
    def fit(self,
            num_epoches=1000,
            max_memory=60,
            balance=10000000,
            discount_factor=0,
            start_epsilon=.5,
            learning=True):
        logger.info(
            "LR: {lr}, DF: {discount_factor}, "
            "TU: [{min_trading_unit}, {max_trading_unit}], "
            "DRT: {delayed_reward_threshold}".format(
                lr=self.policy_network.lr,
                discount_factor=discount_factor,
                min_trading_unit=self.agent.min_trading_unit,
                max_trading_unit=self.agent.max_trading_unit,
                delayed_reward_threshold=self.agent.delayed_reward_threshold))

        # 가시화 준비
        # 차트 데이터는 변하지 않으므로 미리 가시화
        self.visualizer.prepare(self.environment.chart_data)

        # 가시화 결과 저장할 폴더 준비
        epoch_summary_dir = os.path.join(
            settings.BASE_DIR, 'epoch_summary/%s/epoch_summary_%s' %
            (self.stock_code, settings.timestr))
        if not os.path.isdir(epoch_summary_dir):
            os.makedirs(epoch_summary_dir)

        # 에이전트 초기 자본금 설정
        self.agent.set_balance(balance)

        # 학습에 대한 정보 초기화
        max_portfolio_value = 0
        epoch_win_cnt = 0

        # 학습 반복
        for epoch in range(num_epoches):
            # 에포크 관련 정보 초기화
            loss = 0.
            itr_cnt = 0
            win_cnt = 0
            exploration_cnt = 0
            batch_size = 0
            pos_learning_cnt = 0
            neg_learning_cnt = 0

            # 메모리 초기화
            memory_sample = []
            memory_action = []
            memory_reward = []
            memory_prob = []
            memory_pv = []
            memory_num_stocks = []
            memory_exp_idx = []
            memory_learning_idx = []

            # 환경, 에이전트, 정책 신경망 초기화
            self.environment.reset()
            self.agent.reset()
            self.policy_network.reset()
            self.reset()

            # 가시화 초기화
            self.visualizer.clear([0, len(self.chart_data)])

            # 학습을 진행할 수록 탐험 비율 감소
            if learning:
                epsilon = start_epsilon * (1. - float(epoch) /
                                           (num_epoches - 1))
            else:
                epsilon = 0
            epsilon = 1

            while True:
                # 샘플 생성
                next_sample = self._build_sample()
                if next_sample is None:
                    break

                # 정책 신경망 또는 탐험에 의한 행동 결정
                action, confidence, exploration = self.agent.decide_action(
                    self.policy_network, self.sample, epsilon)

                # 결정한 행동을 수행하고 즉시 보상과 지연 보상 획득
                immediate_reward, delayed_reward = self.agent.act(
                    action, confidence)

                # 행동 및 행동에 대한 결과를 기억
                memory_sample.append(next_sample)
                memory_action.append(action)
                memory_reward.append(immediate_reward)
                memory_pv.append(self.agent.portfolio_value)
                memory_num_stocks.append(self.agent.num_stocks)
                memory = [
                    (memory_sample[i], memory_action[i], memory_reward[i])
                    for i in list(range(len(memory_action)))[-max_memory:]
                ]
                if exploration:
                    memory_exp_idx.append(itr_cnt)
                    memory_prob.append([np.nan] * Agent.NUM_ACTIONS)
                else:
                    memory_prob.append(self.policy_network.prob)

                # 반복에 대한 정보 갱신
                batch_size += 1
                itr_cnt += 1
                exploration_cnt += 1 if exploration else 0
                win_cnt += 1 if delayed_reward > 0 else 0

                # 학습 모드이고 지연 보상이 존재할 경우 정책 신경망 갱신
                if delayed_reward == 0 and batch_size >= max_memory:
                    delayed_reward = immediate_reward
                if learning and delayed_reward != 0:
                    # 배치 학습 데이터 크기
                    batch_size = min(batch_size, max_memory)
                    # 배치 학습 데이터 생성
                    x, y = self._get_batch(memory, batch_size, discount_factor,
                                           delayed_reward)
                    if len(x) > 0:
                        if delayed_reward > 0:
                            pos_learning_cnt += 1
                        else:
                            neg_learning_cnt += 1
                        # 정책 신경망 갱신
                        loss += self.policy_network.train_on_batch(x, y)
                        memory_learning_idx.append([itr_cnt, delayed_reward])
                    batch_size = 0

            # 에포크 관련 정보 가시화
            num_epoches_digit = len(str(num_epoches))
            epoch_str = str(epoch + 1).rjust(num_epoches_digit, '0')

            self.visualizer.plot(epoch_str=epoch_str,
                                 num_epoches=num_epoches,
                                 epsilon=epsilon,
                                 action_list=Agent.ACTIONS,
                                 actions=memory_action,
                                 num_stocks=memory_num_stocks,
                                 outvals=memory_prob,
                                 exps=memory_exp_idx,
                                 learning=memory_learning_idx,
                                 initial_balance=self.agent.initial_balance,
                                 pvs=memory_pv)
            self.visualizer.save(
                os.path.join(
                    epoch_summary_dir,
                    'epoch_summary_%s_%s.png' % (settings.timestr, epoch_str)))

            # 에포크 관련 정보 로그 기록
            if pos_learning_cnt + neg_learning_cnt > 0:
                loss /= pos_learning_cnt + neg_learning_cnt
            logger.info(
                "[Epoch %s/%s]\tEpsilon:%.4f\t#Expl.:%d/%d\t"
                "#Buy:%d\t#Sell:%d\t#Hold:%d\t"
                "#Stocks:%d\tPV:%s\t"
                "POS:%s\tNEG:%s\tLoss:%10.6f" %
                (epoch_str, num_epoches, epsilon, exploration_cnt, itr_cnt,
                 self.agent.num_buy, self.agent.num_sell, self.agent.num_hold,
                 self.agent.num_stocks,
                 locale.currency(self.agent.portfolio_value, grouping=True),
                 pos_learning_cnt, neg_learning_cnt, loss))

            # 학습 관련 정보 갱신
            max_portfolio_value = max(max_portfolio_value,
                                      self.agent.portfolio_value)
            if self.agent.portfolio_value > self.agent.initial_balance:
                epoch_win_cnt += 1

        # 학습 관련 정보 로그 기록
        logger.info("Max PV: %s, \t # Win: %d" % (locale.currency(
            max_portfolio_value, grouping=True), epoch_win_cnt))
Ejemplo n.º 41
0
def p(value):
    return locale.currency(value, grouping=True)
Ejemplo n.º 42
0
def process_address():
    address = request.args["address"]

    county, state, city, formatted_address, latitude, longitude = break_address(
        address)

    anarghya = {}
    location = county[:county.index(' County')] + " , " + state
    main_score = store[location]["score"]
    anarghya[formatted_address] = [latitude, longitude, main_score]
    price = get_address_price(address, city + state)
    # find x neighboring counties, use the dmatrix
    from closest import closest_k
    closest_neighbors = closest_k(location)
    from collections import OrderedDict
    scores = []
    for neighbor in closest_neighbors:
        scores.append((neighbor, store[neighbor]["score"]))
    scores.sort(key=lambda x: x[1], reverse=True)
    ordered_scores = OrderedDict()
    for i, score in enumerate(scores):
        ordered_scores[scores[i][0]] = scores[i][1]
    scores = ordered_scores
    # query address for price
    price = get_address_price(address, city + " " + state)
    if 'error' in price.lower():
        flash(
            "Housing data could not be found. Please try a different house. ")
        return redirect(url_for('home'))
    # query all closest_neighbors for price
    final = []
    final.append({
        "lat": latitude,
        "lng": longitude,
        "street": formatted_address,
        "score": round(main_score, 2),
        "price": locale.currency(price[1], grouping=True)
    })
    content = None
    prices = {}
    if state == "CA":
        with open("addresses.json") as file:
            content = json.load(file)
        import copy
        cn = copy.deepcopy(closest_neighbors)
        for i, n in enumerate(cn):
            cn[i] = n.replace(" ", "")
        cn = set(cn)
        for item, address in content.items():

            if item.replace(" ", "") not in cn:
                continue
            try:

                old = address
                address = address.split(',')
                city_state = address[1] + " CA"
                address = address[0]
                result = get_address_price(address, city_state)
                prices[old] = (result[1] if result[0] != 'error' else
                               (random.randint(200000, 600000)))
            except:
                prices[old] = (random.randint(200000, 600000))
    for neighbor, _score in ordered_scores.items():
        if content:
            street = content[neighbor] if neighbor in content else ""
        else:
            street = address
        price = round(prices[street]) if street in prices and prices else 0
        if price and street:
            county, state, city, formatted_address, latitude, longitude = break_address(
                street)
            anarghya[street] = [latitude, longitude, _score]
            final.append({
                "lat": latitude,
                "lng": longitude,
                "street": street,
                "score": round(_score, 2),
                "price": locale.currency(price, grouping=True)
            })

    return render_template('list.html', info=final, anarghya=anarghya)
Ejemplo n.º 43
0
def cur(x):
    return locale.currency(x, grouping=True)
Ejemplo n.º 44
0
def pound_string(value):
    """function will convert a value into a string of pounds and pence containing a £ sign"""
    total = locale.currency(value, grouping=True)
    return total
Ejemplo n.º 45
0
def formata_concurso_text(concurso):
    texto = """{0} - {1}

{2}

{3} Senas - prêmio: {4}
{5} Quinas - prêmio: {6}
{7} Quadras - prêmio: {8}

Valor Acumulado: {9}

Previsão de Prêmio: *{10}*

Próximo Sorteio: {11}

Próximo Concurso 0 ou 5: {12}
Valor Acumulado 0 ou 5: {13}

Acumulado Mega da Virada: {14}"""

    data_concurso = datetime.fromtimestamp(concurso["data"]/1000.0)
    data_proximo_concurso = datetime.fromtimestamp(
        concurso["dt_proximo_concurso"]/1000.0)

    locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')

    premio = valor = locale.currency(
        concurso["valor"], grouping=True, symbol=None)
    premio_quina = locale.currency(
        concurso["valor_quina"], grouping=True, symbol=None)
    premio_quadra = locale.currency(
        concurso["valor_quadra"], grouping=True, symbol=None)

    valor_acumulado = locale.currency(
        concurso["valor_acumulado"],
        grouping=True,
        symbol=None)

    valor_estimado = locale.currency(
        concurso["vr_estimativa"],
        grouping=True,
        symbol=None)

    valor_zero_cinco = locale.currency(
        concurso["ac_final_zero"],
        grouping=True,
        symbol=None)

    valor_mega_virada = locale.currency(
        concurso["vr_acumulado_especial"],
        grouping=True,
        symbol=None)

    if concurso["sorteioAcumulado"]:
        texto = "*Acumulou!!!*\n\n" + texto

    return texto.format(
        concurso["concurso"],
        data_concurso.strftime("%d/%m/%Y"),
        concurso["resultadoOrdenado"],
        concurso["ganhadores"],
        premio,
        concurso["ganhadores_quina"],
        premio_quina,
        concurso["ganhadores_quadra"],
        premio_quadra,
        valor_acumulado,
        valor_estimado,
        data_proximo_concurso.strftime("%d/%m/%Y"),
        concurso["prox_final_zero"],
        valor_zero_cinco,
        valor_mega_virada
    )
Ejemplo n.º 46
0
    def _get_data(self):


        res_partner_obj = self.env['res.partner']

        if self.partner_id:
            res_partner_ids = res_partner_obj.search([('id', '=', self.partner_id.id)])
            partner_name = res_partner_ids.name
        else:
            res_partner_ids = res_partner_obj.search([])
            partner_name = 'Todos'



        result = [
            {
            'partner_name': partner_name,
            'start': self.date_start,
            'end': self.date_end,
            }
        ]

        currency_obj = self.env['res.currency']
        currencys_ids = currency_obj.search([('active', '=', True)])


        for currency in currency_obj.browse(currencys_ids.ids):

            if self.partner_id:

                invoices_obj = self.env['account.invoice']
                invoices_ids = invoices_obj.search([
                    ('currency_id', '=', currency.id),
                    ('state', '=', 'open'),
                    ('partner_id', '=', self.partner_id.id),
                    ('date_invoice', '>=', self.date_start + ' 00:00:00'),
                    ('date_invoice', '<=', self.date_end + ' 23:59:59'),
                ], order='date_invoice')
            else:
                invoices_obj = self.env['account.invoice']
                invoices_ids = invoices_obj.search([
                    ('currency_id', '=', currency.id),
                    ('state', '=', 'open'),
                    ('date_invoice', '>=', self.date_start + ' 00:00:00'),
                    ('date_invoice', '<=', self.date_end + ' 23:59:59'),
                ], order='date_invoice')




            if invoices_ids:
                report_lines = []

                residual_total = 0.00
                monto_vencido_total = 0.00
                monto_30_total = 0.00
                monto_60_total = 0.00
                monto_90_total = 0.00
                monto_120_total = 0.00
                monto_150_total = 0.00
                monto_aplic_total = 0.00

                for invoice in invoices_ids:

                    residual_total += invoice.residual

                    monto_vencido = 0.00
                    monto_30 = 0.00
                    monto_60 = 0.00
                    monto_90 = 0.00
                    monto_120 = 0.00
                    monto_150 = 0.00
                    monto_aplic = 0.00
                    if invoice.date_due:
                        if (datetime.datetime.strptime(invoice.date_due,
                                                       "%Y-%m-%d")- datetime.datetime.now()).days < 0:
                            monto_vencido = invoice.residual
                            monto_vencido_total += monto_vencido

                        if (datetime.datetime.strptime(invoice.date_due,
                                                       "%Y-%m-%d") - datetime.datetime.now()).days > 0 and (
                                    datetime.datetime.strptime(invoice.date_due,
                                                        "%Y-%m-%d") - datetime.datetime.now()).days <= 30:
                            monto_30 = invoice.residual
                            monto_30_total += monto_30

                        if (datetime.datetime.strptime(invoice.date_due,
                                                        "%Y-%m-%d") - datetime.datetime.now()).days > 30 and (
                                datetime.datetime.strptime(invoice.date_due,
                                                        "%Y-%m-%d") - datetime.datetime.now()).days <= 60:
                            monto_60 = invoice.residual
                            monto_60_total += monto_60

                        if (datetime.datetime.strptime(invoice.date_due,
                                                       "%Y-%m-%d") - datetime.datetime.now()).days > 60 and (
                                    datetime.datetime.strptime(invoice.date_due,
                                                        "%Y-%m-%d") - datetime.datetime.now()).days <= 90:
                            monto_90 = invoice.residual
                            monto_90_total += monto_90

                        if (datetime.datetime.strptime(invoice.date_due,
                                                        "%Y-%m-%d") - datetime.datetime.now()).days > 90 and (
                                datetime.datetime.strptime(invoice.date_due,
                                                        "%Y-%m-%d") - datetime.datetime.now()).days <= 120:
                            monto_120 = invoice.residual
                            monto_120_total += monto_120

                        if (datetime.datetime.strptime(invoice.date_due,
                                                        "%Y-%m-%d") - datetime.datetime.now()).days > 120:
                            monto_150 = invoice.residual
                            monto_150_total += monto_150

                    else:
                        monto_vencido = invoice.residual
                        monto_vencido_total += monto_vencido







                    vals = {
                        'partner_ref':invoice.partner_id.ref,
                        'partner_name': invoice.partner_id.name,
                        'date': invoice.date_invoice,
                        'journal_name': invoice.journal_id.name,
                        'folio': invoice.number,
                        'folio_digital': invoice.number,
                        'date_due': invoice.date_due,
                        'currency_id' : invoice.currency_id.name,
                        'residual' : locale.currency(invoice.residual, grouping=True ),
                        'monto_vencido': locale.currency(monto_vencido, grouping=True ),
                        'monto_30': locale.currency(monto_30, grouping=True ),
                        'monto_60': locale.currency(monto_60, grouping=True ),
                        'monto_90': locale.currency(monto_90, grouping=True ),
                        'monto_120': locale.currency(monto_120, grouping=True ),
                        'monto_150': locale.currency(monto_150, grouping=True ),
                        'monto_aplic': locale.currency(monto_aplic, grouping=True ),
                    }
                    report_lines.append(vals)

                sorted_report_lines = sorted(report_lines, key=lambda invoice: invoice['date'])

                report_currency = {
                    'currency': currency.name,
                    'report_lines':sorted_report_lines,
                    'residual_total': locale.currency(residual_total, grouping=True ),
                    'monto_vencido_total': locale.currency(monto_vencido_total, grouping=True ),
                    'monto_30_total': locale.currency(monto_30_total, grouping=True ),
                    'monto_60_total': locale.currency(monto_60_total, grouping=True ),
                    'monto_90_total': locale.currency(monto_90_total, grouping=True ),
                    'monto_120_total': locale.currency(monto_120_total, grouping=True ),
                    'monto_150_total': locale.currency(monto_150_total, grouping=True ),
                    'monto_aplic_total': locale.currency(monto_aplic_total, grouping=True ),
                }
                result.append(report_currency)

        return result
Ejemplo n.º 47
0
            'Month': lastMonth
        }).toarray())[0]
        month_predict = regressor.predict(vec.transform({
            'Year': currentYear,
            'Month': currentMonth
        }).toarray())[0]
        print('bb')
        print(previous_predict)
        print('cc')
        print(month_predict)
        if (predict_heuristic(previous_predict, month_predict, actual_previous_value, actual_value)):
            results.append((
                customer,
                month_predict,
                actual_previous_value
            ))

    return results

if __name__ == '__main__':
    locale.setlocale(locale.LC_ALL, '')
    customers = missed_customers()
    print("here")
    # print(customers)
    for customer in  set(customers):
        print("{} was predicted to buy around {}, they bought only {}".format(
            customer[0],
            locale.currency(customer[1], grouping=True),
            locale.currency(customer[2], grouping=True)
        ))
 def test_overridden_locale_float(self):
     set_default_locale()
     self.assertEqual(currency(self.value_float), locale.currency(self.value_float, grouping=True))
Ejemplo n.º 49
0
def c_locale(zahl):
    return locale.currency(zahl, False, True)
Ejemplo n.º 50
0
    lot = int(orig_future_lot / 2)
    order = {
        'symbol':
        stock_id,
        'nse_symbol':
        'NSE:' + stock_id,
        'future_lot':
        future_lot,
        'orig_future_lot':
        orig_future_lot,
        'priority':
        priority,
        'trigger_price_pts':
        round(util.min_tick_size * round((200 / lot) / util.min_tick_size), 2),
        'traded_amount':
        locale.currency(last_close * lot, grouping=True),
        'last_close':
        last_close,
        'tag':
        None
    }
    orders.append(order)
    priority += 1
    time.sleep(1)

print('[')
for order in orders:
    print(' {')
    for k, v in order.items():
        print(
            "   '" + k + "':",
Ejemplo n.º 51
0
def format_cents(cents, user_locale='en_US.utf8'):
    locale.setlocale(locale.LC_ALL, user_locale)
    return locale.currency(cents / 100.0, symbol=False, grouping=True)
Ejemplo n.º 52
0
def currency(value):
    return locale.currency(value or 0,
                           symbol=True,
                           grouping=True,
                           international=False)
choice = "y"
while choice.lower() == "y":

    # get input from the user
    monthly_investment = float(input("Enter monthly investment:\t"))
    yearly_interest_rate = float(input("Enter yearly interest rate:\t"))
    years = int(input("Enter number of years:\t\t"))

    # convert yearly values to monthly values
    monthly_interest_rate = yearly_interest_rate / 12 / 100
    months = years * 12

    # calculate the future value
    future_value = 0
    for i in range(months):
        future_value = future_value + monthly_investment
        monthly_interest_amount = future_value * monthly_interest_rate
        future_value = future_value + monthly_interest_amount

    # format and display the result
    print("Future value:\t\t\t%s" %
          locale.currency(future_value, grouping=True))
    print()

    # see if the user wants to continue
    choice = input("Continue? (y/n): ")
    print()

print("Bye!")
Ejemplo n.º 54
0
# англосаксонская система
# 1,234.567
# европейская система
# 1.234,567

import locale

locale.setlocale(locale.LC_ALL, "de")  # для  Windows
# locale.setlocale(locale.LC_ALL, "de_DE")   # для MacOS

number = 12345.6789
formatted = locale.format("%f", number)
print(formatted)  # 12345,678900

formatted = locale.format("%.2f", number)
print(formatted)  # 12345,68

formatted = locale.format("%d", number)
print(formatted)  # 12345

formatted = locale.format("%e", number)
print(formatted)  # 1,234568e+04

money = 234.678
formatted = locale.currency(money)
print(formatted)  # 234,68 €
Ejemplo n.º 55
0
# Create a neural network that learns this relationship so that it would predict a 7 bedroom house as costing close to 400k etc.
# the house prices are scaled down. So the prediction is in 'hundreds of thousands'


def house_model(x_bed: int) -> float:
    """Predict the house prices

    A neural model that predicts house prices based on already known bedroom - price data set

    :param x_bed: number of bedrooms for which price needs to be predicted
    :return: [description]
    :rtype: [type]
    """
    bed_data = np.array([0, 1, 2, 3, 4, 5, 6], dtype=int)
    price_data = np.array([0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5], dtype=float)
    model = keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])
    model.compile(optimizer='sgd', loss='mean_squared_error')
    model.fit(bed_data, price_data, epochs=500)
    return float(model.predict(x_bed))


if __name__ == '__main__':
    print('House price prediction starts')
    bed_rooms = 7
    prediction = house_model([bed_rooms])

    locale.setlocale(locale.LC_ALL, '')
    # round to 7 points since unit is in hundreds of thousands
    predct_usd = locale.currency(round(prediction, 7) * 100000, grouping=True)

    print(f'Predicted house price for {bed_rooms} bed rooms is {predct_usd}')
def format_money(amount):
    return locale.currency(amount / 100.)
Ejemplo n.º 57
0
def sizing_cal(config, id, consum):
    mod_power = config['mod']

    irrad = irradbyID(id)

    dol = dolar_data('1')
    dolar_var = dol[0]

    #cálculo da Geração Mínima = (NGD (em Wh)/irrad)
    #calculation of minimum generation = (NGD/irrad)
    gmin = float(((consum * 100) / 3) / irrad)

    #definição da quantidade de paineis
    #defining quantities of panels
    modqt = math.ceil((gmin * 1.25) / mod_power)

    #pegando a info de preço para cada painel
    #retrieving price info for each panel
    mod_uniprice = panels.filter(pot=mod_power).values('value').get()

    #preço total dos paineis
    #panels' total price
    mod_totalprice = math.ceil((modqt * mod_uniprice['value'] * dolar_var))

    #dimensionamento potência do inversor
    #inverter power sizing
    pot_seg = gmin * 1.3

    invpower = inverters.filter(pot__gte=pot_seg)[0]  #r
    invpower = invpower.pot

    #preço do inversor
    #inverter's price
    invprice = inverters.filter(pot__gte=pot_seg)[0]  #r
    invprice = math.ceil(invprice.value)

    #evitação de CO2 mensal (em kg de CO2)
    #monthly CO2 emission avoidance (CO2 kg)
    eco = math.ceil(consum * 1630)  #r

    #area
    area_total = math.ceil(modqt * 1.942336)

    #pesos
    #weights
    modweight = mod_weight(modqt, mod_power, 'on')
    other_weight = math.ceil(modweight * 0.05)

    #payback
    total_cost = math.ceil(mod_totalprice + invprice)
    pb = thebigpayback(id, (modqt * mod_power), total_cost, True)

    #warnings
    dol_stat = dol[1]
    pb_stat = pb[2]
    both_equal = True if (dol_stat == pb_stat) else False

    if (both_equal == False):
        wrng = ("Os valores de " + ("Custo", "Payback")[dol_stat] +
                " podem estar defasados neste dimensionamento")
    else:
        wrng = (
            "Os valores de Custo e Payback podem estar defasados neste dimensionamento",
            False)[dol_stat]

    return [{
        "id": "price",
        "mod_price": mod_totalprice,
        "inv_price": invprice,
        "label": "Custo Estimado",
        "text": locale.currency(total_cost, grouping=True, symbol='R$')
    }, {
        "id": "mod",
        "mod_quant": modqt,
        "label": "Módulos",
        "text": modqt
    }, {
        "id": "inv",
        "inv_power": invpower,
        "label": "Inversor",
        "text": "%s W" % (int(invpower))
    }, {
        "id": "weight",
        "mod_weight": modweight,
        "other_weight": other_weight,
        "label": "Peso",
        "text": "%s kg" % (modweight + other_weight)
    }, {
        "id": "area",
        "area": area_total,
        "label": "Área",
        "text": "%s m²" % (area_total)
    }, {
        "id": "payback",
        "payback_yrs": pb[0],
        "payback_arrays": pb[1],
        "label": "Payback",
        "text": "%s anos" % (pb[0])
    }, {
        "id": "co2",
        "co2": eco,
        "label": "Evitação de CO²",
        "text": "%s kg/mês" % (eco)
    }, {
        "id": "warnings",
        "text": wrng
    }]
Ejemplo n.º 58
0
    return mean_squared_error(y_test, y_pred)


def modele():
    df_user, classifier, Ville, seloger, X_train, X_test, y_train, y_test, y_pred = input_data(
    )

    seloger, X_train, X_test, y_train, y_test = get_data(DATA_URL, Ville)

    # metrics
    score_rmse = RMSE(y_test, y_pred)

    # display prediction
    predict_prices = classifier.predict(df_user)

    return predict_prices, score_rmse


# Prediction
predict_prices, score_rmse = modele()

#afficher prediction
if st.checkbox('Prediction'):
    #st.subheader('Metrique du modele')
    #st.text("Justesse du modele")
    #st.write(round(score_rmse,2),"%")
    st.subheader("Prix du logement")
    l = locale.setlocale(locale.LC_ALL, '')  # avoir le bon currency format
    price = locale.currency(predict_prices[0], grouping=True)
    st.write("Le prix de vente du logement est estimé à {} €".format(price))
Ejemplo n.º 59
0
 def _test_currency(self, value, out, **format_opts):
     self.assertEqual(locale.currency(value, **format_opts), out)
Ejemplo n.º 60
0
def displayemail2(id):

        sf = Salesforce(app_settings['SF-USER'] +".plaidtest", app_settings['SF-PASS'], app_settings['SF-TOKEN'], domain = 'test')
        # get the email belonging to the contact for whom the project is for
        contact_query = sf.query("select Name, ID, (select name, email, MailingAddress from contacts) from account where ID IN (select Account__c from project__c where project__c.Id  = '"+id+"')")
        #link that will be sent in the email in order for the customer to go to payment portal
        email_link = "https://certasunpay.com/linkwithid/" + id
        templateLoader = jinja2.FileSystemLoader(searchpath = "/")
        templateEnv = jinja2.Environment(loader=templateLoader)
        ### get the rest of the data from the project in order to format the templated email
        query = sf.query("select id, Name, Cash_Down_Pmt_Status__c, Cash_Down_Pmt__c, Cash_Permit_Pmt_Status__c, Permit_Pmt__c, Cash_Final_Pmt_Status__c, Cash_final_Pmt__c from Project__c where ID =  '"+id+"'")
        #project down payment:
        p_down = query['records'][0]['Cash_Down_Pmt__c']
        #project down payment status:
        p_down_stat = query['records'][0]['Cash_Down_Pmt_Status__c']
        #project permit payment:
        p_permit = query['records'][0]['Permit_Pmt__c']
        #project permit payment status:
        p_permit_stat = query['records'][0]['Cash_Permit_Pmt_Status__c']
        #project final payment:
        p_final = query['records'][0]['Cash_Final_Pmt__c']
        #project final payment status:
        p_final_stat = query['records'][0]['Cash_Final_Pmt_Status__c']
        #concatonate a string to show the customers address
        address = str(contact_query['records'][0]['Contacts']['records'][0]['MailingAddress']['street']) + " " + str(contact_query['records'][0]['Contacts']['records'][0]['MailingAddress']['city']) + ", " + str(contact_query['records'][0]['Contacts']['records'][0]['MailingAddress']['state'])
        #Name of contact whom project belongs to:
        contact_name = contact_query['records'][0]['Contacts']['records'][0]['Name']
        #split the contact name to get first and last seperate
        contact_name_list = contact_name.split()
        #create an ACCOUNT object for this project
        email_recipient_account = ACCOUNT(contact_query['records'][0]['Name'], contact_name_list[0], contact_name_list[1])
        #set the objects down payment:
        email_recipient_account.dp = p_down
        #set objects down payment status:
        email_recipient_account.dpSTAT = setFrontEndStatus(p_down_stat)
        #set objects permit payment:
        email_recipient_account.pp = p_permit
        #set objects permit payment status:
        email_recipient_account.ppSTAT = setFrontEndStatus(p_permit_stat)
        #set objects final payment:
        email_recipient_account.fp = p_final
        #set objects final payment status:
        email_recipient_account.fpSTAT = setFrontEndStatus(p_final_stat)
        #use getDuePayment method to find out which payment will need to be paid next with logic in that method
        duepayment = email_recipient_account.getDuePayment()
        #use getnextpayment to get the value of the duepayment
        next_payment = email_recipient_account.getnextpayment()
        #locale is used to format currency
        locale.setlocale(locale.LC_ALL,'en_US.UTF-8')
        #format the next_payment from a float to a currency string
        next_payment = locale.currency(next_payment)
        #### create id's to reference images that will be embedded in email
        logoImage_cid = make_msgid()
        bg1Image_cid = make_msgid()
        facebook_cid = make_msgid()
        twitter_cid = make_msgid()
        ig_cid = make_msgid()
        #############
        #create the templated email
        html = render_template('emailtemplate1.html', name = contact_name, chargeAmount = next_payment, duePayment = duepayment, payment_link = email_link, address = address, logoImage_cid = logoImage_cid[1:-1], bg1Image_cid = bg1Image_cid[1:-1], facebook_cid = facebook_cid[1:-1]) #, twitter_cid = twitter_cid[1:-1], ig_cid = ig_cid[1:-1])
        display_html = render_template("email2.html",  name = contact_name, chargeAmount = next_payment, duePayment = duepayment, payment_link = email_link, address = address)
        with open("my_new_file.html", "w") as fh:
            fh.write(display_html)
        os.system('my_new_file.html')
        my_input = input('Do you want to send this email (Y/N)')
        if(my_input == 'Y' or my_input = 'y'):
            #instantiate an EmailMessage OBject
            msg = EmailMessage()
            #Email's subject:
            msg['Subject'] = 'Pay Certasun'
            #Email address message will be sent from
            msg['From'] = '*****@*****.**'#mail_settings['MAIL_USERNAME']
                ############# change back but for testing send to my email ###################
            #Address Email will be sent to
            msg['To'] = "*****@*****.**"#email
            #############################################################################
            #Email messages preamble
            msg.preamble = "Certasun"
            #set the plain text as an empty string
            msg.set_content("")
            #set the templated html of the message
            msg.add_alternative(html, subtype = 'html')
            ############# Embed the images into the email msg###################
            with open('static/img/CertasunLogo.png', 'rb') as fp:
                msg.get_payload()[1].add_related(fp.read(), 'image','png',cid=logoImage_cid)
            with open('static/img/bg1.png', 'rb') as fp:
                msg.get_payload()[1].add_related(fp.read(), 'image', 'png', cid = bg1Image_cid)
            with open('static/img/free_ico_facebook.jpg', 'rb') as fp:
                msg.get_payload()[1].add_related(fp.read(), 'image', 'jpg', cid = facebook_cid)
            smtp = smtplib.SMTP_SSL('smtp.gmail.com', 0)
            smtp.ehlo()
            #start tls which means message will be encrypted
            #smtp.starttls()
            #login to the AWS SES account
            smtp.login('*****@*****.**', 'GoSolar1')
            #send the message, first parameter is who it is from, 2nd is who is is two and the thirsd is the content of the message
            smtp.sendmail("*****@*****.**", '*****@*****.**', msg.as_string())
            #shutdown the connection to the smtp server
            smtp.quit()
        return render_template('email2.html', name = contact_name, chargeAmount = next_payment, duePayment = duepayment, payment_link = email_link, address = address, logoImage_cid = logoImage_cid[1:-1], bg1Image_cid = bg1Image_cid[1:-1], facebook_cid = facebook_cid[1:-1])