Search is not available for this dataset
text
stringlengths
75
104k
def _get_diff(self, cp_file): """Get a diff between running config and a proposed file.""" diff = [] self._create_sot_file() diff_out = self.device.show( 'show diff rollback-patch file {0} file {1}'.format( 'sot_file', self.replace_file.split('/')[-1]), raw_te...
def _save_config(self, filename): """Save the current running config to the given file.""" self.device.show('checkpoint file {}'.format(filename), raw_text=True)
def open(self): """Open the connection wit the device.""" try: self.device.open() except ConnectTimeoutError as cte: raise ConnectionException(cte.message) self.device.timeout = self.timeout self.device._conn._session.transport.set_keepalive(self.keepalive...
def _lock(self): """Lock the config DB.""" if not self.locked: self.device.cu.lock() self.locked = True
def _unlock(self): """Unlock the config DB.""" if self.locked: self.device.cu.unlock() self.locked = False
def compare_config(self): """Compare candidate config with running.""" diff = self.device.cu.diff() if diff is None: return '' else: return diff.strip()
def commit_config(self): """Commit configuration.""" self.device.cu.commit(ignore_warning=self.ignore_warning) if not self.config_lock: self._unlock()
def discard_config(self): """Discard changes (rollback 0).""" self.device.cu.rollback(rb_id=0) if not self.config_lock: self._unlock()
def get_facts(self): """Return facts of the device.""" output = self.device.facts uptime = self.device.uptime or -1 interfaces = junos_views.junos_iface_table(self.device) interfaces.get() interface_list = interfaces.keys() return { 'vendor': u'Juni...
def get_interfaces(self): """Return interfaces details.""" result = {} interfaces = junos_views.junos_iface_table(self.device) interfaces.get() # convert all the tuples to our pre-defined dict structure for iface in interfaces.keys(): result[iface] = { ...
def _get_address_family(table): """ Function to derive address family from a junos table name. :params table: The name of the routing table :returns: address family """ address_family_mapping = { 'inet': 'ipv4', 'inet6': 'ipv6', 'inetf...
def get_bgp_neighbors(self): """Return BGP neighbors details.""" bgp_neighbor_data = {} default_neighbor_details = { 'local_as': 0, 'remote_as': 0, 'remote_id': '', 'is_up': False, 'is_enabled': False, 'description': '', ...
def get_lldp_neighbors(self): """Return LLDP neighbors details.""" lldp = junos_views.junos_lldp_table(self.device) try: lldp.get() except RpcError as rpcerr: # this assumes the library runs in an environment # able to handle logs # otherwi...
def get_lldp_neighbors_detail(self, interface=''): """Detailed view of the LLDP neighbors.""" lldp_neighbors = {} lldp_table = junos_views.junos_lldp_neighbors_detail_table(self.device) try: lldp_table.get() except RpcError as rpcerr: # this assumes the l...
def get_arp_table(self): """Return the ARP table.""" # could use ArpTable # from jnpr.junos.op.phyport import ArpTable # and simply use it # but # we need: # - filters # - group by VLAN ID # - hostname & TTE fields as well arp_table ...
def get_ntp_peers(self): """Return the NTP peers configured on the device.""" ntp_table = junos_views.junos_ntp_peers_config_table(self.device) ntp_table.get() ntp_peers = ntp_table.items() if not ntp_peers: return {} return {napalm_base.helpers.ip(peer[0])...
def get_ntp_servers(self): """Return the NTP servers configured on the device.""" ntp_table = junos_views.junos_ntp_servers_config_table(self.device) ntp_table.get() ntp_servers = ntp_table.items() if not ntp_servers: return {} return {napalm_base.helpers.i...
def get_ntp_stats(self): """Return NTP stats (associations).""" # NTP Peers does not have XML RPC defined # thus we need to retrieve raw text and parse... # :( ntp_stats = [] REGEX = ( '^\s?(\+|\*|x|-)?([a-zA-Z0-9\.+-:]+)' '\s+([a-zA-Z0-9\.]+)\s+...
def get_mac_address_table(self): """Return the MAC address table.""" mac_address_table = [] if self.device.facts.get('personality', '') in ['SWITCH']: # for EX & QFX devices if self.device.facts.get('switch_style', '') in ['VLAN_L2NG']: # for L2NG devices mac_table...
def get_probes_config(self): """Return the configuration of the RPM probes.""" probes = {} probes_table = junos_views.junos_rpm_probes_config_table(self.device) probes_table.get() probes_table_items = probes_table.items() for probe_test in probes_table_items: ...
def get_probes_results(self): """Return the results of the RPM probes.""" probes_results = {} probes_results_table = junos_views.junos_rpm_probes_results_table(self.device) probes_results_table.get() probes_results_items = probes_results_table.items() for probe_result i...
def traceroute(self, destination, source=C.TRACEROUTE_SOURCE, ttl=C.TRACEROUTE_TTL, timeout=C.TRACEROUTE_TIMEOUT, vrf=C.TRACEROUTE_VRF): """Execute traceroute and return results.""" traceroute_result = {} ...
def parse_intf_section(interface): """Parse a single entry from show interfaces output. Different cases: mgmt0 is up admin state is up Ethernet2/1 is up admin state is up, Dedicated Interface Vlan1 is down (Administratively down), line protocol is down, autostate enabled Ethernet154/...
def _get_diff(self): """Get a diff between running config and a proposed file.""" diff = [] self._create_sot_file() command = ('show diff rollback-patch file {0} file {1}'.format( 'sot_file', self.replace_file.split('/')[-1])) diff_out = self.device.send_comman...
def _save_to_checkpoint(self, filename): """Save the current running config to the given file.""" command = 'checkpoint file {}'.format(filename) self.device.send_command(command)
def get_facts(self): """Return a set of facts from the devices.""" # default values. vendor = u'Cisco' uptime = -1 serial_number, fqdn, os_version, hostname, domain_name = ('',) * 5 # obtain output from device show_ver = self.device.send_command('show version') ...
def get_arp_table(self): """ Get arp table information. Return a list of dictionaries having the following set of keys: * interface (string) * mac (string) * ip (string) * age (float) For example:: [ { ...
def get_mac_address_table(self): """ Returns a lists of dictionaries. Each dictionary represents an entry in the MAC Address Table, having the following keys * mac (string) * interface (string) * vlan (int) * active (boolean) * static (...
def get(self, request, format=None): """ Remove all auth tokens owned by request.user. """ tokens = Token.objects.filter(user=request.user) for token in tokens: token.delete() content = {'success': _('User logged out.')} return Response(content, status...
def _set_attrs_to_values(self, response={}): """ Set attributes to dictionary values so can access via dot notation. """ for key in response.keys(): setattr(self, key, response[key])
def add_custom_nl2br_filters(self, app): """Add a custom filter nl2br to jinja2 Replaces all newline to <BR> """ _paragraph_re = re.compile(r'(?:\r\n|\r|\n){3,}') @app.template_filter() @evalcontextfilter def nl2br(eval_ctx, value): result = '\n\n'.j...
def doc(self, groups=None, set_location=True, **properties): """Add flask route to autodoc for automatic documentation Any route decorated with this method will be added to the list of routes to be documented by the generate() or html() methods. By default, the route is added to the 'a...
def generate(self, groups='all', sort=None): """Return a list of dict describing the routes specified by the doc() method Each dict contains: - methods: the set of allowed methods (ie ['GET', 'POST']) - rule: relative url (ie '/user/<int:id>') - endpoint: function nam...
def html(self, groups='all', template=None, **context): """Return an html string of the routes specified by the doc() method A template can be specified. A list of routes is available under the 'autodoc' value (refer to the documentation for the generate() for a description of available...
def unsaved_files_dialog( self, all_files=False, with_cancel=True, with_discard=True): """Return true if OK to continue with close or quit or whatever""" for image in self.images: if image.metadata.changed() and (all_files or image.selected): break else: ...
def from_ISO_8601(cls, date_string, time_string, tz_string): """Sufficiently general ISO 8601 parser. Inputs must be in "basic" format, i.e. no '-' or ':' separators. See https://en.wikipedia.org/wiki/ISO_8601 """ # parse tz_string if tz_string: tz_offset = ...
def post_post(): """Create a new post. Form Data: title, content, authorid. """ authorid = request.form.get('authorid', None) Post(request.form['title'], request.form['content'], users[authorid]) return redirect("/posts")
def xpath(self, xpath): """ Finds another node by XPath originating at the current node. """ return [self.get_node_factory().create(node_id) for node_id in self._get_xpath_ids(xpath).split(",") if node_id]
def css(self, css): """ Finds another node by a CSS selector relative to the current node. """ return [self.get_node_factory().create(node_id) for node_id in self._get_css_ids(css).split(",") if node_id]
def get_bool_attr(self, name): """ Returns the value of a boolean HTML attribute like `checked` or `disabled` """ val = self.get_attr(name) return val is not None and val.lower() in ("true", name)
def set_attr(self, name, value): """ Sets the value of an attribute. """ self.exec_script("node.setAttribute(%s, %s)" % (repr(name), repr(value)))
def value(self): """ Returns the node's value. """ if self.is_multi_select(): return [opt.value() for opt in self.xpath(".//option") if opt["selected"]] else: return self._invoke("value")
def set_header(self, key, value): """ Sets a HTTP header for future requests. """ self.conn.issue_command("Header", _normalize_header(key), value)
def headers(self): """ Returns a list of the last HTTP response headers. Header keys are normalized to capitalized form, as in `User-Agent`. """ headers = self.conn.issue_command("Headers") res = [] for header in headers.split("\r"): key, value = header.split(": ", 1) for line in val...
def eval_script(self, expr): """ Evaluates a piece of Javascript in the context of the current page and returns its value. """ ret = self.conn.issue_command("Evaluate", expr) return json.loads("[%s]" % ret)[0]
def render(self, path, width = 1024, height = 1024): """ Renders the current page to a PNG file (viewport size in pixels). """ self.conn.issue_command("Render", path, width, height)
def cookies(self): """ Returns a list of all cookies in cookie string format. """ return [line.strip() for line in self.conn.issue_command("GetCookies").split("\n") if line.strip()]
def set_attribute(self, attr, value = True): """ Sets a custom attribute for our Webkit instance. Possible attributes are: * ``auto_load_images`` * ``dns_prefetch_enabled`` * ``plugins_enabled`` * ``private_browsing_enabled`` * ``javascript_can_open_windows`` * ``javascript_can_...
def set_html(self, html, url = None): """ Sets custom HTML in our Webkit session and allows to specify a fake URL. Scripts and CSS is dynamically fetched as if the HTML had been loaded from the given URL. """ if url: self.conn.issue_command('SetHtml', html, url) else: self.conn.issue_com...
def set_proxy(self, host = "localhost", port = 0, user = "", password = ""): """ Sets a custom HTTP proxy to use for future requests. """ self.conn.issue_command("SetProxy", host, port, user, password)
def connect(self): """ Returns a new socket connection to this server. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("127.0.0.1", self._port)) return sock
def read_line(self): """ Consume one line from the stream. """ while True: newline_idx = self.buf.find(b"\n") if newline_idx >= 0: res = self.buf[:newline_idx] self.buf = self.buf[newline_idx + 1:] return res chunk = self.f.recv(4096) if not chunk: raise E...
def read(self, n): """ Consume `n` characters from the stream. """ while len(self.buf) < n: chunk = self.f.recv(4096) if not chunk: raise EndOfStreamError() self.buf += chunk res, self.buf = self.buf[:n], self.buf[n:] return res
def issue_command(self, cmd, *args): """ Sends and receives a message to/from the server """ self._writeline(cmd) self._writeline(str(len(args))) for arg in args: arg = str(arg) self._writeline(str(len(arg))) self._sock.sendall(arg.encode("utf-8")) return self._read_response()
def _read_response(self): """ Reads a complete response packet from the server """ result = self.buf.read_line().decode("utf-8") if not result: raise NoResponseError("No response received from server.") msg = self._read_message() if result != "ok": raise InvalidResponseError(msg) r...
def _read_message(self): """ Reads a single size-annotated message from the server """ size = int(self.buf.read_line().decode("utf-8")) return self.buf.read(size).decode("utf-8")
def get_deep_search_results(self, address, zipcode): """ GetDeepSearchResults API """ url = 'http://www.zillow.com/webservice/GetDeepSearchResults.htm' params = { 'address': address, 'citystatezip': zipcode, 'zws-id': self.api_key } ...
def get_updated_property_details(self, zpid): """ GetUpdatedPropertyDetails API """ url = 'http://www.zillow.com/webservice/GetUpdatedPropertyDetails.htm' params = { 'zpid': zpid, 'zws-id': self.api_key } return self.get_data(url, params)
def fix_orientation(img, save_over=False): """ `img` can be an Image instance or a path to an image file. `save_over` indicates if the original image file should be replaced by the new image. * Note: `save_over` is only valid if `img` is a file path. """ path = None if not isinstance(img, Im...
def log_error(self, error, message, detail=None, strip=4): "Add an error message and optional user message to the error list" if message: msg = message + ": " + error else: msg = error tb = traceback.format_stack() if sys.version_info >= (3, 0): ...
def equal(self, a, b, message=None): "Check if two values are equal" if a != b: self.log_error("{} != {}".format(str(a), str(b)), message) return False return True
def is_not_none(self, a, message=None): "Check if a value is not None" if a is None: self.log_error("{} is None".format(str(a)), message) return False return True
def raises(self, exception_type, function, *args, **kwargs): """ Check if a function raises a specified exception type, *args and **kwargs are forwarded to the function """ try: result = function(*args, **kwargs) self.log_error("{} did not throw ex...
def does_not_raise(self, function, *args, **kwargs): """ Check if a function does not raise an exception, *args and **kwargs are forwarded to the function """ try: return function(*args, **kwargs) except Exception as e: self.log_error("{} d...
def calculate_color_temperature(r, g, b): """Converts the raw R/G/B values to color temperature in degrees Kelvin.""" # 1. Map RGB values to their XYZ counterparts. # Based on 6500K fluorescent, 3000K fluorescent # and 60W incandescent values for a wide range. # Note: Y = Illuminance or lux X = ...
def calculate_lux(r, g, b): """Converts the raw R/G/B values to luminosity in lux.""" illuminance = (-0.32466 * r) + (1.57837 * g) + (-0.73191 * b) return int(illuminance)
def _write8(self, reg, value): """Write a 8-bit value to a register.""" self._device.write8(TCS34725_COMMAND_BIT | reg, value)
def enable(self): """Enable the chip.""" # Flip on the power and enable bits. self._write8(TCS34725_ENABLE, TCS34725_ENABLE_PON) time.sleep(0.01) self._write8(TCS34725_ENABLE, (TCS34725_ENABLE_PON | TCS34725_ENABLE_AEN))
def disable(self): """Disable the chip (power down).""" # Flip off the power on and enable bits. reg = self._readU8(TCS34725_ENABLE) reg &= ~(TCS34725_ENABLE_PON | TCS34725_ENABLE_AEN) self._write8(TCS34725_ENABLE, reg)
def set_integration_time(self, integration_time): """Sets the integration time for the TC34725. Provide one of these constants: - TCS34725_INTEGRATIONTIME_2_4MS = 2.4ms - 1 cycle - Max Count: 1024 - TCS34725_INTEGRATIONTIME_24MS = 24ms - 10 cycles - Max Count: 10240 -...
def get_raw_data(self): """Reads the raw red, green, blue and clear channel values. Will return a 4-tuple with the red, green, blue, clear color values (unsigned 16-bit numbers). """ # Read each color register. r = self._readU16LE(TCS34725_RDATAL) g = self._readU1...
def set_interrupt(self, enabled): """Enable or disable interrupts by setting enabled to True or False.""" enable_reg = self._readU8(TCS34725_ENABLE) if enabled: enable_reg |= TCS34725_ENABLE_AIEN else: enable_reg &= ~TCS34725_ENABLE_AIEN self._write8(TCS34...
def set_interrupt_limits(self, low, high): """Set the interrupt limits to provied unsigned 16-bit threshold values. """ self._device.write8(0x04, low & 0xFF) self._device.write8(0x05, low >> 8) self._device.write8(0x06, high & 0xFF) self._device.write8(0x07, high >> 8)
def convert(json_input, build_direction="LEFT_TO_RIGHT", table_attributes=None): """ Converts JSON to HTML Table format. Parameters ---------- json_input : dict JSON object to convert into HTML. build_direction : {"TOP_TO_BOTTOM", "LEFT_TO_RIGHT"} String denoting the build direc...
def convert(self, json_input): """ Converts JSON to HTML Table format. Parameters ---------- json_input : dict JSON object to convert into HTML. Returns ------- str String of converted HTML. """ html_output = self....
def _dict_to_html_attributes(d): """ Converts a dictionary to a string of ``key=\"value\"`` pairs. If ``None`` is provided as the dictionary an empty string is returned, i.e. no html attributes are generated. Parameters ---------- d : dict Dictionary ...
def _list_of_dicts_to_column_headers(list_of_dicts): """ Detects if all entries in an list of ``dict``'s have identical keys. Returns the keys if all keys are the same and ``None`` otherwise. Parameters ---------- list_of_dicts : list List of dictionaries to ...
def _markup(self, entry): """ Recursively generates HTML for the current entry. Parameters ---------- entry : object Object to convert to HTML. Maybe be a single entity or contain multiple and/or nested objects. Returns ------- str ...
def _maybe_club(self, list_of_dicts): """ If all keys in a list of dicts are identical, values from each ``dict`` are clubbed, i.e. inserted under a common column heading. If the keys are not identical ``None`` is returned, and the list should be converted to HTML per the normal...
def update_voice_notify(self, param, must=[APIKEY, TPL_ID, TPL_CONTENT]): '''修改语音通知模版 注意:模板成功修改之后需要重新审核才能使用!同时提醒您如果修改了变量,务必重新测试,以免替换出错! 参数: 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 tpl_id Long 是 模板...
def code(self, code=None, ret_r=False): ''' Args: code: (Optional) set code ret_r: (Optional) force to return Result. Default value is False returns: response code(0-success, others-failure) or self ''' if code or ret_r: self._code ...
def msg(self, msg=None, ret_r=False): '''code's message''' if msg or ret_r: self._msg = msg return self return self._msg
def detail(self, detail=None, ret_r=False): '''code's detail''' if detail or ret_r: self._detail = detail return self return self._detail
def data(self, data=None, ret_r=False): '''response data''' if data or ret_r: self._data = data return self return self._data
def get(self, param=None, must=[APIKEY]): '''查账户信息 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 Args: param: (Optional) Results: Result ''' param = {} if param is None else param r = s...
def _init(self, clnt): '''initialize api by YunpianClient''' assert clnt, "clnt is None" self._clnt = clnt self._apikey = clnt.apikey() self._version = clnt.conf(YP_VERSION, defval=VERSION_V2) self._charset = clnt.conf(HTTP_CHARSET, defval=CHARSET_UTF8) self._name...
def name(self, name=None): '''api name, default is module.__name__''' if name: self._name = name return self return self._name
def post(self, param, h, r): ''' Args: param: request parameters h: ResultHandler r: YunpianApiResult ''' try: rsp = self.client().post(self.uri(), param) # print(rsp) return self.result(rsp, h, r) except Val...
def verify_param(self, param, must=[], r=None): '''return Code.ARGUMENT_MISSING if every key in must not found in param''' if APIKEY not in param: param[APIKEY] = self.apikey() r = Result() if r is None else r for p in must: if p not in param: r.c...
def custom_conf(self, conf): '''custom apikey and http parameters''' if conf: for (key, val) in conf.items(): self.__conf[key] = val return self
def conf(self, key): '''get config''' return self.__conf[key] if key in self.__conf else _YunpianConf.YP_CONF.get(key)
def api(self, name): '''return special API by package's name''' assert name, 'name is none' if flow.__name__ == name: api = flow.FlowApi() elif sign.__name__ == name: api = sign.SignApi() elif sms.__name__ == name: api = sms.SmsApi() e...
def conf(self, key=None, defval=None): '''return YunpianConf if key=None, else return value in YunpianConf''' if key is None: return self._ypconf val = self._ypconf.conf(key) return defval if val is None else val
def post(self, url, data, charset=CHARSET_UTF8, headers={}): '''response json text''' if 'Api-Lang' not in headers: headers['Api-Lang'] = 'python' if 'Content-Type' not in headers: headers['Content-Type'] = "application/x-www-form-urlencoded;charset=" + charset rs...
def urlEncodeAndJoin(self, seq, sepr=','): '''sepr.join(urlencode(seq)) Args: seq: string list to be urlencoded sepr: join seq with sepr Returns: str ''' try: from urllib.parse import quote_plus as encode return sepr.joi...
def send(self, param, must=[APIKEY, MOBILE, CODE]): '''发语音验证码 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 mobile String 是 接收的手机号、固话(需加区号) 15205201314 01088880000 code String 是 验证码,支持4~6位阿拉伯数字 1234 encrypt String 否 加密方式 使用加密 tea (不再使用) ...
def single_send(self, param, must=[APIKEY, MOBILE, TEXT]): '''单条发送 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 mobile String 是 接收的手机号;仅支持单号码发送;国际号码需包含国际地区前缀号码,格式必须是"+"号开头("+"号需要urlencode处理,否则会出现格式错误),国际号码不以"+"开头将被认为是中国地区的号码 (针对国际短信,m...
def pull_reply(self, param=None, must=[APIKEY]): '''获取回复短信 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 page_size Integer 否 每页个数,最大100个,默认20个 20 Args: param: Results: Result ''' param =...
def get_reply(self, param, must=[APIKEY, START_TIME, END_TIME, PAGE_NUM, PAGE_SIZE]): '''查回复的短信 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 start_time String 是 短信回复开始时间 2013-08-11 00:00:00 end_time String 是 短信回复结束时间 2013-08-12 00:00:00 ...
def get_record(self, param, must=[APIKEY, START_TIME, END_TIME]): '''查短信发送记录 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 mobile String 否 需要查询的手机号 15205201314 start_time String 是 短信发送开始时间 2013-08-11 00:00:00 end_time String 是 短信发送结束时间...