code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
sel, f, t = (as_wires(w) for w in (sel, falsecase, truecase)) f, t = match_bitwidth(f, t) outwire = WireVector(bitwidth=len(f)) net = LogicNet(op='x', op_param=None, args=(sel, f, t), dests=(outwire,)) working_block().add_net(net) # this includes sanity check on the mux return outwire
def select(sel, truecase, falsecase)
Multiplexer returning falsecase for select==0, otherwise truecase. :param WireVector sel: used as the select input to the multiplexer :param WireVector falsecase: the WireVector selected if select==0 :param WireVector truecase: the WireVector selected if select==1 The hardware this generates is exactly the same as "mux" but by putting the true case as the first argument it matches more of the C-style ternary operator semantics which can be helpful for readablity. Example of mux as "ternary operator" to take the max of 'a' and 5: :: select( a<5, truecase=a, falsecase=5 )
9.472239
10.280642
0.921367
if len(args) <= 0: raise PyrtlError('error, concat requires at least 1 argument') if len(args) == 1: return as_wires(args[0]) arg_wirevectors = tuple(as_wires(arg) for arg in args) final_width = sum(len(arg) for arg in arg_wirevectors) outwire = WireVector(bitwidth=final_width) net = LogicNet( op='c', op_param=None, args=arg_wirevectors, dests=(outwire,)) working_block().add_net(net) return outwire
def concat(*args)
Concatenates multiple WireVectors into a single WireVector :param WireVector args: inputs to be concatenated :return: WireVector with length equal to the sum of the args' lengths You can provide multiple arguments and they will be combined with the right-most argument being the least significant bits of the result. Note that if you have a list of arguments to concat together you will likely want index 0 to be the least significant bit and so if you unpack the list into the arguements here it will be backwards. The function concat_list is provided for that case specifically. Example using concat to combine two bytes into a 16-bit quantity: :: concat( msb, lsb )
3.795377
4.255752
0.891823
a, b = match_bitwidth(as_wires(a), as_wires(b), signed=True) result_len = len(a) + 1 ext_a = a.sign_extended(result_len) ext_b = b.sign_extended(result_len) # add and truncate to the correct length return (ext_a + ext_b)[0:result_len]
def signed_add(a, b)
Return wirevector for result of signed addition. :param a: a wirevector to serve as first input to addition :param b: a wirevector to serve as second input to addition Given a length n and length m wirevector the result of the signed addition is length max(n,m)+1. The inputs are twos complement sign extended to the same length before adding.
4.375788
3.956464
1.105985
a, b = as_wires(a), as_wires(b) final_len = len(a) + len(b) # sign extend both inputs to the final target length a, b = a.sign_extended(final_len), b.sign_extended(final_len) # the result is the multiplication of both, but truncated # TODO: this may make estimates based on the multiplication overly # pessimistic as half of the multiply result is thrown right away! return (a * b)[0:final_len]
def signed_mult(a, b)
Return a*b where a and b are treated as signed values.
7.283904
7.187953
1.013349
a, b = match_bitwidth(as_wires(a), as_wires(b), signed=True) r = a - b return r[-1] ^ (~a[-1]) ^ (~b[-1])
def signed_lt(a, b)
Return a single bit result of signed less than comparison.
7.433799
6.616402
1.123541
a, b = match_bitwidth(as_wires(a), as_wires(b), signed=True) r = a - b return (r[-1] ^ (~a[-1]) ^ (~b[-1])) | (a == b)
def signed_le(a, b)
Return a single bit result of signed less than or equal comparison.
7.417902
6.70383
1.106517
a, b = match_bitwidth(as_wires(a), as_wires(b), signed=True) r = b - a return r[-1] ^ (~a[-1]) ^ (~b[-1])
def signed_gt(a, b)
Return a single bit result of signed greater than comparison.
7.299351
6.732351
1.08422
a, b = match_bitwidth(as_wires(a), as_wires(b), signed=True) r = b - a return (r[-1] ^ (~a[-1]) ^ (~b[-1])) | (a == b)
def signed_ge(a, b)
Return a single bit result of signed greater than or equal comparison.
7.281555
6.872951
1.059451
a, shamt = _check_shift_inputs(bits_to_shift, shift_amount) bit_in = bits_to_shift[-1] # shift in sign_bit dir = Const(0) # shift right return barrel.barrel_shifter(bits_to_shift, bit_in, dir, shift_amount)
def shift_right_arithmetic(bits_to_shift, shift_amount)
Shift right arithmetic operation. :param bits_to_shift: WireVector to shift right :param shift_amount: WireVector specifying amount to shift :return: WireVector of same length as bits_to_shift This function returns a new WireVector of length equal to the length of the input `bits_to_shift` but where the bits have been shifted to the right. An arithemetic shift is one that treats the value as as signed number, meaning the sign bit (the most significant bit of `bits_to_shift`) is shifted in. Note that `shift_amount` is treated as unsigned.
8.669569
9.042011
0.95881
# TODO: when we drop 2.7 support, this code should be cleaned up with explicit # kwarg support for "signed" rather than the less than helpful "**opt" if len(opt) == 0: signed = False else: if len(opt) > 1 or 'signed' not in opt: raise PyrtlError('error, only supported kwarg to match_bitwidth is "signed"') signed = bool(opt['signed']) max_len = max(len(wv) for wv in args) if signed: return (wv.sign_extended(max_len) for wv in args) else: return (wv.zero_extended(max_len) for wv in args)
def match_bitwidth(*args, **opt)
Matches the bitwidth of all of the input arguments with zero or sign extend :param args: WireVectors of which to match bitwidths :param opt: Optional keyword argument 'signed=True' (defaults to False) :return: tuple of args in order with extended bits Example of matching the bitwidths of two WireVectors `a` and `b` with with zero extention: :: a,b = match_bitwidth(a, b) Example of matching the bitwidths of three WireVectors `a`,`b`, and `c` with with sign extention: :: a,b = match_bitwidth(a, b, c, signed=True)
5.132317
4.781093
1.073461
from .memory import _MemIndexed block = working_block(block) if isinstance(val, (int, six.string_types)): # note that this case captures bool as well (as bools are instances of ints) return Const(val, bitwidth=bitwidth, block=block) elif isinstance(val, _MemIndexed): # convert to a memory read when the value is actually used if val.wire is None: val.wire = as_wires(val.mem._readaccess(val.index), bitwidth, truncating, block) return val.wire elif not isinstance(val, WireVector): raise PyrtlError('error, expecting a wirevector, int, or verilog-style ' 'const string got %s instead' % repr(val)) elif bitwidth == '0': raise PyrtlError('error, bitwidth must be >= 1') elif val.bitwidth is None: raise PyrtlError('error, attempting to use wirevector with no defined bitwidth') elif bitwidth and bitwidth > val.bitwidth: return val.zero_extended(bitwidth) elif bitwidth and truncating and bitwidth < val.bitwidth: return val[:bitwidth] # truncate the upper bits else: return val
def as_wires(val, bitwidth=None, truncating=True, block=None)
Return wires from val which may be wires, integers, strings, or bools. :param val: a wirevector-like object or something that can be converted into a Const :param bitwidth: The bitwidth the resulting wire should be :param bool truncating: determines whether bits will be dropped to achieve the desired bitwidth if it is too long (if true, the most-significant bits will be dropped) :param Block block: block to use for wire This function is mainly used to coerce values into WireVectors (for example, operations such as "x+1" where "1" needs to be converted to a Const WireVector). An example: :: def myhardware(input_a, input_b): a = as_wires(input_a) b = as_wires(input_b) myhardware(3, x) The function as_wires will covert the 3 to Const but keep `x` unchanged assuming it is a WireVector.
4.82141
4.624355
1.042612
from .corecircuits import concat_list w = as_wires(w) idxs = list(range(len(w))) # we make a list of integers and slice those up to use as indexes idxs_lower = idxs[0:range_start] idxs_middle = idxs[range_start:range_end] idxs_upper = idxs[range_end:] if len(idxs_middle) == 0: raise PyrtlError('Cannot update bitfield of size 0 (i.e. there are no bits to update)') newvalue = as_wires(newvalue, bitwidth=len(idxs_middle), truncating=truncating) if len(idxs_middle) != len(newvalue): raise PyrtlError('Cannot update bitfield of length %d with value of length %d ' 'unless truncating=True is specified' % (len(idxs_middle), len(newvalue))) result_list = [] if idxs_lower: result_list.append(w[idxs_lower[0]:idxs_lower[-1]+1]) result_list.append(newvalue) if idxs_upper: result_list.append(w[idxs_upper[0]:idxs_upper[-1]+1]) result = concat_list(result_list) if len(result) != len(w): raise PyrtlInternalError('len(result)=%d, len(original)=%d' % (len(result), len(w))) return result
def bitfield_update(w, range_start, range_end, newvalue, truncating=False)
Return wirevector w but with some of the bits overwritten by newvalue. :param w: a wirevector to use as the starting point for the update :param range_start: the start of the range of bits to be updated :param range_end: the end of the range of bits to be updated :param newvalue: the value to be written in to the start:end range :param truncating: if true, clip the newvalue to be the proper number of bits Given a wirevector w, this function returns a new wirevector that is identical to w except in the range of bits specified. In that specified range, the value newvalue is swapped in. For example: `bitfield_update(w, 20, 23, 0x7)` will return return a wirevector of the same length as w, and with the same values as w, but with bits 20, 21, and 22 all set to 1. Note that range_start and range_end will be inputs to a slice and so standar Python slicing rules apply (e.g. negative values for end-relative indexing and support for None). :: w = bitfield_update(w, 20, 23, 0x7) # sets bits 20, 21, 22 to 1 w = bitfield_update(w, 20, 23, 0x6) # sets bit 20 to 0, bits 21 and 22 to 1 w = bitfield_update(w, 20, None, 0x7) # assuming w is 32 bits, sets bits 31..20 = 0x7 w = bitfield_update(w, -1, None, 0x1) # set the LSB (bit) to 1
2.758462
2.784818
0.990536
# check dictionary keys are of the right type keytypeset = set(type(x) for x in table.keys() if x is not otherwise) if len(keytypeset) != 1: raise PyrtlError('table mixes multiple types {} as keys'.format(keytypeset)) keytype = list(keytypeset)[0] # check that dictionary is complete for the enum try: enumkeys = list(keytype.__members__.values()) except AttributeError: raise PyrtlError('type {} not an Enum and does not support the same interface' .format(keytype)) missingkeys = [e for e in enumkeys if e not in table] # check for "otherwise" in table and move it to a default if otherwise in table: if default is not None: raise PyrtlError('both "otherwise" and default provided to enum_mux') else: default = table[otherwise] if strict and default is None and missingkeys: raise PyrtlError('table provided is incomplete, missing: {}'.format(missingkeys)) # generate the actual mux vals = {k.value: d for k, d in table.items() if k is not otherwise} if default is not None: vals['default'] = default return muxes.sparse_mux(cntrl, vals)
def enum_mux(cntrl, table, default=None, strict=True)
Build a mux for the control signals specified by an enum. :param cntrl: is a wirevector and control for the mux. :param table: is a dictionary of the form mapping enum->wirevector. :param default: is a wirevector to use when the key is not present. In addtion it is possible to use the key 'otherwise' to specify a default value, but it is an error if both are supplied. :param strict: is flag, that when set, will cause enum_mux to check that the dictionary has an entry for every possible value in the enum. Note that if a default is set, then this check is not performed as the default will provide valid values for any underspecified keys. :return: a wirevector which is the result of the mux. :: class Command(Enum): ADD = 1 SUB = 2 enum_mux(cntrl, {ADD: a+b, SUB: a-b}) enum_mux(cntrl, {ADD: a+b}, strict=False) # SUB case undefined enum_mux(cntrl, {ADD: a+b, otherwise: a-b}) enum_mux(cntrl, {ADD: a+b}, default=a-b)
4.114855
3.913583
1.051429
if len(vectorlist) <= 0: raise PyrtlError('rtl_any requires at least 1 argument') converted_vectorlist = [as_wires(v) for v in vectorlist] if any(len(v) != 1 for v in converted_vectorlist): raise PyrtlError('only length 1 WireVectors can be inputs to rtl_any') return or_all_bits(concat_list(converted_vectorlist))
def rtl_any(*vectorlist)
Hardware equivalent of python native "any". :param WireVector vectorlist: all arguments are WireVectors of length 1 :return: WireVector of length 1 Returns a 1-bit WireVector which will hold a '1' if any of the inputs are '1' (i.e. it is a big ol' OR gate)
3.829522
3.864932
0.990838
if len(vectorlist) <= 0: raise PyrtlError('rtl_all requires at least 1 argument') converted_vectorlist = [as_wires(v) for v in vectorlist] if any(len(v) != 1 for v in converted_vectorlist): raise PyrtlError('only length 1 WireVectors can be inputs to rtl_all') return and_all_bits(concat_list(converted_vectorlist))
def rtl_all(*vectorlist)
Hardware equivalent of python native "all". :param WireVector vectorlist: all arguments are WireVectors of length 1 :return: WireVector of length 1 Returns a 1-bit WireVector which will hold a '1' only if all of the inputs are '1' (i.e. it is a big ol' AND gate)
3.94759
3.899191
1.012413
if len(B) == 1: A, B = B, A # so that we can reuse the code below :) if len(A) == 1: return concat_list(list(A & b for b in B) + [Const(0)]) # keep WireVector len consistent result_bitwidth = len(A) + len(B) bits = [[] for weight in range(result_bitwidth)] for i, a in enumerate(A): for j, b in enumerate(B): bits[i + j].append(a & b) while not all(len(i) <= 2 for i in bits): deferred = [[] for weight in range(result_bitwidth + 1)] for i, w_array in enumerate(bits): # Start with low weights and start reducing while len(w_array) >= 3: # build a new full adder a, b, cin = (w_array.pop(0) for j in range(3)) deferred[i].append(a ^ b ^ cin) deferred[i + 1].append(a & b | a & cin | b & cin) if len(w_array) == 2: a, b = w_array deferred[i].append(a ^ b) deferred[i + 1].append(a & b) else: deferred[i].extend(w_array) bits = deferred[:result_bitwidth] import six add_wires = tuple(six.moves.zip_longest(*bits, fillvalue=Const(0))) adder_result = concat_list(add_wires[0]) + concat_list(add_wires[1]) return adder_result[:result_bitwidth]
def _basic_mult(A, B)
A stripped-down copy of the Wallace multiplier in rtllib
3.373542
3.316883
1.017082
global _depth _check_under_condition() _depth += 1 if predicate is not otherwise and len(predicate) > 1: raise PyrtlError('all predicates for conditional assignments must wirevectors of len 1') _conditions_list_stack[-1].append(predicate) _conditions_list_stack.append([])
def _push_condition(predicate)
As we enter new conditions, this pushes them on the predicate stack.
10.922882
9.974934
1.095033
_check_under_condition() final_predicate, pred_set = _current_select() _check_and_add_pred_set(lhs, pred_set) _predicate_map.setdefault(lhs, []).append((final_predicate, rhs))
def _build(lhs, rhs)
Stores the wire assignment details until finalize is called.
11.124697
10.095911
1.101901
# pred_sets conflict if we cannot find one shared predicate that is "negated" in one # and "non-negated" in the other for pred_a, bool_a in pred_set_a: for pred_b, bool_b in pred_set_b: if pred_a is pred_b and bool_a != bool_b: return False return True
def _pred_sets_are_in_conflict(pred_set_a, pred_set_b)
Find conflict in sets, return conflict if found, else None.
4.325364
4.510706
0.958911
from .memory import MemBlock from pyrtl.corecircuits import select for lhs in _predicate_map: # handle memory write ports if isinstance(lhs, MemBlock): p, (addr, data, enable) = _predicate_map[lhs][0] combined_enable = select(p, truecase=enable, falsecase=Const(0)) combined_addr = addr combined_data = data for p, (addr, data, enable) in _predicate_map[lhs][1:]: combined_enable = select(p, truecase=enable, falsecase=combined_enable) combined_addr = select(p, truecase=addr, falsecase=combined_addr) combined_data = select(p, truecase=data, falsecase=combined_data) lhs._build(combined_addr, combined_data, combined_enable) # handle wirevector and register assignments else: if isinstance(lhs, Register): result = lhs # default for registers is "self" elif isinstance(lhs, WireVector): result = 0 # default for wire is "0" else: raise PyrtlInternalError('unknown assignment in finalize') predlist = _predicate_map[lhs] for p, rhs in predlist: result = select(p, truecase=rhs, falsecase=result) lhs._build(result)
def _finalize()
Build the required muxes and call back to WireVector to finalize the wirevector build.
3.603704
3.459492
1.041686
# helper to create the conjuction of predicates def and_with_possible_none(a, b): assert(a is not None or b is not None) if a is None: return b if b is None: return a return a & b def between_otherwise_and_current(predlist): lastother = None for i, p in enumerate(predlist[:-1]): if p is otherwise: lastother = i if lastother is None: return predlist[:-1] else: return predlist[lastother+1:-1] select = None pred_set = set() # for all conditions except the current children (which should be []) for predlist in _conditions_list_stack[:-1]: # negate all of the predicates between "otherwise" and the current one for predicate in between_otherwise_and_current(predlist): select = and_with_possible_none(select, ~predicate) pred_set.add((predicate, True)) # include the predicate for the current one (not negated) if predlist[-1] is not otherwise: predicate = predlist[-1] select = and_with_possible_none(select, predicate) pred_set.add((predicate, False)) if select is None: raise PyrtlError('problem with conditional assignment') if len(select) != 1: raise PyrtlInternalError('conditional predicate with length greater than 1') return select, pred_set
def _current_select()
Function to calculate the current "predicate" in the current context. Returns a tuple of information: (predicate, pred_set). The value pred_set is a set([ (predicate, bool), ... ]) as described in the _reset_conditional_state
4.293907
3.940105
1.089795
is_rom = False bits = 2**mem.addrwidth * mem.bitwidth read_ports = len(mem.readport_nets) try: write_ports = len(mem.writeport_nets) except AttributeError: # dealing with ROMs if not isinstance(mem, RomBlock): raise PyrtlInternalError('Mem with no writeport_nets attribute' ' but not a ROM? Thats an error') write_ports = 0 is_rom = True ports = max(read_ports, write_ports) return bits, ports, is_rom
def _bits_ports_and_isrom_from_memory(mem)
Helper to extract mem bits and ports for estimation.
4.822021
4.569587
1.055242
if abc_cmd is None: abc_cmd = 'strash;scorr;ifraig;retime;dch,-f;map;print_stats;' else: # first, replace whitespace with commas as per yosys requirements re.sub(r"\s+", ',', abc_cmd) # then append with "print_stats" to generate the area and delay info abc_cmd = '%s;print_stats;' % abc_cmd def extract_area_delay_from_yosys_output(yosys_output): report_lines = [line for line in yosys_output.split('\n') if 'ABC: netlist' in line] area = re.match('.*area\s*=\s*([0-9\.]*)', report_lines[0]).group(1) delay = re.match('.*delay\s*=\s*([0-9\.]*)', report_lines[0]).group(1) return float(area), float(delay) yosys_arg_template = temp_d, temp_path = tempfile.mkstemp(suffix='.v') try: # write the verilog to a temp with os.fdopen(temp_d, 'w') as f: OutputToVerilog(f, block=block) # call yosys on the temp, and grab the output yosys_arg = yosys_arg_template % (temp_path, library, library, abc_cmd) yosys_output = subprocess.check_output(['yosys', yosys_arg]) area, delay = extract_area_delay_from_yosys_output(yosys_output) except (subprocess.CalledProcessError, ValueError) as e: print('Error with call to yosys...', file=sys.stderr) print('---------------------------------------------', file=sys.stderr) print(e.output, file=sys.stderr) print('---------------------------------------------', file=sys.stderr) raise PyrtlError('Yosys callfailed') except OSError as e: print('Error with call to yosys...', file=sys.stderr) raise PyrtlError('Call to yosys failed (not installed or on path?)') finally: os.remove(temp_path) return area, delay
def yosys_area_delay(library, abc_cmd=None, block=None)
Synthesize with Yosys and return estimate of area and delay. :param library: stdcell library file to target in liberty format :param abc_cmd: string of commands for yosys to pass to abc for synthesis :param block: pyrtl block to analyze :return: a tuple of numbers: area, delay The area and delay are returned in units as defined by the stdcell library. In the standard vsc 130nm library, the area is in a number of "tracks", each of which is about 1.74 square um (see area estimation for more details) and the delay is in ps. http://www.vlsitechnology.org/html/vsc_description.html May raise `PyrtlError` if yosys is not configured correctly, and `PyrtlInternalError` if the call to yosys was not able successfully
3.41592
3.280156
1.04139
cp_length = self.max_length() scale_factor = 130.0 / tech_in_nm if ffoverhead is None: clock_period_in_ps = scale_factor * (cp_length + 189 + 194) else: clock_period_in_ps = (scale_factor * cp_length) + ffoverhead return 1e6 * 1.0/clock_period_in_ps
def max_freq(self, tech_in_nm=130, ffoverhead=None)
Estimates the max frequency of a block in MHz. :param tech_in_nm: the size of the circuit technology to be estimated (for example, 65 is 65nm and 250 is 0.25um) :param ffoverhead: setup and ff propagation delay in picoseconds :return: a number representing an estimate of the max frequency in Mhz If a timing_map has already been generated by timing_analysis, it will be used to generate the estimate (and `gate_delay_funcs` will be ignored). Regardless, all params are optional and have reasonable default values. Estimation is based on Dennard Scaling assumption and does not include wiring effect -- as a result the estimates may be optimistic (especially below 65nm).
3.884351
4.00154
0.970714
critical_paths = [] # storage of all completed critical paths wire_src_map, dst_map = self.block.net_connections() def critical_path_pass(old_critical_path, first_wire): if isinstance(first_wire, (Input, Const, Register)): critical_paths.append((first_wire, old_critical_path)) return if len(critical_paths) >= cp_limit: raise self._TooManyCPsError() source = wire_src_map[first_wire] critical_path = [source] critical_path.extend(old_critical_path) arg_max_time = max(self.timing_map[arg_wire] for arg_wire in source.args) for arg_wire in source.args: # if the time for both items are the max, both will be on a critical path if self.timing_map[arg_wire] == arg_max_time: critical_path_pass(critical_path, arg_wire) max_time = self.max_length() try: for wire_pair in self.timing_map.items(): if wire_pair[1] == max_time: critical_path_pass([], wire_pair[0]) except self._TooManyCPsError: print("Critical path count limit reached") if print_cp: self.print_critical_paths(critical_paths) return critical_paths
def critical_path(self, print_cp=True, cp_limit=100)
Takes a timing map and returns the critical paths of the system. :param print_cp: Whether to print the critical path to the terminal after calculation :return: a list containing tuples with the 'first' wire as the first value and the critical paths (which themselves are lists of nets) as the second
3.881574
3.680751
1.05456
line_indent = " " * 2 # print the critical path for cp_with_num in enumerate(critical_paths): print("Critical path", cp_with_num[0], ":") print(line_indent, "The first wire is:", cp_with_num[1][0]) for net in cp_with_num[1][1]: print(line_indent, (net)) print()
def print_critical_paths(critical_paths)
Prints the results of the critical path length analysis. Done by default by the `timing_critical_path()` function.
4.749564
4.937645
0.961909
return self._request(endpoint, 'post', data, **kwargs)
def _post(self, endpoint, data, **kwargs)
Method to perform POST request on the API. :param endpoint: Endpoint of the API. :param data: POST DATA for the request. :param kwargs: Other keyword arguments for requests. :return: Response of the POST request.
5.065988
8.362062
0.60583
final_url = self.url + endpoint if not self._is_authenticated: raise LoginRequired rq = self.session if method == 'get': request = rq.get(final_url, **kwargs) else: request = rq.post(final_url, data, **kwargs) request.raise_for_status() request.encoding = 'utf_8' if len(request.text) == 0: data = json.loads('{}') else: try: data = json.loads(request.text) except ValueError: data = request.text return data
def _request(self, endpoint, method, data=None, **kwargs)
Method to hanle both GET and POST requests. :param endpoint: Endpoint of the API. :param method: Method of HTTP request. :param data: POST DATA for the request. :param kwargs: Other keyword arguments. :return: Response for the request.
2.717229
2.820813
0.963278
self.session = requests.Session() login = self.session.post(self.url+'login', data={'username': username, 'password': password}) if login.text == 'Ok.': self._is_authenticated = True else: return login.text
def login(self, username='admin', password='admin')
Method to authenticate the qBittorrent Client. Declares a class attribute named ``session`` which stores the authenticated session if the login is correct. Else, shows the login error. :param username: Username. :param password: Password. :return: Response to login request to the API.
3.341174
3.323141
1.005426
params = {} for name, value in filters.items(): # make sure that old 'status' argument still works name = 'filter' if name == 'status' else name params[name] = value return self._get('query/torrents', params=params)
def torrents(self, **filters)
Returns a list of torrents matching the supplied filters. :param filter: Current status of the torrents. :param category: Fetch all torrents with the supplied label. :param sort: Sort torrents by. :param reverse: Enable reverse sorting. :param limit: Limit the number of torrents returned. :param offset: Set offset (if less than 0, offset from end). :return: list() of torrent with matching filter.
5.774283
6.496906
0.888774
prefs = self._get('query/preferences') class Proxy(Client): def __init__(self, url, prefs, auth, session): super(Proxy, self).__init__(url) self.prefs = prefs self._is_authenticated = auth self.session = session def __getitem__(self, key): return self.prefs[key] def __setitem__(self, key, value): kwargs = {key: value} return self.set_preferences(**kwargs) def __call__(self): return self.prefs return Proxy(self.url, prefs, self._is_authenticated, self.session)
def preferences(self)
Get the current qBittorrent preferences. Can also be used to assign individual preferences. For setting multiple preferences at once, see ``set_preferences`` method. Note: Even if this is a ``property``, to fetch the current preferences dict, you are required to call it like a bound method. Wrong:: qb.preferences Right:: qb.preferences()
3.160233
3.401531
0.929062
# old:new format old_arg_map = {'save_path': 'savepath'} # , 'label': 'category'} # convert old option names to new option names options = kwargs.copy() for old_arg, new_arg in old_arg_map.items(): if options.get(old_arg) and not options.get(new_arg): options[new_arg] = options[old_arg] if type(link) is list: options['urls'] = "\n".join(link) else: options['urls'] = link # workaround to send multipart/formdata request # http://stackoverflow.com/a/23131823/4726598 dummy_file = {'_dummy': (None, '_dummy')} return self._post('command/download', data=options, files=dummy_file)
def download_from_link(self, link, **kwargs)
Download torrent using a link. :param link: URL Link or list of. :param savepath: Path to download the torrent. :param category: Label or Category of the torrent(s). :return: Empty JSON data.
4.561086
4.286045
1.064171
if isinstance(file_buffer, list): torrent_files = {} for i, f in enumerate(file_buffer): torrent_files.update({'torrents%s' % i: f}) else: torrent_files = {'torrents': file_buffer} data = kwargs.copy() if data.get('save_path'): data.update({'savepath': data['save_path']}) return self._post('command/upload', data=data, files=torrent_files)
def download_from_file(self, file_buffer, **kwargs)
Download torrent using a file. :param file_buffer: Single file() buffer or list of. :param save_path: Path to download the torrent. :param label: Label of the torrent(s). :return: Empty JSON data.
3.380543
3.077533
1.098459
data = {'hash': infohash.lower(), 'urls': trackers} return self._post('command/addTrackers', data=data)
def add_trackers(self, infohash, trackers)
Add trackers to a torrent. :param infohash: INFO HASH of torrent. :param trackers: Trackers.
7.164737
8.711897
0.822408
if isinstance(infohash_list, list): data = {'hashes': '|'.join([h.lower() for h in infohash_list])} else: data = {'hashes': infohash_list.lower()} return data
def _process_infohash_list(infohash_list)
Method to convert the infohash_list to qBittorrent API friendly values. :param infohash_list: List of infohash.
3.041124
3.393786
0.896086
data = self._process_infohash_list(infohash_list) return self._post('command/pauseAll', data=data)
def pause_multiple(self, infohash_list)
Pause multiple torrents. :param infohash_list: Single or list() of infohashes.
5.623491
6.931944
0.811243
data = self._process_infohash_list(infohash_list) data['label'] = label return self._post('command/setLabel', data=data)
def set_label(self, infohash_list, label)
Set the label on multiple torrents. IMPORTANT: OLD API method, kept as it is to avoid breaking stuffs. :param infohash_list: Single or list() of infohashes.
4.853463
6.388049
0.759772
data = self._process_infohash_list(infohash_list) data['category'] = category return self._post('command/setCategory', data=data)
def set_category(self, infohash_list, category)
Set the category on multiple torrents. :param infohash_list: Single or list() of infohashes.
4.185725
5.455164
0.767296
data = self._process_infohash_list(infohash_list) return self._post('command/resumeAll', data=data)
def resume_multiple(self, infohash_list)
Resume multiple paused torrents. :param infohash_list: Single or list() of infohashes.
6.125003
7.419909
0.825482
data = self._process_infohash_list(infohash_list) return self._post('command/delete', data=data)
def delete(self, infohash_list)
Delete torrents. :param infohash_list: Single or list() of infohashes.
4.913164
6.474936
0.758797
data = self._process_infohash_list(infohash_list) return self._post('command/deletePerm', data=data)
def delete_permanently(self, infohash_list)
Permanently delete torrents. :param infohash_list: Single or list() of infohashes.
6.200594
7.748823
0.800198
data = self._process_infohash_list(infohash_list) return self._post('command/recheck', data=data)
def recheck(self, infohash_list)
Recheck torrents. :param infohash_list: Single or list() of infohashes.
5.568675
6.675063
0.83425
data = self._process_infohash_list(infohash_list) return self._post('command/increasePrio', data=data)
def increase_priority(self, infohash_list)
Increase priority of torrents. :param infohash_list: Single or list() of infohashes.
5.599852
7.081461
0.790776
data = self._process_infohash_list(infohash_list) return self._post('command/decreasePrio', data=data)
def decrease_priority(self, infohash_list)
Decrease priority of torrents. :param infohash_list: Single or list() of infohashes.
5.863398
7.465389
0.785411
data = self._process_infohash_list(infohash_list) return self._post('command/topPrio', data=data)
def set_max_priority(self, infohash_list)
Set torrents to maximum priority level. :param infohash_list: Single or list() of infohashes.
8.818781
11.450372
0.770174
data = self._process_infohash_list(infohash_list) return self._post('command/bottomPrio', data=data)
def set_min_priority(self, infohash_list)
Set torrents to minimum priority level. :param infohash_list: Single or list() of infohashes.
9.524901
12.344785
0.771573
if priority not in [0, 1, 2, 7]: raise ValueError("Invalid priority, refer WEB-UI docs for info.") elif not isinstance(file_id, int): raise TypeError("File ID must be an int") data = {'hash': infohash.lower(), 'id': file_id, 'priority': priority} return self._post('command/setFilePrio', data=data)
def set_file_priority(self, infohash, file_id, priority)
Set file of a torrent to a supplied priority level. :param infohash: INFO HASH of torrent. :param file_id: ID of the file to set priority. :param priority: Priority level of the file.
4.770274
5.171498
0.922416
data = self._process_infohash_list(infohash_list) return self._post('command/getTorrentsDlLimit', data=data)
def get_torrent_download_limit(self, infohash_list)
Get download speed limit of the supplied torrents. :param infohash_list: Single or list() of infohashes.
7.227606
9.077096
0.796247
data = self._process_infohash_list(infohash_list) data.update({'limit': limit}) return self._post('command/setTorrentsDlLimit', data=data)
def set_torrent_download_limit(self, infohash_list, limit)
Set download speed limit of the supplied torrents. :param infohash_list: Single or list() of infohashes. :param limit: Speed limit in bytes.
5.6535
7.230676
0.781877
data = self._process_infohash_list(infohash_list) return self._post('command/getTorrentsUpLimit', data=data)
def get_torrent_upload_limit(self, infohash_list)
Get upoload speed limit of the supplied torrents. :param infohash_list: Single or list() of infohashes.
6.712256
8.952012
0.749804
data = self._process_infohash_list(infohash_list) data.update({'limit': limit}) return self._post('command/setTorrentsUpLimit', data=data)
def set_torrent_upload_limit(self, infohash_list, limit)
Set upload speed limit of the supplied torrents. :param infohash_list: Single or list() of infohashes. :param limit: Speed limit in bytes.
5.48728
7.227536
0.759219
json_data = "json={}".format(json.dumps(kwargs)) headers = {'content-type': 'application/x-www-form-urlencoded'} return self._post('command/setPreferences', data=json_data, headers=headers)
def set_preferences(self, **kwargs)
Set preferences of qBittorrent. Read all possible preferences @ http://git.io/vEgDQ :param kwargs: set preferences in kwargs form.
3.700757
3.657296
1.011883
data = self._process_infohash_list(infohash_list) return self._post('command/toggleSequentialDownload', data=data)
def toggle_sequential_download(self, infohash_list)
Toggle sequential download in supplied torrents. :param infohash_list: Single or list() of infohashes.
4.904469
6.415916
0.764422
data = self._process_infohash_list(infohash_list) return self._post('command/toggleFirstLastPiecePrio', data=data)
def toggle_first_last_piece_priority(self, infohash_list)
Toggle first/last piece priority of supplied torrents. :param infohash_list: Single or list() of infohashes.
5.133995
6.589214
0.779151
data = self._process_infohash_list(infohash_list) data.update({'value': json.dumps(value)}) return self._post('command/setForceStart', data=data)
def force_start(self, infohash_list, value=True)
Force start selected torrents. :param infohash_list: Single or list() of infohashes. :param value: Force start value (bool)
4.763013
5.635033
0.84525
target = list(filter(lambda x: x['name'] == name, current_app.config['VUE_CONFIGURATION'])) if not target: raise ValueError('Can not find resource from configuration.') target = target[0] use_minified = (isinstance(use_minified, bool) and use_minified) or current_app.config['VUE_USE_MINIFIED'] CdnClass = LocalCDN if target['use_local'] else getattr(cdn, target['cdn'], CDN) resource_url = CdnClass(name=name, version=target.get('version', ''), use_minified=use_minified).get_resource_url() if resource_url.startswith('//') and current_app.config['VUE_CDN_FORCE_SSL']: resource_url = 'https:%s' % resource_url return resource_url
def vue_find_resource(name, use_minified=None)
Resource finding function, also available in templates. :param name: Script to find a URL for. :param use_minified': If set to True/False, use/don't use minified. If None, honors VUE_USE_MINIFIED. :return: A URL.
3.027352
3.153662
0.959948
try: time = float(time) except (ValueError, TypeError): raise ValueError("Input must be numeric") # weeks if time >= 7 * 60 * 60 * 24: weeks = math.floor(time / (7 * 60 * 60 * 24)) timestr = "{:g} weeks, ".format(weeks) + humantime(time % (7 * 60 * 60 * 24)) # days elif time >= 60 * 60 * 24: days = math.floor(time / (60 * 60 * 24)) timestr = "{:g} days, ".format(days) + humantime(time % (60 * 60 * 24)) # hours elif time >= 60 * 60: hours = math.floor(time / (60 * 60)) timestr = "{:g} hours, ".format(hours) + humantime(time % (60 * 60)) # minutes elif time >= 60: minutes = math.floor(time / 60.) timestr = "{:g} min., ".format(minutes) + humantime(time % 60) # seconds elif (time >= 1) | (time == 0): timestr = "{:g} s".format(time) # milliseconds elif time >= 1e-3: timestr = "{:g} ms".format(time * 1e3) # microseconds elif time >= 1e-6: timestr = "{:g} \u03BCs".format(time * 1e6) # nanoseconds or smaller else: timestr = "{:g} ns".format(time * 1e9) return timestr
def humantime(time)
Converts a time in seconds to a reasonable human readable time Parameters ---------- t : float The number of seconds Returns ------- time : string The human readable formatted value of the given time
1.526649
1.537309
0.993066
return len(string) - wcswidth(re.compile(r'\x1b[^m]*m').sub('', string))
def ansi_len(string)
Extra length due to any ANSI sequences in the string.
5.514968
5.040817
1.094062
return linestyle.begin + linestyle.sep.join(data) + linestyle.end
def format_line(data, linestyle)
Formats a list of elements using the given line style
8.635626
9.448091
0.914008
if isinstance(width, int): widths = [width] * n else: assert len(width) == n, "Widths and data do not match" widths = width return widths
def parse_width(width, n)
Parses an int or array of widths Parameters ---------- width : int or array_like n : int
3.998322
4.357481
0.917576
# Number of columns in the table. ncols = len(data[0]) if headers is None else len(headers) tablestyle = STYLES[style] widths = parse_width(width, ncols) # Initialize with a hr or the header tablestr = [hrule(ncols, widths, tablestyle.top)] \ if headers is None else [header(headers, width=widths, align=align, style=style)] # parse each row tablestr += [row(d, widths, format_spec, align, style) for d in data] # only add the final border if there was data in the table if len(data) > 0: tablestr += [hrule(ncols, widths, tablestyle.bottom)] # print the table out.write('\n'.join(tablestr) + '\n') out.flush()
def table(data, headers=None, format_spec=FMT, width=WIDTH, align=ALIGN, style=STYLE, out=sys.stdout)
Print a table with the given data Parameters ---------- data : array_like An (m x n) array containing the data to print (m rows of n columns) headers : list, optional A list of n strings consisting of the header of each of the n columns (Default: None) format_spec : string, optional Format specification for formatting numbers (Default: '5g') width : int or array_like, optional The width of each column in the table (Default: 11) align : string The alignment to use ('left', 'center', or 'right'). (Default: 'right') style : string or tuple, optional A formatting style. (Default: 'fancy_grid') out : writer, optional A file handle or object that has write() and flush() methods (Default: sys.stdout)
3.741008
4.028293
0.928683
tablestyle = STYLES[style] widths = parse_width(width, len(headers)) alignment = ALIGNMENTS[align] # string formatter data = map(lambda x: ('{:%s%d}' % (alignment, x[0] + ansi_len(x[1]))).format(x[1]), zip(widths, headers)) # build the formatted str headerstr = format_line(data, tablestyle.row) if add_hr: upper = hrule(len(headers), widths, tablestyle.top) lower = hrule(len(headers), widths, tablestyle.below_header) headerstr = '\n'.join([upper, headerstr, lower]) return headerstr
def header(headers, width=WIDTH, align=ALIGN, style=STYLE, add_hr=True)
Returns a formatted row of column header strings Parameters ---------- headers : list of strings A list of n strings, the column headers width : int The width of each column (Default: 11) style : string or tuple, optional A formatting style (see STYLES) Returns ------- headerstr : string A string consisting of the full header row to print
4.679575
4.866587
0.961572
tablestyle = STYLES[style] widths = parse_width(width, len(values)) assert isinstance(format_spec, string_types) | isinstance(format_spec, list), \ "format_spec must be a string or list of strings" if isinstance(format_spec, string_types): format_spec = [format_spec] * len(list(values)) # mapping function for string formatting def mapdata(val): # unpack width, datum, prec = val if isinstance(datum, string_types): return ('{:%s%i}' % (ALIGNMENTS[align], width + ansi_len(datum))).format(datum) elif isinstance(datum, Number): return ('{:%s%i.%s}' % (ALIGNMENTS[align], width, prec)).format(datum) else: raise ValueError('Elements in the values array must be strings, ints, or floats') # string formatter data = map(mapdata, zip(widths, values, format_spec)) # build the row string return format_line(data, tablestyle.row)
def row(values, width=WIDTH, format_spec=FMT, align=ALIGN, style=STYLE)
Returns a formatted row of data Parameters ---------- values : array_like An iterable array of data (numbers or strings), each value is printed in a separate column width : int The width of each column (Default: 11) format_spec : string The precision format string used to format numbers in the values array (Default: '5g') align : string The alignment to use ('left', 'center', or 'right'). (Default: 'right') style : namedtuple, optional A line formatting style Returns ------- rowstr : string A string consisting of the full row of data to print
4.174871
4.128023
1.011349
widths = parse_width(width, n) hrstr = linestyle.sep.join([('{:%s^%i}' % (linestyle.hline, width)).format('') for width in widths]) return linestyle.begin + hrstr + linestyle.end
def hrule(n=1, width=WIDTH, linestyle=LineStyle('', '─', '─', ''))
Returns a formatted string used as a border between table rows Parameters ---------- n : int The number of columns in the table width : int The width of each column (Default: 11) linestyle : tuple A LineStyle namedtuple containing the characters for (begin, hr, sep, end). (Default: ('', '─', '─', '')) Returns ------- rowstr : string A string consisting of the row border to print
9.666331
8.660334
1.116162
return hrule(n, width, linestyle=STYLES[style].top)
def top(n, width=WIDTH, style=STYLE)
Prints the top row of a table
19.987354
22.530643
0.887119
out.write(header([message], width=max(width, len(message)), style=style) + '\n') out.flush()
def banner(message, width=30, style='banner', out=sys.stdout)
Prints a banner message Parameters ---------- message : string The message to print in the banner width : int The minimum width of the banner (Default: 30) style : string A line formatting style (Default: 'banner') out : writer An object that has write() and flush() methods (Default: sys.stdout)
4.823862
6.772581
0.712263
table(df.values, list(df.columns), **kwargs)
def dataframe(df, **kwargs)
Print table with data from the given pandas DataFrame Parameters ---------- df : DataFrame A pandas DataFrame with the table to print
10.848034
13.438373
0.807243
self._query_params += str(QueryParam.ADVANCED) + str(QueryParam.ADDRESS) + address.replace(" ", "+").lower()
def set_address(self, address)
Set the address. :param address:
16.367613
18.529297
0.883337
self._query_params += str(QueryParam.MIN_LEASE) + str(min_lease)
def set_min_lease(self, min_lease)
Set the minimum lease period in months. :param min_lease: int
12.467407
12.028742
1.036468
self._query_params += str(QueryParam.DAYS_OLD) + str(added)
def set_added_since(self, added)
Set this to retrieve ads that are a given number of days old. For example to retrieve listings that have been been added a week ago: set_added_since(7) :param added: int
37.382473
19.710928
1.896535
self._query_params += str(QueryParam.MAX_LEASE) + str(max_lease)
def set_max_lease(self, max_lease)
Set the maximum lease period in months. :param max_lease: int
12.755933
12.367872
1.031377
if availability >= 5: availability = '5%2B' self._query_params += str(QueryParam.AVALIABILITY) + str(availability)
def set_availability(self, availability)
Set the maximum lease period in months. :param availability:
17.136461
21.409325
0.80042
if not isinstance(room_type, RoomType): raise DaftException("room_type should be an instance of RoomType.") self._query_params += str(QueryParam.ROOM_TYPE) + str(room_type)
def set_room_type(self, room_type)
Set the room type. :param room_type:
6.383217
6.631351
0.962582
self._query_params += str(QueryParam.KEYWORDS) + '+'.join(keywords)
def set_keywords(self, keywords)
Pass an array to filter the result by keywords. :param keywords
27.186144
31.236244
0.87034
self._area = area.replace(" ", "-").lower() if isinstance(area, str) else ','.join( map(lambda x: x.lower().replace(' ', '-'), area))
def set_area(self, area)
The area to retrieve listings from. Use an array to search multiple areas. :param area: :return:
5.225183
4.661112
1.121016
if open_viewing: self._open_viewing = open_viewing self._query_params += str(QueryParam.OPEN_VIEWING)
def set_open_viewing(self, open_viewing)
Set to True to only search for properties that have upcoming 'open for viewing' dates. :param open_viewing: :return:
5.83337
6.163843
0.946385
if not isinstance(offset, int) or offset < 0: raise DaftException("Offset should be a positive integer.") self._offset = str(offset)
def set_offset(self, offset)
The page number which is in increments of 10. The default page number is 0. :param offset: :return:
5.825535
5.704303
1.021253
if not isinstance(min_price, int): raise DaftException("Min price should be an integer.") self._min_price = str(min_price) self._price += str(QueryParam.MIN_PRICE) + self._min_price
def set_min_price(self, min_price)
The minimum price. :param min_price: :return:
5.812325
5.627678
1.03281
if not isinstance(max_price, int): raise DaftException("Max price should be an integer.") self._max_price = str(max_price) self._price += str(QueryParam.MAX_PRICE) + self._max_price
def set_max_price(self, max_price)
The maximum price. :param max_price: :return:
5.934095
5.822236
1.019213
if not isinstance(listing_type, SaleType) and not isinstance(listing_type, RentType): raise DaftException("listing_type should be an instance of SaleType or RentType.") self._listing_type = listing_type
def set_listing_type(self, listing_type)
The listings you'd like to scrape i.e houses, properties, auction, commercial or apartments. Use the SaleType or RentType enum to select the listing type. i.e set_listing_type(SaleType.PROPERTIES) :param listing_type: :return:
4.299635
3.428326
1.25415
if not isinstance(min_beds, int): raise DaftException("Minimum number of beds should be an integer.") self._min_beds = str(min_beds) self._query_params += str(QueryParam.MIN_BEDS) + self._min_beds
def set_min_beds(self, min_beds)
The minimum number of beds. :param min_beds: :return:
4.785684
4.558824
1.049763
if not isinstance(max_beds, int): raise DaftException("Maximum number of beds should be an integer.") self._max_beds = str(max_beds) self._query_params += str(QueryParam.MAX_BEDS) + self._max_beds
def set_max_beds(self, max_beds)
The maximum number of beds. :param max_beds: :return:
4.584907
4.775801
0.960029
if not isinstance(sort_by, SortType): raise DaftException("sort_by should be an instance of SortType.") self._sort_by = str(sort_by)
def set_sort_by(self, sort_by)
Use this method to sort by price, distance, upcoming viewing or date using the SortType object. :param sort_by: :return:
4.630876
4.766937
0.971457
if not isinstance(sort_order, SortOrder): raise DaftException("sort_order should be an instance of SortOrder.") self._sort_order = str(sort_order)
def set_sort_order(self, sort_order)
Use the SortOrder object to sort the listings descending or ascending. :param sort_order: :return:
4.578309
4.622444
0.990452
if not isinstance(commercial_property_type, CommercialType): raise DaftException("commercial_property_type should be an instance of CommercialType.") self._commercial_property_type = str(commercial_property_type)
def set_commercial_property_type(self, commercial_property_type)
Use the CommercialType object to set the commercial property type. :param commercial_property_type: :return:
3.875751
3.346841
1.158033
if not isinstance(commercial_min_size, int): raise DaftException("commercial_min_size should be an integer.") self._commercial_min_size = str(commercial_min_size) self._query_params += str(QueryParam.COMMERCIAL_MIN) + self._commercial_min_size
def set_commercial_min_size(self, commercial_min_size)
The minimum size in sq ft. :param commercial_min_size: :return:
4.457711
4.531115
0.9838
if not isinstance(commercial_max_size, int): raise DaftException("commercial_max_size should be an integer.") self._commercial_max_size = str(commercial_max_size) self._query_params += str(QueryParam.COMMERCIAL_MAX) + self._commercial_max_size
def set_commercial_max_size(self, commercial_max_size)
The maximum size in sq ft. :param commercial_max_size: :return:
4.533268
4.570607
0.991831
if not isinstance(student_accommodation_type, StudentAccommodationType): raise DaftException("student_accommodation_type should be an instance of StudentAccommodationType.") self._student_accommodation_type = str(student_accommodation_type)
def set_student_accommodation_type(self, student_accommodation_type)
Set the student accomodation type. :param student_accommodation_type: StudentAccomodationType
2.904191
3.193361
0.909447
self._query_params += str(QueryParam.NUM_OCCUPANTS) + str(num_occupants)
def set_num_occupants(self, num_occupants)
Set the max number of occupants living in the property for rent. :param num_occupants: int
8.768801
8.550938
1.025478
self._query_params += str(QueryParam.ROUTE_ID) + str(public_transport_route)
def set_public_transport_route(self, public_transport_route)
Set the public transport route. :param public_transport_route: TransportRoute
12.937896
17.661486
0.732549
query_add = '' for property_type in property_types: if not isinstance(property_type, PropertyType): raise DaftException("property_types should be an instance of PropertyType.") query_add += str(property_type) self._query_params += query_add
def set_property_type(self, property_types)
Set the property type for rents. :param property_types: Array of Enum PropertyType
4.825181
5.143664
0.938083
self.set_url() listings = [] request = Request(debug=self._debug) url = self.get_url() soup = request.get(url) divs = soup.find_all("div", {"class": "box"}) [listings.append(Listing(div, debug=self._debug)) for div in divs] return listings
def search(self)
The search function returns an array of Listing objects. :return: Listing object
4.216974
3.747396
1.125308
try: if self._data_from_search: return self._data_from_search.find('div', {'class': 'price-changes-sr'}).text else: return self._ad_page_content.find('div', {'class': 'price-changes-sr'}).text except Exception as e: if self._debug: logging.error( "Error getting price_change. Error message: " + e.args[0]) return
def price_change(self)
This method returns any price change. :return:
3.988734
3.898333
1.02319
upcoming_viewings = [] try: if self._data_from_search: viewings = self._data_from_search.find_all( 'div', {'class': 'smi-onview-text'}) else: viewings = [] except Exception as e: if self._debug: logging.error( "Error getting upcoming_viewings. Error message: " + e.args[0]) return for viewing in viewings: upcoming_viewings.append(viewing.text.strip()) return upcoming_viewings
def upcoming_viewings(self)
Returns an array of upcoming viewings for a property. :return:
3.87794
3.921945
0.98878
facilities = [] try: list_items = self._ad_page_content.select("#facilities li") except Exception as e: if self._debug: logging.error( "Error getting facilities. Error message: " + e.args[0]) return for li in list_items: facilities.append(li.text) return facilities
def facilities(self)
This method returns the properties facilities. :return:
5.024544
5.173619
0.971186
overviews = [] try: list_items = self._ad_page_content.select("#overview li") except Exception as e: if self._debug: logging.error( "Error getting overviews. Error message: " + e.args[0]) return for li in list_items: overviews.append(li.text) return overviews
def overviews(self)
This method returns the properties overviews. :return:
4.890062
5.024737
0.973198
features = [] try: list_items = self._ad_page_content.select("#features li") except Exception as e: if self._debug: logging.error( "Error getting features. Error message: " + e.args[0]) return for li in list_items: features.append(li.text) return features
def features(self)
This method returns the properties features. :return:
5.309292
5.239774
1.013267
try: if self._data_from_search: t = self._data_from_search.find('a').contents[0] else: t = self._ad_page_content.find( 'div', {'class': 'smi-object-header'}).find( 'h1').text.strip() except Exception as e: if self._debug: logging.error( "Error getting formalised_address. Error message: " + e.args[0]) return s = t.split('-') a = s[0].strip() if 'SALE AGREED' in a: a = a.split() a = a[3:] a = ' '.join([str(x) for x in a]) return a.lower().title().strip()
def formalised_address(self)
This method returns the formalised address. :return:
4.843636
4.781
1.013101
formalised_address = self.formalised_address if formalised_address is None: return try: address = formalised_address.split(',') except Exception as e: if self._debug: logging.error( "Error getting address_line_1. Error message: " + e.args[0]) return return address[0].strip()
def address_line_1(self)
This method returns the first line of the address. :return:
4.263002
4.046046
1.053622
try: uls = self._ad_page_content.find( "ul", {"class": "smi-gallery-list"}) except Exception as e: if self._debug: logging.error( "Error getting images. Error message: " + e.args[0]) return images = [] if uls is None: return for li in uls.find_all('li'): if li.find('img')['src']: images.append(li.find('img')['src']) return images
def images(self)
This method returns the listing image. :return:
4.272308
4.162261
1.026439