def __getpid(self, ttyonly=False): max_retry = 1000 i = 0 while True: if (i > max_retry): raise Exp(errno.EIO, 'getpid fail') if (self.running()): while (1): a = get_value(self.home + "/status/status.pid") if (a != ''): self.pid = int(a) break else: time.sleep(0.1) while (1): a = get_value(self.home + "/status/parent.pid") if (a != ''): self.ppid = int(a) break else: time.sleep(0.1) break else: time.sleep(0.1) i = i + 1
def __init__(self): self.image_name = get_value("REDIS_IMAGE") docker_hosts = get_value("DOCKER_HOSTS") sentinel_hosts = get_value("SENTINEL_HOSTS") self.sentinel_hosts = json.loads(sentinel_hosts) self.docker_hosts = json.loads(docker_hosts) self.port_range_start = 49153
def parse_response(data): json = {} json['vin'] = get_value(data, 'vin') json['color'] = get_value(data, 'color') json['doorCount'] = 4 if get_value(data, 'fourDoorSedan') else 2 json['driveTrain'] = get_value(data, 'driveTrain') return json
def __init__(self): url = get_value("ZABBIX_URL") user = get_value("ZABBIX_USER") password = get_value("ZABBIX_PASSWORD") self.host_id = get_value("ZABBIX_HOST") self.interface_id = get_value("ZABBIX_INTERFACE") from pyzabbix import ZabbixAPI self.zapi = ZabbixAPI(url) self.zapi.login(user, password) self.items = self.mongo()['redisapi']['zabbix']
def __init__(self): url = get_value("ZABBIX_URL") user = get_value("ZABBIX_USER") password = get_value("ZABBIX_PASSWORD") self.host_id = get_value("ZABBIX_HOST") self.host_name = os.environ.get("ZABBIX_HOST_NAME", "Zabbix Server") self.interface_id = get_value("ZABBIX_INTERFACE") from pyzabbix import ZabbixAPI self.zapi = ZabbixAPI(url) self.zapi.login(user, password) self.items = self.mongo()['zabbix']
def __init__(self): url = get_value("ZABBIX_URL") user = get_value("ZABBIX_USER") password = get_value("ZABBIX_PASSWORD") self.host_id = get_value("ZABBIX_HOST") self.host_name = os.environ.get("ZABBIX_HOST_NAME", "Zabbix Server") self.interface_id = get_value("ZABBIX_INTERFACE") from pyzabbix import ZabbixAPI self.zapi = ZabbixAPI(url) self.zapi.login(user, password) self.items = self.mongo()["zabbix"]
def __init__(self): try: self.conn = mysql.connector.connect( user=get_value('db_user'), password=get_value('db_password'), host=get_value('db_host'), database=get_value('db_name')) self.cursor = self.conn.cursor() except mysql.connector.errors.ProgrammingError: print('Что-то пошло не так при соединении с базой') sys.exit()
def __init_register_port(self, path, hostname): prefix = "/sdfs/redis/%s" % (hostname) if (os.path.exists(path + "/port")): self.port_idx = int(get_value(path + "/port")) self.port = str(self.config.redis_baseport + self.port_idx) return True idx = None for i in range(NODE_PORT): key = prefix + "/port/" + str(i) try: #dmsg("etcd write " + key) self.etcd.write(key, "", prevExist=False) idx = i break except etcd.EtcdAlreadyExist: continue if (idx == None): derror("no port space in " + prefix) return False else: dmsg("register port " + str(idx)) set_value(path + "/port", str(idx)) self.port_idx = idx self.port = str(self.config.redis_baseport + self.port_idx) return True
def test_continue_in_finally_with_exception(tracer, test_server): """Tests POP_FINALLY when tos is an exception.""" tracer.start() # If the finally clause executes a return, break or continue statement, the saved # exception is discarded. for x in range(2): try: raise IndexError finally: continue # BREAK_LOOP (3.7) POP_FINALLY (3.8) tracer.stop() assert tracer.events == [ Binding(target=Symbol("x"), value="0", lineno=58), JumpBackToLoopStart(lineno=62, jump_target=16), Binding(target=Symbol("x"), value="1", lineno=58), JumpBackToLoopStart(lineno=62, jump_target=16), ] assert tracer.loops == [ Loop( start_offset=16, end_offset=get_value({"py38": 36, "default": 40}), start_lineno=58, ) ] test_server.assert_frame_sent("test_continue_in_finally_with_exception")
def test_continue_in_finally(tracer, test_server): tracer.start() for x in range(2): try: pass finally: continue # 3.8: POP_FINALLY, >= 3.9: POP_EXCEPT, RERAISE tracer.stop() assert tracer.events == [ Binding(target=Symbol("x"), value="0", lineno=22), JumpBackToLoopStart(lineno=26, jump_target=16), Binding(target=Symbol("x"), value="1", lineno=22), JumpBackToLoopStart(lineno=26, jump_target=16), ] assert tracer.loops == [ Loop( start_offset=16, end_offset=get_value({"py38": 32, "default": 24}), start_lineno=22, ) ] test_server.assert_frame_sent("test_continue_in_finally")
async def reduce_pull_request(pull_request): # Разбор pull_request result = {} for k, v in PULL_REQUEST.items(): result[k] = get_value(v, pull_request) return result
def get_variable_value(self, name, value_type=None): variable_sets = self.get_variable_sets(name) # Nothing ? if not variable_sets: return None # Get the last value return get_value(variable_sets[-1], value_type)
def chapter_info(content): """ Scrapes all chapter information of a specific novel. Both latest released chapters and if the novel is complete. :param content: The content page of a novel. :returns: A dictionary with scraped and cleaned information. """ chap_info = dict() chapter_status = get_value_str_txt(content.find('div', attrs={'id': 'editstatus'})) if chapter_status is not None: chap_info['complete_original'] = 'complete' in chapter_status.lower() chapter_current = re.search(r'(\d+)[ wnl]*(?=chap)', chapter_status.lower()) if chapter_current is not None: chapter_current = chapter_current.group(1).strip() + " chapters" else: # Check if volume chapter_current = re.search(r'(\d+)[ wnl]*(?=volu)', chapter_status.lower()) if chapter_current is not None: chapter_current = chapter_current.group(1).strip() + " volumes" else: # Get the first number chapter_current = re.search(r'(\d+)', chapter_status.lower()) if chapter_current is not None: chapter_current = chapter_current.group(1).strip() chap_info['chapters_original_current'] = chapter_current if chapter_current != "" else None chap_info['complete_translated'] = str2bool(get_value(content.find('div', attrs={'id': 'showtranslated'}))) table = content.find('table', attrs={'id': 'myTable'}) if table is not None: release_table = table.find('tbody') chap_info['chapter_latest_translated'] = release_table.find('tr').find_all('td')[2].a.string.strip() return chap_info
def running(self): if (self.disk_status): return False path = self.home + "/status/status" try: fd = open(path, 'r') except IOError as err: if err.errno != errno.ENOENT: raise else: return False try: fcntl.flock(fd.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError as err: if err.errno != errno.EAGAIN: raise else: buf = get_value(path) if (buf == "running\n"): return True else: return False fcntl.flock(fd.fileno(), fcntl.LOCK_UN) fd.close() return False
def agregar(request): """ Agrega una nueva expecialidad de Medico """ plantilla = get_template('especialidades/nueva.html') dict = generar_base_dict(request) dict['titulo'] = 'Agregar Expecialidad' query = int(request.POST.get('query', '0')) dict['query'] = query if query: nombre = get_value(request, 'nombre', '') if nombre != '': if not(Expecialidades.objects.filter(nombre=nombre)): exp = Expecialidades(nombre=nombre) exp.save() dict['msj_class'] = MSJ_OK dict['mensaje'] = 'Se a Agregado %s' %nombre else: dict['msj_class'] = MSJ_ERROR dict['mensaje'] = 'Error la expecialidad ya existe %s' %nombre contexto = Context(dict) html = plantilla.render(contexto) return HttpResponse(html)
def test_numpy(tracer, test_server): tracer.start() x = np.array([6, 7, 8]) tracer.stop() from utils import get_os_type, get_value int_type = get_value({ "windows": "int32", "linux": "int64", "mac": "int64" }) assert tracer.events == [ Binding( lineno=8, target=Symbol("x"), value=f'{{"dtype":"{int_type}","values":[6,7,8]}}', repr="array([6,7,8])", sources=set(), ) ] if get_os_type() != "windows": test_server.assert_frame_sent("test_numpy")
def publisher_info(content): """ Scrapes all publisher information of a specific novel. :param content: The content page of a novel. :returns: A dictionary with scraped and cleaned information. """ pub_info = dict() pub_info['start_year'] = get_value(content.find('div', attrs={'id': 'edityear'}), ) pub_info['licensed'] = str2bool(get_value(content.find('div', attrs={'id': 'showlicensed'}))) pub_info['original_publisher'] = get_value(content.find('div', attrs={'id': 'showopublisher'}), lambda e: e.a, lambda e: e.a.string.strip().lower()) pub_info['english_publisher'] = get_value(content.find('div', attrs={'id': 'showepublisher'}), lambda e: e.a, lambda e: e.a.string.strip().lower()) return pub_info
def test_pandas(tracer, mocked_responses): tracer.start() baby_data_set = [ ("Bob", 968), ("Jessica", 155), ("Mary", 77), ("John", 578), ("Mel", 973), ] df = pd.DataFrame(data=baby_data_set, columns=["Names", "Births"]) tracer.stop() from utils import get_value eol = get_value({"windows": r"\r\n", "linux": r"\n", "mac": "\\n"}) assert tracer.events == [ Binding( lineno=get_value({"py37": 13, "default": 8}), target=Symbol("baby_data_set"), value='[["Bob",968],["Jessica",155],["Mary",77],["John",578],["Mel",973]]', repr=( "[('Bob', 968), ('Jessica', 155), " "('Mary', 77), ('John', 578), ('Mel', 973)]" ), sources=set(), ), Binding( lineno=15, target=Symbol("df"), value=( f'{{"values":"Names,Births{eol}Bob,968{eol}Jessica,155{eol}' f'Mary,77{eol}John,578{eol}Mel,973{eol}"' ',"txt":true,"meta":{"dtypes":{"Names":"object","Births":"int64"},' '"index":"{\\"py/object\\":\\"pandas.core.indexes.range.RangeIndex\\"' ',\\"values\\":\\"[0,1,2,3,4]\\",\\"txt\\":true,\\"meta\\":{\\"dtype\\"' ':\\"int64\\",\\"name\\":null}}",' '"column_level_names":[null],"header":[0]}}' ), repr=( " Names Births\n0 Bob 968\n1 Jessica 155\n2" " Mary 77\n3 John 578\n4 Mel 973" ), sources={Symbol("baby_data_set")}, ), ]
def test_while_jump_to_zero(trace): @trace def while_jump_to_zero(count): while count > 0: count -= 1 while_jump_to_zero(2) assert trace.events == [ InitialValue( lineno=103, target=Symbol("count"), value="2", repr="2", ), Binding( lineno=104, target=Symbol("count"), value="1", repr="1", sources={Symbol("count")}, ), JumpBackToLoopStart(lineno=104, jump_target=get_value({ "py37": 2, "default": 0 })), Binding( lineno=104, target=Symbol("count"), value="0", repr="0", sources={Symbol("count")}, ), JumpBackToLoopStart(lineno=104, jump_target=get_value({ "py37": 2, "default": 0 })), Return( lineno=104, value="null", repr="None", sources=set(), ), ]
def test_numpy(tracer, check_golden_file): tracer.start() x = np.array([6, 7, 8]) tracer.stop() from utils import get_value int_type = get_value({"windows": "int32", "linux": "int64", "mac": "int64"})
def compute_q(MDP, V, s, a): '''根据给定的MDP,价值函数V,计算状态行为对s,a的价值qsa ''' S, A, R, P, gamma = MDP q_sa = 0 print('对当前的行为' + str(a) + '计算它的行为价值计算,对行为,计算其对应所有状态的价值') for s_prime in S: print('状态' + str(s) + '经过a行为,' + str(a) + '获取转移概率' + str(get_prob(P, s, a, s_prime)) + '以及分数' + str(get_value(V, s_prime))) q_sa += get_prob(P, s, a, s_prime) * get_value(V, s_prime) print('状态' + str(s) + '经过a行为,' + str(a) + str(q_sa)) q_sa = get_reward(R, s, a) + gamma * q_sa print('算出这个行为价值为' + str(q_sa)) return q_sa
def compute_q(MDP, V, s, a): S, A, R, P, gamma = MDP #s采取动作a之后可能的状态 q_sa = 0.0 for s_prime in S: q_sa += get_prob(P, s, a, s_prime) * get_value(V, s_prime) q_sa = get_reward(R, s, a) + gamma * q_sa return q_sa
def obtain_data_set_avg(self): result = [] now_value = utils.get_value(self.locations, self.raw_value) if not utils.check_list_null(self.data_sets): compare_set = map(utils.get_avg, self.data_sets) return now_value, compare_set else: return None, None
def parse_response(data): values = data.get('doors').get('values') doors = {} for door in values: doors[get_value(door, 'location')] = get_value(door, 'locked') json = [] for location in ['frontLeft', 'frontRight', 'backLeft', 'backRight']: if location not in doors: continue json.append({ 'location': location, 'locked': doors[location], }) return json
def parse_line(self, tree, portindex, line): """ Parse line into dict where value is str, list or extended list """ line = line.lstrip() key = self._select_key(line) for item in self.list_items: if line.startswith(item): index = self._get_index(line) if line.startswith('switchport trunk allowed vlan'): self.values[index].extend(splitrange(get_value(key, line))) tree['port'][portindex]['vlan_allow_list'] \ = self.values[index] return tree else: self.values[index].append(get_value(key, line)) tree['port'][portindex][item] = self.values[index] return tree tree['port'][portindex][key] = get_value(key, line) return tree
def compute_q(MDP, V, s, a): '''根据给定的MDP, 价值函数V, 计算(状态行为对)s, a的价值qsa 公式 2.16 ''' S, A, R, P, gamma = MDP q_sa = 0 for s_prime in S: q_sa += get_prob(P, s, a, s_prime) * get_value(V, s_prime) q_sa = get_reward(R, s, a) + gamma * q_sa return q_sa
def __parse_data(self): section = self.sections['.data'] last_free = 1 # first cell is for IP for line in section: tokens = line.split() assert len(tokens) > 1 # name value addr = last_free if addr >= len(self.memory): self.__grow_memory(addr + 1) self.memory[addr] = get_value(' '.join(tokens[1:])) last_free += 1
def compute_q(MDP, V, s, a): ''' According to the given MDP, the value function V, calculate the value qsa of the state behavior to s, a formula $$q_{\pi}(s,a) = R^a_b + \gamma \sum_{s' \in S}P^a_{ss'} \nu \pi(s') $$ #markdown ''' S, A, R, P, gamma = MDP q_sa = 0 for s_prime in S: q_sa += get_prob(P, s, a, s_prime) * get_value(V, s_prime) q_sa = get_reward(R, s, a) + gamma * q_sa return q_sa
def __redis_pid(self, force): pidfile = os.path.join(self.workdir, 'run/redis-server.pid') while (1): if os.path.exists(pidfile): self.redis_pid = int(get_value(pidfile)) break else: if force: time.sleep(0.1) else: break
def __layout_local(self): config = os.path.join(self.workdir, "config") #dmsg("load local layout") try: self.volume = get_value(config + "/volume") if (self.volume[-1] == '\n'): self.volume = self.volume[:-1] v = get_value(config + "/id") t = v[1:-1].split(',') self.id = (int(t[0]), int(t[1])) v = get_value(config + "/port") self.port_idx = int(v) self.port = str(self.config.redis_baseport + self.port_idx) return True except: self.port = None #dmsg("load local layout fail") return False
def __set_ldconfig(self): ldconfig = "/etc/ld.so.conf.d/sdfs.conf" libs = ["%s/app/lib" % (self.home), "/usr/local/lib"] if os.path.isfile(ldconfig): v = get_value(ldconfig) if not v.startswith(self.home): dwarn("home is: %s, but ldconfig unmatched!!!" % (self.home)) else: for lib in libs: cmd = "echo %s >> %s" % (lib, ldconfig) exec_shell(cmd) exec_shell("ldconfig")
def general_info(content): """ Scrapes all general information of a specific novel. :param content: The content page of a novel. :returns: A dictionary with scraped and cleaned information. """ gen_info = dict() gen_info['name'] = get_value(content.find('div', attrs={'class', 'seriestitlenu'})) gen_info['assoc_names'] = get_value(content.find('div', attrs={'id': 'editassociated'}), check=lambda e: e, parse=lambda e: list(e.stripped_strings)) gen_info['original_language'] = get_value(content.find('div', attrs={'id': 'showlang'}), lambda e: e.a, lambda e: e.text.strip().lower()) gen_info['authors'] = [author.text.lower() for author in content.find('div', attrs={'id': 'showauthors'}).find_all('a')] gen_info['genres'] = [genre.text.lower() for genre in content.find('div', attrs={'id': 'seriesgenre'}).find_all('a', attrs={'class': 'genre'})] gen_info['tags'] = [tag.text.lower() for tag in content.find('div', attrs={'id': 'showtags'}).find_all('a')] return gen_info
def test_nested_loop(tracer, check_golden_file): tracer.start() for i in range(2): for j in range(2): a = i + j tracer.stop() assert tracer.loops == [ Loop( start_offset=get_value({"default": 28, "py37": 32}), end_offset=get_value({"default": 40, "py37": 44}), start_lineno=9, end_lineno=10, ), Loop( start_offset=get_value({"default": 16, "py37": 18}), end_offset=get_value({"default": 42, "py37": 48}), start_lineno=8, end_lineno=10, ), ]
def check_targets_conditions(targets_conditions, counters, frame): # List to keep the conditions that weren't true remaining_conditions = [] for condition in targets_conditions: # Get value of left operand left_operand = condition['condition']['left_operand'] left_operand_value = get_value(left_operand, counters) operator = condition['condition']['operator'] # Get value of right operand right_operand = condition['condition']['right_operand'] right_operand_value = get_value(right_operand, counters) left_operand = left_operand.replace('-', '_') context = { left_operand: left_operand_value, right_operand: right_operand_value } expression = f"{left_operand} {operator} {right_operand}" expression_value = eval(expression, context) if expression_value is True: # Execute action action = condition['action'] action_args = condition['action_arguments'] # If the action requires the frame, append it to the arguments if action in actions.ACTIONS_THAT_REQUIRE_FRAME: action_args.append(frame) actions.do(action, *action_args) else: # If the current condition wasn't met we keep it for the next round remaining_conditions.append(condition) # Update the list to the conditions that haven't been met targets_conditions[:] = remaining_conditions[:]
def delay(self): return get_value(self._delay, self.signalchain)
def fadein(self): return get_value(self._fadein, self.signalchain)
def exponentialslope(self): return get_value(self._exponentialslope, self.envelope)
def volume(self): return get_value(self._volume, self.parent)
def sync(self): return get_value(self._sync, self.signalchain)
def gatereset(self): return get_value(self._gatereset, self.signalchain)
def pulsewidth(self): return get_value(self._pulsewidth, self.signalchain)
def attackmod(self): return get_value(self._attackmod, self.envelope)
def attacktime(self): return get_value(self._attacktime, self.envelope)
def sustainlevel(self): return get_value(self._sustainlevel, self.envelope)
def sustaintime(self): return get_value(self._sustaintime, self.envelope)
def releasetime(self): return get_value(self._releasetime, self.envelope)
def polyphony(self): return get_value(self._polyphony, self.parent)
def phase(self): return get_value(self._phase, self.signalchain)
def speed(self): return get_value(self._speed, self.signalchain)
def legato(self): return get_value(self._legato, self.envelope)
def get_user_field_value(self, name, value_type=None): user_field_decl = self.get_user_field_decl(name) # Nothing ? if user_field_decl is None: return None return get_value(user_field_decl, value_type)
def freerun(self): return get_value(self._freerun, self.envelope)
def synctoggle(self): return get_value(self._synctoggle, self.signalchain)
def loop(self): return get_value(self._loop, self.envelope)
def decaytime(self): return get_value(self._decaytime, self.envelope)
def pitchbendrange(self): return get_value(self._pitchbendrange, self.parent)
def __init__(self): self.server = get_value("REDIS_SERVER_HOST")
def ampmod(self): return get_value(self._ampmod, self.envelope)