def dijkstra(G): """ Dijkstra algorithm for finding shortest path from start position to end. """ srcIdx = G.vex2idx[G.startpos] dstIdx = G.vex2idx[G.endpos] # build dijkstra nodes = list(G.neighbors.keys()) dist = {node: float('inf') for node in nodes} prev = {node: None for node in nodes} dist[srcIdx] = 0 while nodes: curNode = min(nodes, key=lambda node: dist[node]) nodes.remove(curNode) if dist[curNode] == float('inf'): break for neighbor, cost in G.neighbors[curNode]: newCost = dist[curNode] + cost if newCost < dist[neighbor]: dist[neighbor] = newCost prev[neighbor] = curNode # retrieve path path = deque() curNode = dstIdx while prev[curNode] is not None: path.appendleft(G.vertices[curNode]) curNode = prev[curNode] path.appendleft(G.vertices[curNode]) return list(path)
def keans_cluster(self, lis): self.score = json.loads(red.get('scores').decode('utf-8')) score = [] mini = 99999999.0 maxi = 0.0 for ele in lis: k = [] k.append((self.score[str(ele)])) if float(self.score[str(ele)]) < (mini): mini = float(self.score[str(ele)]) elif float(self.score[str(ele)]) > maxi: maxi = float(self.score[str(ele)]) score.append(k) kmeans = KMeans(n_clusters=4, random_state=0).fit(score) centers = (kmeans.cluster_centers_) a = [] for key in centers: a.extend(key) a.sort() range = [] range.append(mini) range.extend(a) range.append(maxi) return range pass
def init(): print("Please enter in coefficients from Standard Ax^2 + Bx + C ") ConstA = input("Value for Constant A: ") ConstB = input("Value for Constant B: ") ConstC = input("Value for Constant C: ") print("You have entered the following values: " + ConstA, ConstB, ConstC) calc(float(ConstA), float(ConstB), float(ConstC))
def coef(x, y): n = len(x) a = [] for i in range(n): a.append(y[i]) for j in range(1, n): for i in range(n - 1, j - 1, -1): a[i] = float(a[i] - a[i - 1]) / float(x[i] - x[i - j]) return np.array(a)
def ajax_get_mechanics_nearest(request): try: lat = float(request.POST.get('id_lat').strip(' "')) lng = float(request.POST.get('id_lng').strip(' "')) skill = request.POST.get('id_skill') mechanics_nearest = get_mechanics_nearest(lat, lng, skill) result = [{"pk": x[0], "name": x[1], "miles": x[2], "bio": x[3], "icon": x[4], "skills": x[5], "rating": x[6], "ratingcount": x[7]} for x in mechanics_nearest] return HttpResponse(simplejson.dumps(result), content_type="application/json") except Exception: print(traceback.format_exc()) return HttpResponse("Internal Error, try again later", status=500)
def clean_value(value): """ To ensure the computed dataframe is consistently typed all values are co-erced to float or we die trying... """ if isinstance(value, (int, float)): return float(value) if value is None: return None # else str... value = value.rstrip('%') value = value.replace(',', '') return float(value)
def ajax_subscribe_availability(request): try: email = request.POST.get('id_email', "") lat = float(request.POST.get('id_lat').strip(' "')) lng = float(request.POST.get('id_lng').strip(' "')) check = check_email(email) if check is not None: return check subscriber = NotifyAvailability(email=email, latitude=lat, longitude=lng) subscriber.save() return HttpResponse("") except Exception: print(traceback.format_exc()) return HttpResponse("Internal Error, try again later", status=500)
def accept_signal(trade_signal, parameter): iv = perc_to_float(trade_signal.iv) if iv < parameter.volmin: return False elif iv > parameter.volmax: return False elif float(trade_signal.uvol) < parameter.minuvol: return False elif float(trade_signal.uoi) < parameter.minuoi: return False elif float(trade_signal.origin_price) < parameter.pricemin: return False else: return True
def ajax_get_mechanics(request): try: sw_lat = float(request.POST.get('id_sw_lat').strip(' "')) sw_lng = float(request.POST.get('id_sw_lng').strip(' "')) ne_lat = float(request.POST.get('id_ne_lat').strip(' "')) ne_lng = float(request.POST.get('id_ne_lng').strip(' "')) skill = request.POST.get('id_skill') mechanics_list = get_mechanics_list(sw_lat, sw_lng, ne_lat, ne_lng, skill) result = [{"pk": x[0], "latlng": (x[1], x[2]), "radius": x[3], "icon": get_icon_url_from_user(get_user_model().objects.get(pk=x[4]))} for x in mechanics_list] return HttpResponse(simplejson.dumps(result), content_type="application/json") except Exception: print(traceback.format_exc()) return HttpResponse("Internal Error, try again later", status=500)
def atom_err(text, default=None, allow_inf_nan=True): """ Parse an atomic literal (int, float, bool, None, name) from the given text. Return a (value, error) pair per Go style. If parsing is successful, then (<value>, None) is returned, otherwise (<default>, ParseError) is returned. This is needed for distinguishable parsing of None. This recognizes and parses all the atoms that are distinguishable by their type alone. """ # Try parsing the literal in order of (assumed) frequency of types # Integer if integer_pattern.fullmatch(text) is not None: return builtins.int(text), None # Float elif (float_pattern.fullmatch(text) is not None or (allow_inf_nan and inf_nan_pattern.fullmatch(text) is not None)): return builtins.float(text), None # Boolean elif bool_true_pattern.fullmatch(text) is not None: return True, None elif bool_false_pattern.fullmatch(text) is not None: return False, None # None / Null elif none_pattern.fullmatch(text) is not None: return None, None # Name / Keyword / Identifier. This must come after the other atoms # whose representations are words. elif name_pattern.fullmatch(text) is not None: return text, None # Whitespace, strings, or non-atoms else: return default, ParseError('Cannot parse an atom from', text)
def brevity_penalty(c, r): if c > r: bp = 1 else: bp = math.exp(1-(float(r)/c)) return bp
def runCommandWithTimeout(commandString, timeout_in_second): try: timeoutInSecond = float(timeout_in_second) start_time = time.time() #p = subprocess.Popen(commandString,stderr=subprocess.PIPE, shell=True, preexec_fn=os.setsid) p = subprocess.Popen(commandString, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, preexec_fn=os.setsid) # http://stackoverflow.com/questions/4789837/how-to-terminate-a-python-subprocess-launched-with-shell-true p.wait(timeoutInSecond) running_time = (time.time() - start_time) #err = p.communicate() print("Command has finished, running p.communicate() ...") out, err = p.communicate() #print(out.decode('utf-8')) #print("running time: %.2f ms" % running_time) if p.returncode==0: #print("return code: %d " % p.returncode) print(out.decode('utf-8')) print(err.decode('utf-8')) return running_time else: return "error" except subprocess.TimeoutExpired as e: #print("Timeout after %s s" % timeoutInSecond) print(e) os.killpg(p.pid, signal.SIGTERM) return "timeout"
def runCommandWithTimeout(commandString, timeout_in_second): try: timeoutInSecond = float(timeout_in_second) print(commandString) start_time = time.time() #p = subprocess.Popen(commandString,stderr=subprocess.PIPE, shell=True, preexec_fn=os.setsid) p = subprocess.Popen(commandString, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, preexec_fn=os.setsid) # http://stackoverflow.com/questions/4789837/how-to-terminate-a-python-subprocess-launched-with-shell-true p.wait(timeoutInSecond) running_time = (time.time() - start_time) #err = p.communicate() print("Command has finished") out, err = p.communicate() #print(out.decode('utf-8')) print(out.decode('utf-8')) print(err.decode('utf-8')) print("Result has retrieved") print("Runtime of this command: %.2f ms" % running_time) if p.returncode==0: #print("return code: %d " % p.returncode) return running_time else: return "error" except subprocess.TimeoutExpired as e: #print("Timeout after %s s" % timeoutInSecond) print(e) os.killpg(p.pid, signal.SIGTERM) return "timeout"
def strictfloat(value): ''' Converts any type that is a subclass of :class:`numbers.Real` (e.g. :class:`float` and ``numpy.float64``) to :class:`float`, and fails otherwise. Notable difference with the behavior of :class:`float`: * :func:`strictfloat` does not convert a :class:`str` to an :class:`float`. Examples -------- >>> strictfloat(1), type(strictfloat(1)) (1.0, <class 'float'>) >>> strictfloat(numpy.float64(1.2)), type(strictfloat(numpy.float64(1.2))) (1.2, <class 'float'>) >>> strictfloat(1.2+3.4j) Traceback (most recent call last): ... ValueError: not a real number: (1.2+3.4j) >>> strictfloat('1.2') Traceback (most recent call last): ... ValueError: not a real number: '1.2' ''' if not isinstance(value, numbers.Real): raise ValueError('not a real number: {!r}'.format(value)) return builtins.float(value)
def set(self, value): try: if value is not None: self.value = builtins.float(value) else: self.value = None except ValueError as e: raise BadParameterType("float", value)
def clean(self): latitude = self.cleaned_data.get('latitude') longitude = self.cleaned_data.get('longitude') radius = self.cleaned_data.get('radius') if not latitude or not longitude or not radius: raise forms.ValidationError("Please select an area you wish to work at") if float(radius) > 100000: raise forms.ValidationError("Please reduce your selected radius")
def convert(*args): try: value = float(num_entry.get()) C = round((value - 32) * 5 / 9, 1) res.set(C) except ValueError: pass
def float(arg, default=None): var = _env_var(arg) if var is not None: try: return builtins.float(var) except ValueError: raise TypeError else: return default
def float_err(text, allow_inf_nan=True): """ Parse a float from the given text. Return a (value, error) pair per Go style. """ if is_float(text, allow_inf_nan): return builtins.float(text), None else: return None, ParseError('Cannot parse a float from', text)
def float( env_var: builtins.str, default: Optional[builtins.float] = None, ) -> Optional[builtins.float]: try: return builtins.float(env_var) except ValueError: raise TypeError( f"Invalid float value specified: {env_var} " "Parsenvy accepts only valid floats and integers as float values")
def process_keys(key, value): if key == 'V' or key == 'VPV': # mV -> V return float(value) / 1000 elif key == 'IL' or key == 'I': return int(value) # mA elif key == 'PPV' or key == 'H21': # W return int(value) elif key == 'H20': # 0.01Kw -> Kw return float(value) / 100 elif key == 'CS': return int(value) # vedirect.Vedirect.VICTRON_CS[value] elif key == 'MPPT': return int(value) # vedirect.Vedirect.VICTRON_MTTP[value] elif key == 'ERR': return int(value) # vedirect.Vedirect.VICTRON_ERROR[value] elif key == 'LOAD': return 1 if value == 'ON' else 0 # ON / OFF else: raise ValueError('Unable to parse key')
def get_network_fee(): # with web3.py he gives 520 gwei which is too much """ Give an estimate of network fee for a simple ether transaction. from http://gasprice.dopedapp.com/ :return: network cost """ br = StatefulBrowser(user_agent="Firefox") page = br.open("http://gasprice.dopedapp.com/") response = page.json() gwei_price = float(response["safe_price_in_gwei"]) return gwei_price * GWEI_TO_ETHER * NB_GAS_FOR_TRANSACTION
def band_creation(self): master = {} cat = json.loads(red.get('cat').decode('utf-8')) limits = json.loads(red.get('limits').decode('utf-8')) score = json.loads(red.get('scores').decode('utf-8')) for ele in cat: master[ele] = {} for ele1 in limits: if ele == ele1: for num in range(len(limits[ele1]) - 1): master[ele][num] = [] for ids in cat[ele]: if float(score[str( ids)]) > limits[ele1][num] and float( score[str(ids)]) < limits[ele1][num + 1]: master[ele][num].append(ids) red.set('master', json.dumps(master)) pass
def assert_bounded(val, lower=None, upper=None, msg=None): '''Assert that ``lower <= val <= upper``. :arg val: The value to check. :arg lower: The lower bound. If ``None``, it defaults to ``-inf``. :arg upper: The upper bound. If ``None``, it defaults to ``inf``. :returns: ``True`` on success. :raises reframe.core.exceptions.SanityError: if assertion fails. ''' if lower is None: lower = builtins.float('-inf') if upper is None: upper = builtins.float('inf') if val >= lower and val <= upper: return True error_msg = msg or 'value {0} not within bounds {1}..{2}' raise SanityError(_format(error_msg, val, lower, upper))
def rr(self): pre_processes = [] # running_time等于进程到达时间时会将其入队 over_processes = [] # 完成队列 flag = 0 # 记录完成的进程数 running_time = self.running_time time_block = self.time_block pre_processes.append(self.processes[0]) # 先将第一个进程入队 while (flag != len(self.processes)): # 是否进程入队的优先级高于进程从队首切换到队尾的优先级? # 执行当前队首进程,如果一个时间片内不能执行完,则放入队列尾部 # 判断时间片是否大于剩余服务时间 if time_block >= pre_processes[0].left_serve_time: for i in range(pre_processes[0].left_serve_time): pre_processes[0].left_serve_time -= 1 running_time += 1 for i in range(len(self.processes)): if running_time == self.processes[i].arrive_time: pre_processes.append(self.processes[i]) # 就绪队列进入队尾 if pre_processes[0].left_serve_time == 0: # 计算完成时间 pre_processes[0].finish_time = running_time # 计算周转时间 pre_processes[0].cycling_time = pre_processes[0].finish_time \ - pre_processes[0].arrive_time # 计算带权周转时间 pre_processes[0].w_cycling_time = float(pre_processes[0].cycling_time) / \ pre_processes[0].serve_time # 打印 print('%s 进程已完成的进程,详细信息如下:' % pre_processes[0].name) print('进程名称:%s ,完成时间: %d ,周转时间:%d ,带权周转时间: %.2f' % (pre_processes[0].name, pre_processes[0].finish_time, pre_processes[0].cycling_time, pre_processes[0].w_cycling_time)) flag += 1 over_processes.append(pre_processes.pop(0)) # 进程结束从就绪队列出队进完成队列 continue # 直接结束此次循环,下面内容不执行 else: # 剩余服务时间大于一个时间片 for i in range(time_block): pre_processes[0].left_serve_time -= 1 running_time += 1 for i in range(len(self.processes)): # 判断此时有没有就绪队列加入队尾 if running_time == self.processes[i].arrive_time: pre_processes.append(self.processes[i]) # 一个时间片结束进程从队头切换至队尾 pre_processes.append(pre_processes.pop(0))
def __init__(self,ai_settings,screen): super(Alien, self).__init__() self.screen=screen self.ai_setting=ai_settings self.image = pygame.image.load('images/alien.bmp') self.rect = self.image.get_rect() self.rect.x=self.rect.width self.rect.y=self.rect.height self.x = float(self.rect.x)
def __read_temperature(self): ut = c_long(27898) if not self.__test: self.__bus.start_comunication(self.DEVICE_ADDRESS) self.__bus.write_byte(0xF4, 0x2E) sleep(0.45) ut = c_long(self.__bus.read_word(0xF6)).value self.__bus.stop_comunication() x1 = (ut - self.__AC6) * self.__AC5 / pow(2, 15) x2 = self.__MC * pow(2, 11) / (x1 + self.__MD) self.__B5 = x1 + x2 t = (self.__B5 + 8) / pow(2, 4) return float(t) / 10
def get_options(cls): browser = cls._create_browser() browser.open(cls.OPTIONS_URL) soup = browser.get_current_page() p = soup.select("p.hero-description") string = p[1].get_text() # Calculate the price in USD eur = float(string[string.index("€") + 1:string.index("/")]) price = round(CurrencyRates().convert("EUR", "USD", eur), 2) name, _ = cls.get_metadata() option = VpnOption(name, "OpenVPN", price, sys.maxsize, sys.maxsize) return [option]
def determine_tachy(patient_id): """ Return if patient is tachy from most recent measurement and time stamp, send email if tachy Args: patient_id (str): Returns: ans_str (str): if tachy or not time (str): time stamp Raises: ValidationError: User doesn't exist """ connect("mongodb://*****:*****@ds157818.mlab.com:57818/hr") a = int(patient_id) try: for user in User.objects.raw({"_id": a}): try: validate_get_heart_rate(user.heart_rate) except ValidationError: pass time = user.time_stamp[-1] answer = determine_if_tachy(float(user.user_age), int(user.heart_rate[-1])) # send email if tahycardic if answer: logging.warning("User is tachycardic") send_email() ans_str = 'Tachycardic' else: ans_str = 'Not tachycardic' logging.info("User is not tachycardic") mes = jsonify(ans_str, time) except UnboundLocalError: mes = "User does not exist" mes = jsonify(mes) logging.warning("Tried to test if " "tachycardia for user that does not exist") return mes
def scanD(D, Ck, minSupport): ssCnt = {} for tid in D: for can in Ck: if can.issubset(tid): ssCnt[can] = ssCnt.get(can, 0) + 1 numItems = float(len(D)) retList = [] supportData = {} for key in ssCnt: support = ssCnt[key] / numItems if support >= minSupport: retList.insert(0, key) supportData[key] = support return retList, supportData
def read_mat(): f = open('mat.out','r') result = [[0]*4224 for i in range(4224)] i=0 for line in f: if i>=2: #print(i) line = line[:-1] lineSplit = line.split(":") indiceInfo = lineSplit[1].strip().split(") (") for index,ele in enumerate(indiceInfo): if index==0: ele = ele[1:] if index == len(indiceInfo)-1: ele = ele[:-1] someInfo = ele.split(',') infoIndex = int(someInfo[0].strip()) value = float(someInfo[1].strip()) result[i-2][infoIndex] = float(str(value)) i+=1 if (4226 == i): break return bsr_matrix(result)
def float(name, default=None, allow_none=False): """Get a string environment value or the default. Args: name: The environment variable name default: The default value to use if no environment variable is found allow_none: If the return value can be `None` (i.e. optional) """ value = read(name, default, allow_none) if isinstance(value, builtins.str): value = value.strip() if value is None and allow_none: return None else: return builtins.float(value)
def plot_confusion_matrix(cm, target_names, title='Confusion matrix', cmap=None, normalize=False): accuracy = np.trace(cm) / float(np.sum(cm)) misclass = 1 - accuracy if cmap is None: cmap = plt.get_cmap('Blues') plt.figure(figsize=(8, 6)) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() if target_names is not None: tick_marks = np.arange(len(target_names)) plt.xticks(tick_marks, target_names, rotation=45) plt.yticks(tick_marks, target_names) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] thresh = cm.max() / 1.5 if normalize else cm.max() / 2 for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): if normalize: plt.text(j, i, "{:0.4f}".format(cm[i, j]), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") else: plt.text(j, i, "{:,}".format(cm[i, j]), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass)) plt.show()
def div(a, b): return float(a) / float(b)
def __init__(self, dtype_or_func=None, default=None, missing_values=None, locked=False): # Convert unicode (for Py3) if isinstance(missing_values, unicode): missing_values = asbytes(missing_values) elif isinstance(missing_values, (list, tuple)): missing_values = asbytes_nested(missing_values) # Defines a lock for upgrade self._locked = bool(locked) # No input dtype: minimal initialization if dtype_or_func is None: self.func = str2bool self._status = 0 self.default = default or False dtype = np.dtype('bool') else: # Is the input a np.dtype ? try: self.func = None dtype = np.dtype(dtype_or_func) except TypeError: # dtype_or_func must be a function, then if not hasattr(dtype_or_func, '__call__'): errmsg = "The input argument `dtype` is neither a function"\ " or a dtype (got '%s' instead)" raise TypeError(errmsg % type(dtype_or_func)) # Set the function self.func = dtype_or_func # If we don't have a default, try to guess it or set it to None if default is None: try: default = self.func(asbytes('0')) except ValueError: default = None dtype = self._getdtype(default) # Set the status according to the dtype _status = -1 for (i, (deftype, func, default_def)) in enumerate(self._mapper): if np.issubdtype(dtype.type, deftype): _status = i if default is None: self.default = default_def else: self.default = default break if _status == -1: # We never found a match in the _mapper... _status = 0 self.default = default self._status = _status # If the input was a dtype, set the function to the last we saw if self.func is None: self.func = func # If the status is 1 (int), change the function to # something more robust. if self.func == self._mapper[1][1]: if issubclass(dtype.type, np.uint64): self.func = np.uint64 elif issubclass(dtype.type, np.int64): self.func = np.int64 else: self.func = lambda x : int(float(x)) # Store the list of strings corresponding to missing values. if missing_values is None: self.missing_values = set([asbytes('')]) else: if isinstance(missing_values, bytes): missing_values = missing_values.split(asbytes(",")) self.missing_values = set(list(missing_values) + [asbytes('')]) # self._callingfunction = self._strict_call self.type = self._dtypeortype(dtype) self._checked = False self._initial_default = default
def float(text, default=None, allow_inf_nan=True): """Return a float parsed from the given text, else `default`.""" return (builtins.float(text) if is_float(text, allow_inf_nan) else default)