def frange(start,stop,step): # генератор для дробных чисел start=dec(str(start)) # xrange не поддерживает float stop=dec(str(stop)) step=dec(str(step)) while start<stop: start+=step yield float(start)
def encode(self, s): l = int(dec(len(s)) * self.mag_num) res = [str(ord(c) * l) for c in s] # how slow will this make this hasher? decimal.getcontext().prec = 77 d = dec(''.join(res)).rotate(-1) return sane_hex(d)[:self.max_len]
def encode(self, s): l = int(dec(len(s)) * self.mag_num) res = ''.join([str(hash(c) * l) for c in s]).replace('-', '56') # Is speed going to be a problem here? decimal.getcontext().prec = 116 d = dec(res).rotate(-2) return sane_hex(d)[:self.max_len]
def sort_and_batch(self, resource, context, results): # Calculate the probable and assured amount self.assured = dec('0.0') self.probable = dec('0.0') for brain in results.get_documents(): self.assured += brain.crm_p_assured self.probable += brain.crm_p_probable proxy = super(CRM_SearchContacts, self) return proxy.sort_and_batch(resource, context, results)
def countDer(n): global der der = [dec('0') for i in range(n + 3)] der[0] = dec('1') der[1] = dec('0') der[2] = dec('1') for i in range(3, n + 1): der[i] = dec(i - 1) * (der[i - 1] + der[i - 2]) return der[n]
def run(self): i = 0 while i < self._requests: for e in self._list: if self._stop: return self.count += 1 payload = {} if 'params' in e: for p in e['params']: payload.update({p['name']: p['value']}) files = {} if 'files' in e: for f in e['files']: path, name = os.path.split(f['value']) try: files[f['name']] = (name, open(f['value'], 'rb')) except: if self._log: logging.error("Unable to read file: " + f['value']) try: if e['type'] == "get": req = requests.get(e['url']) elif e['type'] == "delete": req = requests.delete(e['url']) elif e['type'] == "put": req = requests.put(e['url'], data=payload, files=files) else: req = requests.post(e['url'], data=payload, files=files) res = {'url': e['url'], 'data': payload, 'status': req.status_code, 'content': req.text, 'time': (dec(req.elapsed.microseconds) / 1000 / 1000)} if self._log: logging.debug(res) except Exception as ex: try: elapsed = dec(req.elapsed.microseconds) / 1000 / 1000 except NameError: elapsed = dec(0) if str(ex.message.reason) not in self.errors: self.errors.append(str(ex.message.reason)) res = {'url': e['url'], 'data': payload, 'status': 0, 'error': str(ex.message.reason), 'time': elapsed} if self._log: logging.error(res) self.results.append(res) i += 1 if i == self._requests: return return
def forwards(self, orm): "Write your forwards migration here" for dme in orm.Grain.objects.filter(name__contains='Dry Malt Extract'): dme.volume_to_weight_conversion = dec(4) dme.save() for lme in orm.Grain.objects.filter(name__contains='Liquid Malt Extract'): lme.volume_to_weight_conversion = dec(12) lme.save() for honey in orm.Grain.objects.filter(name__icontains='Honey').exclude(name__icontains='Malt'): honey.volume_to_weight_conversion = dec(12) honey.save() for sap in orm.Grain.objects.filter(name='Maple Sap'): sap.volume_to_weight_conversion = dec('8.5') sap.save() for name in ('Treacle', 'Molasses', 'Maple Syrup', 'Golden Syrup'): for fermentable in orm.Grain.objects.filter(name__contains=name): fermentable.volume_to_weight_conversion = dec(12) fermentable.save() for name in ('Corn Sugar', 'Dextrose', 'Malto Dextrin', 'Invert Sugar'): for dex in orm.Grain.objects.filter(name__startswith=name): dex.volume_to_weight_conversion = dec(6) dex.save() for name in ('Cane (Beet) Sugar', 'Sucrose'): for sugar in orm.Grain.objects.filter(name__startswith=name): sugar.volume_to_weight_conversion = dec(7) sugar.save() for name in ('Turbinado', 'Brown Sugar', 'Demerara'): for sugar in orm.Grain.objects.filter(name__contains=name): sugar.volume_to_weight_conversion = dec(7) sugar.save()
def forwards(self, orm): "Write your forwards migration here" for dme in orm.Grain.objects.filter(name__contains="Dry Malt Extract"): dme.volume_to_weight_conversion = dec(4) dme.save() for lme in orm.Grain.objects.filter(name__contains="Liquid Malt Extract"): lme.volume_to_weight_conversion = dec(12) lme.save() for honey in orm.Grain.objects.filter(name__icontains="Honey").exclude(name__icontains="Malt"): honey.volume_to_weight_conversion = dec(12) honey.save() for sap in orm.Grain.objects.filter(name="Maple Sap"): sap.volume_to_weight_conversion = dec("8.5") sap.save() for name in ("Treacle", "Molasses", "Maple Syrup", "Golden Syrup"): for fermentable in orm.Grain.objects.filter(name__contains=name): fermentable.volume_to_weight_conversion = dec(12) fermentable.save() for name in ("Corn Sugar", "Dextrose", "Malto Dextrin", "Invert Sugar"): for dex in orm.Grain.objects.filter(name__startswith=name): dex.volume_to_weight_conversion = dec(6) dex.save() for name in ("Cane (Beet) Sugar", "Sucrose"): for sugar in orm.Grain.objects.filter(name__startswith=name): sugar.volume_to_weight_conversion = dec(7) sugar.save() for name in ("Turbinado", "Brown Sugar", "Demerara"): for sugar in orm.Grain.objects.filter(name__contains=name): sugar.volume_to_weight_conversion = dec(7) sugar.save()
def __init__(self, bootstrap): ConfigObject.__init__(self, bootstrap) self.coinserv = CoinserverRPC( "http://{0}:{1}@{2}:{3}/" .format(bootstrap['coinserv']['username'], bootstrap['coinserv']['password'], bootstrap['coinserv']['address'], bootstrap['coinserv']['port'], pool_kwargs=dict(maxsize=bootstrap.get('maxsize', 10)))) self.exchangeable = bool(self.exchangeable) self.minimum_payout = dec(self.minimum_payout) # If a pool payout addr is specified, make sure it matches the # configured address version. if self.pool_payout_addr is not None: try: ver = address_version(self.pool_payout_addr) except (KeyError, AttributeError): ver = None if ver not in self.address_version: raise ConfigurationException( "{} is not a valid {} address. Must be version {}, got version {}" .format(self.pool_payout_addr, self.key, self.address_version, ver)) # Check to make sure there is a configured pool address for # unexchangeable currencies if self.exchangeable is False and self.pool_payout_addr is None: raise ConfigurationException( "Unexchangeable currencies require a pool payout addr." "No valid address found for {}".format(self.key))
def test_decimal_repr(self): cell = odf_create_cell(dec('2.718281828'), text=u"2,72") expected = ('<table:table-cell office:value-type="float" ' 'office:value="2.718281828">' '<text:p>2,72</text:p>' '</table:table-cell>') self.assertEqual(cell.serialize(), expected)
def npl(phenny, input): """Shows the time from NPL's SNTP server.""" client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) client.sendto('\x1b' + 47 * '\0', ('ntp1.npl.co.uk', 123)) data, address = client.recvfrom(1024) if data: buf = struct.unpack('B' * 48, data) d = dec('0.0') for i in range(8): d += dec(buf[32 + i]) * dec(str(math.pow(2, (3 - i) * 8))) d -= dec(2208988800L) a, b = str(d).split('.') f = '%Y-%m-%d %H:%M:%S' result = datetime.datetime.fromtimestamp(d).strftime(f) + '.' + b[:6] phenny.say(result + ' - ntp1.npl.co.uk') else: phenny.say('No data received, sorry')
def test_set_cell_repeat(self): row = self.row_repeats.clone() row.set_cell_value(1, 3.14) self.assertEqual(row.get_cell_values(), [1, dec('3.14'), 1, 2, 3, 3, 3]) # Test repetitions are synchronized self.assertEqual(row.get_row_width(), 7)
def observation_length(pj, selected_observations: list) -> tuple: """ max length of selected observations total media length Args: selected_observations (list): list of selected observations Returns: float: maximum media length for all observations float: total media length for all observations """ selectedObsTotalMediaLength = dec("0.0") max_obs_length = 0 for obs_id in selected_observations: obs_length = observation_total_length(pj[OBSERVATIONS][obs_id]) if obs_length in [dec("0"), dec("-1")]: selectedObsTotalMediaLength = -1 break max_obs_length = max(max_obs_length, obs_length) selectedObsTotalMediaLength += obs_length # an observation media length is not available if selectedObsTotalMediaLength == -1: # propose to user to use max event time if dialog.MessageDialog( programName, (f"A media length is not available for the observation <b>{obs_id}</b>.<br>" "Use last event time as media length?"), [YES, NO]) == YES: maxTime = 0 # max length for all events all subjects max_length = 0 for obs_id in selected_observations: if pj[OBSERVATIONS][obs_id][EVENTS]: maxTime += max(pj[OBSERVATIONS][obs_id][EVENTS])[0] max_length = max(max_length, max(pj[OBSERVATIONS][obs_id][EVENTS])[0]) logging.debug(f"max time all events all subjects: {maxTime}") max_obs_length = max_length selectedObsTotalMediaLength = maxTime else: max_obs_length = -1 selectedObsTotalMediaLength = dec("-1") return max_obs_length, selectedObsTotalMediaLength
def get_value(element, value_type=None, try_get_text=True, get_type=False): """Only for "with office:value-type" elements, not for meta fields """ if value_type is None: value_type = element.get_attribute('office:value-type') #value_type = to_str(value_type) if value_type == 'boolean': value = element.get_attribute('office:boolean-value') if get_type: return (value, value_type) return value # value is already decoded by get_attribute for booleans elif value_type in {'float', 'percentage', 'currency'}: value = dec(element.get_attribute('office:value')) # Return 3 instead of 3.0 if possible if int(value) == value: if get_type: return (int(value), value_type) return int(value) if get_type: return (value, value_type) return value elif value_type == 'date': value = element.get_attribute('office:date-value') if 'T' in value: if get_type: return (DateTime.decode(value), value_type) return DateTime.decode(value) else: if get_type: return (Date.decode(value), value_type) return Date.decode(value) elif value_type == 'string': value = element.get_attribute('office:string-value') if value is not None: if get_type: return (str(value), value_type) return str(value) if try_get_text: value = [] for para in element.get_elements('text:p'): value.append(para.text_recursive) if value: if get_type: return ('\n'.join(value), value_type) return '\n'.join(value) if get_type: return (None, value_type) return None elif value_type == 'time': value = Duration.decode(element.get_attribute('office:time-value')) if get_type: return (value, value_type) return value elif value_type is None: if get_type: return (None, None) return None raise ValueError('unexpected value type "%s"' % value_type)
def calculate_total_heat_of_reaction(self): # Yes, it is as easy as this ... tihihihi. self.total_heat = dec('0.0') for i in range(len(self.heat_flow) - 1): self.total_heat += self.heat_flow[i] * self.timestep # Round to get a sensible value self.total_heat = round(self.total_heat, 3)
def sanity_check(cube): # Assert allocation percent totals 100 total = 0 count = 0 for a in cube.allocations.values(): try: total += a.percent except TypeError: # percent is None?? pass else: count += 1 if total == 0: # No allocations set yet return False elif abs(total - 1) > count * 0.0001: # Pass this along to the user or trigger new allocations? log.warning(f'{cube} Allocations total {total}') log.warning(f'{cube} Attempting normalization of percentages') try: for a in cube.allocations.values(): a.percent = dec(a.percent) / dec(total) db_session.add(a) db_session.commit() return True except Exception as e: log.debug(e) return False else: log.debug(f'{cube} Allocations total {total}') # Skip 0 balance cubes bal_tot = sum([bal.total for bal in cube.balances]) if not bal_tot: log.warning(f'{cube} Zero balance') return False # Create 0% allocation for missing ones (balance available) curs = set([b.currency for b in cube.balances]) for c in curs: if c.symbol not in cube.allocations: log.warning(f'{cube} Missing {c} allocation (setting to 0)') cube.allocations[c.symbol] = AssetAllocation(currency=c, percent=0) db_session.add(cube) db_session.commit() return True
def create_temperature_in_kelvin(self): # self.in_kelvin is either 1 or 0. Zero will be evaluated as False # here ... Cool! if not self.in_kelvin and hasattr(self, 'temperature'): for i in range(len(self.temperature)): self.temperature[i] = self.temperature[i] + dec('273.15') elif not hasattr(self, 'temperature'): print("The data does not contain temperature data!")
def clean(self, value): value = super(DecimalField, self).clean(value) if value is None or isinstance(value, dec): return value try: return value.to_decimal() except AttributeError: return dec(value)
def assertVecEqual(self, expected_coordinates, actual, round_val=None): if round_val: self.assertEqual(expected_coordinates, [round(x, round_val) for x in actual.coordinates]) else: self.assertEqual( [dec(x) for x in expected_coordinates], [x for x in actual.coordinates])
def get_value(element, value_type=None, try_get_text=True, get_type=False): """Only for "with office:value-type" elements """ if value_type is None: value_type = element.get_attribute('office:value-type') if value_type == 'boolean': value = element.get_attribute('office:boolean-value') if get_type: return (Boolean.decode(value), value_type) return Boolean.decode(value) elif value_type in ('float', 'percentage', 'currency'): value = dec(element.get_attribute('office:value')) # Return 3 instead of 3.0 if possible if int(value) == value: if get_type: return (int(value), value_type) return int(value) if get_type: return (value, value_type) return value elif value_type == 'date': value = element.get_attribute('office:date-value') if 'T' in value: if get_type: return (DateTime.decode(value), value_type) return DateTime.decode(value) else: if get_type: return (Date.decode(value), value_type) return Date.decode(value) elif value_type == 'string': value = element.get_attribute('office:string-value') if value is not None: if get_type: return (unicode(value), value_type) return unicode(value) if try_get_text: value = [] for para in element.get_elements('text:p'): value.append(para.get_text(recursive=True)) if value: if get_type: return (u"\n".join(value), value_type) return u"\n".join(value) if get_type: return (None, value_type) return None elif value_type == 'time': value = Duration.decode(element.get_attribute('office:time-value')) if get_type: return (value, value_type) return value elif value_type is None: if get_type: return (None, None) return None raise ValueError, 'unexpected value type "%s"' % value_type
def get_price(exchange, base, quote): url = f'{_exapi_url}/{exchange}/midprice' params = {'base': base, 'quote': quote} r = requests.get(url, params=params) if r.status_code == 200: price = r.json() return dec(price['price_str']) else: raise r.status_code
def validate_str_perc(perc, round=dec('0.01')): """ Tries to convert a var representing an 0-100 scale percentage into a mathematically useful Python Decimal. Default is rounding to 0.01% Then checks to ensure decimal is within valid bounds """ # Try to convert to decimal try: dec_perc = dec(perc).quantize(round) / 100 except TypeError: return False else: # Check bounds if dec_perc > dec('1') or dec_perc < dec('0'): return False else: return dec_perc
def get_value(element, value_type=None, try_get_text=True, get_type=False): """Only for "with office:value-type" elements, not for meta fields""" if value_type is None: value_type = element.get_attribute("office:value-type") # value_type = to_str(value_type) if value_type == "boolean": value = element.get_attribute("office:boolean-value") if get_type: return (value, value_type) return value # value is already decoded by get_attribute for booleans if value_type in {"float", "percentage", "currency"}: value = dec(element.get_attribute("office:value")) # Return 3 instead of 3.0 if possible if int(value) == value: if get_type: return (int(value), value_type) return int(value) if get_type: return (value, value_type) return value if value_type == "date": value = element.get_attribute("office:date-value") if "T" in value: if get_type: return (DateTime.decode(value), value_type) return DateTime.decode(value) if get_type: return (Date.decode(value), value_type) return Date.decode(value) if value_type == "string": value = element.get_attribute("office:string-value") if value is not None: if get_type: return (str(value), value_type) return str(value) if try_get_text: value = [] for para in element.get_elements("text:p"): value.append(para.text_recursive) if value: if get_type: return ("\n".join(value), value_type) return "\n".join(value) if get_type: return (None, value_type) return None if value_type == "time": value = Duration.decode(element.get_attribute("office:time-value")) if get_type: return (value, value_type) return value if value_type is None: if get_type: return (None, None) return None raise ValueError('unexpected value type "%s"' % value_type)
def __init__(self, *args, **kwargs): if not kwargs.get('null', False): kwargs.setdefault('default', dec('0')) self.max_value = kwargs.pop('max_value', None) self.min_value = kwargs.pop('min_value', None) super(DecimalField, self).__init__(*args, **kwargs) min_allowed, max_allowed = self.range self.validators.append(MinValueValidator(min_allowed)) self.validators.append(MaxValueValidator(max_allowed))
def import_value(self, value, serializer): value = self.prepare_to_import(value, serializer) if value is None: return value elif (self.force_string or self.data_type not in serializer.importation_data_types): return self.import_value_from_string(value, serializer) else: return dec(str(value))
def __mul__(self, right): left = self.value if left is None: # NC * right = NC return self.__class__('NC') if isinstance(right, Numeric): right = right.value if right is None: # left * NC = NC return self.__class__('NC') if left == '': left = 0 left = dec(str(left)) if right == '': right = 0 right = dec(str(right)) # <type> * <type> return self.__class__(left * right)
def __rsub__(self, left): right = self.value if right is None: # left - NC = NC return self.__class__('NC') if isinstance(left, Numeric): left = left.value if left is None: # NC - right = NC return self.__class__('NC') if left == '': left = 0 left = dec(str(left)) if right == '': right = 0 right = dec(str(right)) # <type> - <type> return self.__class__(left - right)
def read_products(path): file_txt = open(path, "r") file_txt_raw = ''.join(file_txt.readlines()).replace("\\\n", " ") file_lines = [ line.replace("\|", " - ") for line in file_txt_raw.split("\n") if line != "" ] for line in file_lines: values = line.split("|") product_id = values[0] sku = values[1] product_description = values[2] price_cost = dec(values[3]) price_sale = dec(values[4]) Product(product_id, sku, product_description, price_cost, price_sale)
def latice_exploration_core_task(funcs_chunck): import find_params_basic_alg exps = [ {'f_x': lambda x: n**x, 'dfdx': lambda x: n.ln() * n**x} for n in [ dec(i) for i,t in funcs_chunck if t == 'exps' ] ] roots = [ {'f_x': lambda x: x**q, 'dfdx': lambda x: q * x**(q-dec(1))} for q in [ dec(1)/dec(i) for i,t in funcs_chunck if t == 'roots' ] ] funcs = exps + roots results = [] b_a = lambda a: 0.9878*a**0.8285 for f_dict in funcs: gd = find_params_basic_alg.GradientDescentBasicAlgo(enforce_Z=True, **f_dict) for x in range(2,5): basic_y = round(b_a(x)) for y in range(max(basic_y-2, 1), basic_y+2): res = gd.find_params(x, y, show_progress=False) if res: results.append({'values': res, 'f_dict': f_dict}) return results
def npl(willie, trigger): """Shows the time from NPL's SNTP server.""" # for server in ('ntp1.npl.co.uk', 'ntp2.npl.co.uk'): client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) client.sendto("\x1b" + 47 * "\0", ("ntp1.npl.co.uk", 123)) data, address = client.recvfrom(1024) if data: buf = struct.unpack("B" * 48, data) d = dec("0.0") for i in range(8): d += dec(buf[32 + i]) * dec(str(math.pow(2, (3 - i) * 8))) d -= dec(2208988800L) a, b = str(d).split(".") f = "%Y-%m-%d %H:%M:%S" result = datetime.datetime.fromtimestamp(d).strftime(f) + "." + b[:6] willie.say(result + " - ntp1.npl.co.uk") else: willie.say("No data received, sorry")
def classifier(document, prob_negative, prob_positive, vocabulary): document = divide_and_conquer(document) for word in document: if word in vocabulary: if word not in stopwords: prob_positive *= prob_positive + dec( vocabulary[word]["posprob"]) prob_negative *= prob_negative + dec( vocabulary[word]["negprob"]) #else: #Laplace smoothing when word unknown #"prob_positive = dec(prob_positive * (1/(vocabulary["total_words"]["unique"] + vocabulary["pos:class"]["count"]))) #prob_negative = dec(prob_negative * (1/(vocabulary["total_words"]["unique"] + vocabulary["neg:class"]["count"]))) if prob_positive > prob_negative: return "positive" else: return "negative"
def vMargin(self): ''' ' !Calculate only after all trades added! ''' if len(self.trades) == 0: print '--> Trades list IS EMPTY' return if len(self.trades) == 1: ''' TODO: rewrite to method which estimates open positions every day by the end of the contest. ------------------- If there is only one trade then evaluate by the end of contest. ''' url = eod.STOCK_URL + '{0}.xml?from={1}&till={1}&lang=RU'.\ format(self.sname, '2015-12-15') xml = eod.getXml(url) if len(xml) > 0: try: price = eod.getStockPrice(xml) except: print '--> Stock {0} - NOT FOUND'.format(self.sname) price = self.trades[0]['price'] qty = self.trades[0]['qty'] format_ = ['2015-12-15 18:45:00.000', self.sname, qty, price] self.addTrade('{0};{1};{2};{3}'.format(*format_)) else: print '--> XML for getStockPrice() from moex_eod.py NOT FOUND' return #if number of trades more than 1 position = 0 for i in range(0, len(self.trades) - 1): dt = self.trades[i + 1]['date'] pr1 = self.trades[i]['price'] pr2 = self.trades[i + 1]['price'] qty = self.trades[i]['qty'] position += int(qty) vm = position*(dec(pr2) - dec(pr1)) self.vmargin += [{'date':dt, 'vmargin':vm}] return self.vmargin
def read_bills(path): file_txt = open(path, "r") for line in [ line.replace("\|", " - ") for line in file_txt.readlines() if line != "" ]: values = line.split("|") bill_id = values[0] bill_number = values[1] bill_date = values[2] customer_id = values[3] discount = (dec_hundred - dec(values[4])) / dec_hundred soon_payment = (dec_hundred - dec(values[5])) / dec_hundred shipping_amount = dec(values[6]) Bill(bill_id, bill_number, bill_date, customer_id, discount, soon_payment, shipping_amount)
def read_bill_items(path): file_txt = open(path, "r") for line in [ line.replace("\|", " - ") for line in file_txt.readlines() if line != "" ]: values = line.split("|") billitem_id = values[0] bill_id = values[1] product_id = values[2] units = dec(values[3]) price = dec(values[4]) discount_1 = (dec_hundred - dec(values[5])) / dec_hundred discount_2 = (dec_hundred - dec(values[6])) / dec_hundred BillItem(billitem_id, bill_id, product_id, units, price, discount_1, discount_2)
def normal_probability_plot(path, tables, conf): fname = path + '.png' treenums = tables['tree_number'] x = sorted([float(dec(num).log10()) for ast, num in treenums]) y = [100.0*((j - 0.5)/float(len(x))) for j in xrange(1, len(x)+1)] plt.clf() with warnings.catch_warnings(): warnings.simplefilter("ignore") stats.probplot(x, dist='norm', plot=plt) plt.savefig(fname, format='png')
def convertToOneDigit(l): while True: s = str(sum(l)) if len(s) == 1: break l = list(map(int, list(s))) return dec(s)
def __init__(self, bootstrap): bootstrap['_algo'] = bootstrap.pop('algo') ConfigObject.__init__(self, bootstrap) # Check all our valid versions and ensure we have configuration # information on them assert isinstance(self.fee_perc, basestring) assert isinstance(self.block_bonus, basestring) self.fee_perc = dec(self.fee_perc) self.hr_fee_perc = round(self.fee_perc * 100, 2)
def arthro_dic(self, arthro_num): """Επιστρέφει: {'20.00': 100, '54.00': 24, '50.00': -124}""" arthro = self.dart.get(arthro_num, None) dfic = {} for lno in arthro: egr = self.dtrd[lno] # Εάν υπάρχουν παραπάνω από μία γραμμές με τον ίδιο κωδικό # λογιστικής αθροίζονται σε μία dfic[egr.lmo] = dfic.get(egr.lmo, dec(0)) + egr.xre - egr.pis return dfic
def main(): C = readDecimal() L = readInt() ans = dec('0.0') for i in range(L): A = readDecimals() ans += A[0] * A[1] * C print('%.7f' % ans)
def find_smallest_conversion(all_data): smallest_conversion = dec('1.0') for data in all_data: # Interesting, isn't it? I'm searching for the maximum to determine # the minimal highest conversion ... tihihihi. minimum = max(data.conversion_steps) if minimum < smallest_conversion: smallest_conversion = minimum return smallest_conversion
def getMostLikelyPath(): odoSliced = odometry[1:] index = 0 scores = [] iniProb = 1/len(paths) for path in paths: score = dec(iniProb) for index in xrange( len(path) - 1 ): odo = odoSliced[index] state_p = path[index] state_n = path[index+1] score *= dec(norm.pdf(state_n[0], state_p[0], odo)) * dec(norm.pdf(state_n[1], state_p[1], odo)) # score_x = dec( str(norm.pdf(state_n[0], state_p[0], odo)) ) # score_y = dec( str(norm.pdf(state_n[1], state_p[1], odo)) ) # score *= score_x * score_y #print score scores.append(score) index = scores.index( max(scores) ) return paths[index]
def below_trade_min(cube, ex_pair, bal_tgt, val_diff_pct, amount, val): # Get currency ex = ex_pair.exchange # Check if order meets trade minimum try: params = { 'base': ex_pair.base_currency.symbol, 'quote': ex_pair.quote_currency.symbol } d = api_request(cube, 'GET', ex_pair.exchange.name, '/details', params) except AttributeError: # Exchange is probably external... not performing minimum checks log.warning(f'{cube} No details for {ex_pair}') d = None except Exception as e: log.error(e) d = None else: if d and (amount < d['min_amt'] or val < d['min_val']): # Below trade minimum # Consider the target reached log.debug(f'{cube} {ex} {ex_pair.base_currency} reached target') b = Balance.query.filter_by( cube=cube, exchange=ex, currency=ex_pair.base_currency).first() b.target = None db_session.add(b) db_session.commit() return True if bal_tgt != 0: if abs(dec(val_diff_pct)) < dec(cube.threshold / 100): # Below threshold, target reached log.info('%s %s %s below threshold' % (cube, ex, ex_pair.base_currency)) b = Balance.query.filter_by( cube=cube, exchange=ex, currency=ex_pair.base_currency).first() b.target = None db_session.add(b) db_session.commit() return True return False
def __init__(self, bootstrap): bootstrap['_algo'] = bootstrap.pop('algo') bootstrap['_currencies'] = bootstrap.pop('currencies') bootstrap['key'] = int(bootstrap['key']) ConfigObject.__init__(self, bootstrap) self.id = self.key assert isinstance(self.fee_perc, basestring) assert isinstance(self.block_bonus, basestring) self.fee_perc = dec(self.fee_perc) self.hr_fee_perc = round(self.fee_perc * 100, 2)
def test_problems(self): l1 = Line(Vector([4.046, 2.836]), 1.21) l2 = Line(Vector([10.115, 7.09]), 3.025) self.assertTrue(l1.__eq__(l2)) self.assertEquals(None, l1.intersection(l2)) l1 = Line(Vector([7.204, 3.182]), 8.68) l2 = Line(Vector([8.172, 4.114]), 9.883) self.assertEquals((dec('1.17277663546464155833736023125'), dec('0.0726955116633319428771277112348')), l1.intersection(l2).coordinates) self.assertFalse(l1.__eq__(l2)) l1 = Line(Vector([1.182, 5.562]), 6.744) l2 = Line(Vector([1.773, 8.343]), 9.525) self.assertEquals(None, l1.intersection(l2)) self.assertFalse(l1.__eq__(l2))
def Gratio(): clear() print("Calculating...") tstart = time.perf_counter() Golden = dec(dec(dec(1) + dec(dec(5)**dec(0.5))) / dec(2)) clear() print("Converting") finalgolden = dec(int(Golden * dec(10**maxpr)) / dec(10**maxpr)) tend = time.perf_counter() clear() print("Done!\n") print(finalgolden) if maxpr == 0: lensub = 0 else: lensub = 1 stlength = len(str(finalgolden)) - lensub print("\nLength", stlength) print("\nAccurate Precision", maxpr) print("Time:", '%.4f' % (tend - tstart), "Seconds")
def kartella(self, lmos, apo=None, eos=None): Kar = namedtuple('Kar', 'tno dat par per xre pis sum') val = [] rsum = dec(0) for lin in self.dtrd.values(): if lin.lmo.startswith(lmos): rsum += lin.xre - lin.pis lva = Kar(lin.tno, self.dtrh[lin.tno].dat, self.dtrh[lin.tno].par, self.dper[lin.tno].per, lin.xre, lin.pis, rsum) val.append(lva) return val
def convertparams(self): """ Scales nonbonded terms by 2^(-5/6) """ factor = dec(1.78179743628)# = 2^(5/6) = (2.0 / 2.0**(1./6.)) self.diafcopa1 = (-1 * (dec(self.param1).as_tuple().exponent)) - 16 # chosen such that we get the same nr of sigfigs after ff_charm_to_viparr self.diafcopa2 = -1 * (dec(self.param2).as_tuple().exponent) self.a = dec(self.param1) / factor self.b = - dec(self.param2) if self.extraparam1: self.c = dec(self.extraparam1) / factor self.d = - dec(self.extraparam2)
def btc_value(self): # """ Caches and returns estimated currency value in BTC """ # if self.key == "BTC": # return dec('1') # # # XXX: Needs better number here! # err, dat, _ = exchanges.optimal_sell(self.key, dec('1000'), exchanges._get_current_object().exchanges) # try: # current_app.logger.info("Got new average price of {} for {}" # .format(dat['avg_price'], self)) # return dat['avg_price'] # except (KeyError, TypeError): # current_app.logger.warning("Unable to grab price for currency {}, got {} from autoex!" # .format(self.key, dict(err=err, dat=dat))) return dec('0')
def __init__(self, bootstrap): bootstrap['_algo'] = bootstrap.pop('algo', None) if bootstrap['_algo'] is None: raise ConfigurationException( "A currency in config.toml is missing an entry in " "defaults.toml! The following config may help identify it: {}" .format(bootstrap)) ConfigObject.__init__(self, bootstrap) if self.coinserv: cfg = self.coinserv self.coinserv = CoinserverRPC( "http://{0}:{1}@{2}:{3}/" .format(cfg['username'], cfg['password'], cfg['address'], cfg['port'], pool_kwargs=dict(maxsize=bootstrap.get('maxsize', 10)))) self.coinserv.config = cfg elif self.sellable or self.mineable or self.buyable: raise ConfigurationException( "Coinserver must be configured for {}!".format(self.key)) self.sellable = bool(self.sellable) self.buyable = bool(self.buyable) self.merged = bool(self.merged) self.minimum_payout = dec(self.minimum_payout) # If a pool payout addr is specified, make sure it matches the # configured address version. if self.pool_payout_addr is not None: try: ver = address_version(self.pool_payout_addr) except (KeyError, AttributeError): ver = None if ver not in self.address_version: raise ConfigurationException( "{} is not a valid {} address. Must be version {}, got version {}" .format(self.pool_payout_addr, self.key, self.address_version, ver)) # Check to make sure there is a configured pool address for # unsellable currencies if self.sellable is False and self.pool_payout_addr is None and self.mineable: raise ConfigurationException( "Unsellable currencies require a pool payout addr." "No valid address found for {}".format(self.key))
def manage_compta(request, tmpl, user_id=None): operations = user = None if user_id: try: user = User.objects.get(id=user_id) except: user = None if user: operations = Operation.objects.filter(user=user).order_by('order', 'id') solde = dec(0) for i,op in enumerate(operations): if op.date_payment: solde -= op.amount else: solde += op.amount operations[i].set_solde(solde) return tmpl, {'user_obj': user, 'operations': operations}
def order_paid(self, order, fee, user, data): curdate = date.now() method = self.get_paiement_method() order.save_paid(method, data) if fee > 0: account = self.get_supplier_account() if account: op = Operation( debit=account, credit=method.account, label=_("Commission (fee) order #%d") % (order.id), comment='', amount=dec(fee), payment=method, date=curdate, date_payment=curdate, order=order, user=user) op.save()
def get_value(element, value_type=None, try_get_text=True): """Only for "with office:value-type" elements """ if value_type is None: value_type = element.get_attribute('office:value-type') if value_type == 'boolean': value = element.get_attribute('office:boolean-value') return Boolean.decode(value) elif value_type in ('float', 'percentage', 'currency'): value = dec(element.get_attribute('office:value')) # Return 3 instead of 3.0 if possible if int(value) == value: return int(value) return value elif value_type == 'date': value = element.get_attribute('office:date-value') if 'T' in value: return DateTime.decode(value) else: return Date.decode(value) elif value_type == 'string': value = element.get_attribute('office:string-value') if value is not None: return unicode(value) # XXX: get_text or get_formatted_text ??? if try_get_text: value = element.get_text(recursive=True) if value != '': return value return None elif value_type == 'time': value = element.get_attribute('office:time-value') return Duration.decode(value) elif value_type is None: return None raise ValueError, 'unexpected value type "%s"' % value_type
def makeParts(value, p_size, spending_name, spending_time): """make p_size parts with the value. if centimes left, we allocate these lost ones to a random user. sometimes it's positive numbers, sometimes not! my priority was to NOT have lost centimes. P.S.: sorry for this madness with floating and decimal numbers, there wasn't any 'easy' way! """ getcontext().prec = 6 value = dec(str(value)) # I'll probably go to hell for this... # attribution aux parts de la valeur entière divisible par p_size parts = [int(value/p_size)] * p_size # on transforme le reste en centimes que l'on distribue left_centimes = int(100 * (value - sum(parts))) # attribution aux parts des centimes restants for idx, part in enumerate(parts): parts[idx] += (left_centimes/p_size) / 100. # on attribue les centimes restants à un user aléatoire the_last_centime = (left_centimes % p_size) / 100. if the_last_centime != 0: the_one = randint(0, len(parts)-1) parts[the_one] += the_last_centime # any error is logged. because money is money. no jokes! if float(value) != float(sum(parts)): LOGGER.p_log('error in adding a spending', level='warning') LOGGER.p_log('spending_time: ' + str(spending_time), blank=True) LOGGER.p_log('value: ' + str(value), blank=True) LOGGER.p_log('sum: ' + str(sum(parts)), blank=True) LOGGER.p_log('parts: ' + str(parts), blank=True) return parts