docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Private method to execute command. Args: command(Command): The defined command. data(dict): The uri variable and body. uppack(bool): If unpack value from result. Returns: The unwrapped value field in the json response.
def _execute(self, command, data=None, unpack=True): if not data: data = {} if self.session_id is not None: data.setdefault('session_id', self.session_id) data = self._wrap_el(data) res = self.remote_invoker.execute(command, data) ret = WebDriverResult.from_object(res) ret.raise_for_status() ret.value = self._unwrap_el(ret.value) if not unpack: return ret return ret.value
760,666
Convert {'Element': 1234} to WebElement Object Args: value(str|list|dict): The value field in the json response. Returns: The unwrapped value.
def _unwrap_el(self, value): if isinstance(value, dict) and 'ELEMENT' in value: element_id = value.get('ELEMENT') return WebElement(element_id, self) elif isinstance(value, list) and not isinstance(value, str): return [self._unwrap_el(item) for item in value] else: return value
760,667
Convert WebElement Object to {'Element': 1234} Args: value(str|list|dict): The local value. Returns: The wrapped value.
def _wrap_el(self, value): if isinstance(value, dict): return {k: self._wrap_el(v) for k, v in value.items()} elif isinstance(value, WebElement): return {'ELEMENT': value.element_id} elif isinstance(value, list) and not isinstance(value, str): return [self._wrap_el(item) for item in value] else: return value
760,668
Switch to the given window. Support: Web(WebView) Args: window_name(str): The window to change focus to. Returns: WebDriver Object.
def switch_to_window(self, window_name): data = { 'name': window_name } self._execute(Command.SWITCH_TO_WINDOW, data)
760,670
Sets the width and height of the current window. Support: Web(WebView) Args: width(int): the width in pixels. height(int): the height in pixels. window_handle(str): Identifier of window_handle, default to 'current'. Returns: WebDriver Object.
def set_window_size(self, width, height, window_handle='current'): self._execute(Command.SET_WINDOW_SIZE, { 'width': int(width), 'height': int(height), 'window_handle': window_handle})
760,671
Sets the x,y position of the current window. Support: Web(WebView) Args: x(int): the x-coordinate in pixels. y(int): the y-coordinate in pixels. window_handle(str): Identifier of window_handle, default to 'current'. Returns: WebDriver Object.
def set_window_position(self, x, y, window_handle='current'): self._execute(Command.SET_WINDOW_POSITION, { 'x': int(x), 'y': int(y), 'window_handle': window_handle})
760,672
Execute JavaScript Synchronously in current context. Support: Web(WebView) Args: script: The JavaScript to execute. *args: Arguments for your JavaScript. Returns: Returns the return value of the function.
def execute_script(self, script, *args): return self._execute(Command.EXECUTE_SCRIPT, { 'script': script, 'args': list(args)})
760,676
Execute JavaScript Asynchronously in current context. Support: Web(WebView) Args: script: The JavaScript to execute. *args: Arguments for your JavaScript. Returns: Returns the return value of the function.
def execute_async_script(self, script, *args): return self._execute(Command.EXECUTE_ASYNC_SCRIPT, { 'script': script, 'args': list(args)})
760,677
Set a cookie. Support: Web(WebView) Args: cookie_dict: A dictionary contain keys: "name", "value", ["path"], ["domain"], ["secure"], ["httpOnly"], ["expiry"]. Returns: WebElement Object.
def add_cookie(self, cookie_dict): if not isinstance(cookie_dict, dict): raise TypeError('Type of the cookie must be a dict.') if not cookie_dict.get( 'name', None ) or not cookie_dict.get( 'value', None): raise KeyError('Missing required keys, \'name\' and \'value\' must be provided.') self._execute(Command.ADD_COOKIE, {'cookie': cookie_dict})
760,678
Save the screenshot to local. Support: Android iOS Web(WebView) Args: filename(str): The path to save the image. quietly(bool): If True, omit the IOError when failed to save the image. Returns: WebElement Object. Raises: WebDriverException. IOError.
def save_screenshot(self, filename, quietly = False): imgData = self.take_screenshot() try: with open(filename, "wb") as f: f.write(b64decode(imgData.encode('ascii'))) except IOError as err: if not quietly: raise err
760,679
Find an element in the current context. Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(str): The value of the location strategy. Returns: WebElement Object. Raises: WebDriverException.
def element(self, using, value): return self._execute(Command.FIND_ELEMENT, { 'using': using, 'value': value })
760,680
Check if an element in the current context. Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(str): The value of the location strategy. Returns: Return True if the element does exists and return False otherwise. Raises: WebDriverException.
def element_if_exists(self, using, value): try: self._execute(Command.FIND_ELEMENT, { 'using': using, 'value': value }) return True except: return False
760,681
Check if an element in the current context. Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(str): The value of the location strategy. Returns: Return Element if the element does exists and return None otherwise. Raises: WebDriverException.
def element_or_none(self, using, value): try: return self._execute(Command.FIND_ELEMENT, { 'using': using, 'value': value }) except: return None
760,682
Find elements in the current context. Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(str): The value of the location strategy. Returns: Return a List<Element | None>, if no element matched, the list is empty. Raises: WebDriverException.
def elements(self, using, value): return self._execute(Command.FIND_ELEMENTS, { 'using': using, 'value': value })
760,683
Wait for driver till satisfy the given condition Support: Android iOS Web(WebView) Args: timeout(int): How long we should be retrying stuff. interval(int): How long between retries. asserter(callable): The asserter func to determine the result. Returns: Return the driver. Raises: WebDriverException.
def wait_for( self, timeout=10000, interval=1000, asserter=lambda x: x): if not callable(asserter): raise TypeError('Asserter must be callable.') @retry( retry_on_exception=lambda ex: isinstance(ex, WebDriverException), stop_max_delay=timeout, wait_fixed=interval ) def _wait_for(driver): asserter(driver) return driver return _wait_for(self)
760,684
The factory method to create WebDriverResult from JSON Object. Args: obj(dict): The JSON Object returned by server.
def from_object(cls, obj): return cls( obj.get('sessionId', None), obj.get('status', 0), obj.get('value', None) )
760,687
Convert value to a list of key strokes >>> value_to_key_strokes(123) ['123'] >>> value_to_key_strokes('123') ['123'] >>> value_to_key_strokes([1, 2, 3]) ['123'] >>> value_to_key_strokes(['1', '2', '3']) ['123'] Args: value(int|str|list) Returns: A list of string.
def value_to_key_strokes(value): result = '' if isinstance(value, Integral): value = str(value) for v in value: if isinstance(v, Keys): result += v.value elif isinstance(v, Integral): result += str(v) else: result += v return [result]
760,691
Convert value to a list of key strokes >>> value_to_single_key_strokes(123) ['1', '2', '3'] >>> value_to_single_key_strokes('123') ['1', '2', '3'] >>> value_to_single_key_strokes([1, 2, 3]) ['1', '2', '3'] >>> value_to_single_key_strokes(['1', '2', '3']) ['1', '2', '3'] Args: value(int|str|list) Returns: A list of string.
def value_to_single_key_strokes(value): result = [] if isinstance(value, Integral): value = str(value) for v in value: if isinstance(v, Keys): result.append(v.value) elif isinstance(v, Integral): result.append(str(v)) else: result.append(v) return result
760,692
format a string by a map Args: format_string(str): A format string mapping(dict): A map to format the string Returns: A formatted string. Raises: KeyError: if key is not provided by the given map.
def format_map(self, format_string, mapping): return self.vformat(format_string, args=None, kwargs=mapping)
760,695
Find name of exception by WebDriver defined error code. Args: code(str): Error code defined in protocol. Returns: The error name defined in protocol.
def find_exception_by_code(code): errorName = None for error in WebDriverError: if error.value.code == code: errorName = error break return errorName
760,696
Initialize the WebElement Args: element_id(str): The UDID returned by remote servers. driver(WebDriver): The WebDriver Object.
def __init__(self, element_id, driver): self.element_id = str(element_id) self._driver = driver
760,702
Private method to execute command with data. Args: command(Command): The defined command. data(dict): The uri variable and body. Returns: The unwrapped value field in the json response.
def _execute(self, command, data=None, unpack=True): if not data: data = {} data.setdefault('element_id', self.element_id) return self._driver._execute(command, data, unpack)
760,704
find an element in the current element. Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(str): The value of the location strategy. Returns: WebElement Object. Raises: WebDriverException.
def element(self, using, value): return self._execute(Command.FIND_CHILD_ELEMENT, { 'using': using, 'value': value })
760,705
Check if an element in the current element. Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(str): The value of the location strategy. Returns: Return Element if the element does exists and return None otherwise. Raises: WebDriverException.
def element_or_none(self, using, value): try: return self._execute(Command.FIND_CHILD_ELEMENT, { 'using': using, 'value': value }) except: return None
760,706
find elements in the current element. Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(str): The value of the location strategy. Returns: Return a List<Element | None>, if no element matched, the list is empty. Raises: WebDriverException.
def elements(self, using, value): return self._execute(Command.FIND_CHILD_ELEMENTS, { 'using': using, 'value': value })
760,707
Deprecated use element.touch('drag', { toX, toY, duration(s) }) instead. Move the mouse by an offset of the specificed element. Support: Android Args: x(float): X offset to move to, relative to the top-left corner of the element. y(float): Y offset to move to, relative to the top-left corner of the element. Returns: WebElement object.
def move_to(self, x=0, y=0): self._driver.move_to(self, x, y)
760,708
Deprecated use touch('drag', { fromX, fromY, toX, toY, duration(s) }) instead. Flick on the touch screen using finger motion events. This flickcommand starts at a particulat screen location. Support: iOS Args: x(float}: The x offset in pixels to flick by. y(float): The y offset in pixels to flick by. speed(float) The speed in pixels per seconds. Returns: WebElement object.
def flick(self, x, y, speed): self._driver.flick(self, x, y, speed)
760,709
Apply touch actions on devices. Such as, tap/doubleTap/press/pinch/rotate/drag. See more on https://github.com/alibaba/macaca/issues/366. Support: Android iOS Args: name(str): Name of the action args(dict): Arguments of the action Returns: WebDriver Object. Raises: WebDriverException.
def touch(self, name, args=None): if isinstance(name, list) and not isinstance(name, str): for obj in name: obj['element'] = self.element_id actions = name elif isinstance(name, str): if not args: args = {} args['type'] = name args['element'] = self.element_id actions = [args] else: raise TypeError('Invalid parameters.') self._driver._execute(Command.PERFORM_ACTIONS, { 'actions': actions })
760,710
Assert whether the target is displayed Args: target(WebElement): WebElement Object. Returns: Return True if the element is displayed or return False otherwise.
def is_displayed(target): is_displayed = getattr(target, 'is_displayed', None) if not is_displayed or not callable(is_displayed): raise TypeError('Target has no attribute \'is_displayed\' or not callable') if not is_displayed(): raise WebDriverException('element not visible')
760,711
Load a data file and return it as a list of lines. Parameters: filename: The name of the file (no directories included). encoding: The file encoding. Defaults to utf-8.
def load_data_file(filename, encoding='utf-8'): data = pkgutil.get_data(PACKAGE_NAME, os.path.join(DATA_DIR, filename)) return data.decode(encoding).splitlines()
760,825
Generator to access evenly sized sub-cells in a 2d array Args: shape (tuple): number of sub-cells in y,x e.g. (10,15) d01 (tuple, optional): cell size in y and x p01 (tuple, optional): position of top left edge Returns: int: 1st index int: 2nd index slice: first dimension slice: 1st dimension
def subCell2DSlices(arr, shape, d01=None, p01=None): if p01 is not None: yinit, xinit = p01 else: xinit, yinit = 0, 0 x, y = xinit, yinit g0, g1 = shape s0, s1 = arr.shape[:2] if d01 is not None: d0, d1 = d01 else: d0, d1 = s0 / g0, s1 / g1 y1 = d0 + yinit for i in range(g0): for j in range(g1): x1 = x + d1 yield (i, j, slice(max(0, _rint(y)), max(0, _rint(y1))), slice(max(0, _rint(x)), max(0, _rint(x1)))) x = x1 y = y1 y1 = y + d0 x = xinit
761,427
Return array where every cell is the output of a given cell function Args: fn (function): ...to be executed on all sub-arrays Returns: array: value of every cell equals result of fn(sub-array) Example: mx = subCell2DFnArray(myArray, np.max, (10,6) ) - -> here mx is a 2d array containing all cell maxima
def subCell2DFnArray(arr, fn, shape, dtype=None, **kwargs): sh = list(arr.shape) sh[:2] = shape out = np.empty(sh, dtype=dtype) for i, j, c in subCell2DGenerator(arr, shape, **kwargs): out[i, j] = fn(c) return out
761,429
Parse a named VHDL file Args: fname(str): Name of file to parse Returns: Parsed objects.
def parse_vhdl_file(fname): with open(fname, 'rt') as fh: text = fh.read() return parse_vhdl(text)
761,646
Parse a text buffer of VHDL code Args: text(str): Source code to parse Returns: Parsed objects.
def parse_vhdl(text): lex = VhdlLexer name = None kind = None saved_type = None end_param_group = False cur_package = None metacomments = [] parameters = [] param_items = [] generics = [] ports = [] sections = [] port_param_index = 0 last_item = None array_range_start_pos = 0 objects = [] for pos, action, groups in lex.run(text): if action == 'metacomment': realigned = re.sub(r'^#+', lambda m: ' ' * len(m.group(0)), groups[0]) if last_item is None: metacomments.append(realigned) else: last_item.desc = realigned if action == 'section_meta': sections.append((port_param_index, groups[0])) elif action == 'function': kind = 'function' name = groups[0] param_items = [] parameters = [] elif action == 'procedure': kind = 'procedure' name = groups[0] param_items = [] parameters = [] elif action == 'param': if end_param_group: # Complete previous parameters for i in param_items: parameters.append(i) param_items = [] end_param_group = False param_items.append(VhdlParameter(groups[1])) elif action == 'param_type': mode, ptype = groups if mode is not None: mode = mode.strip() for i in param_items: # Set mode and type for all pending parameters i.mode = mode i.data_type = ptype end_param_group = True elif action == 'param_default': for i in param_items: i.default_value = groups[0] elif action == 'end_subprogram': # Complete last parameters for i in param_items: parameters.append(i) if kind == 'function': vobj = VhdlFunction(name, cur_package, parameters, groups[0], metacomments) else: vobj = VhdlProcedure(name, cur_package, parameters, metacomments) objects.append(vobj) metacomments = [] parameters = [] param_items = [] kind = None name = None elif action == 'component': kind = 'component' name = groups[0] generics = [] ports = [] param_items = [] sections = [] port_param_index = 0 elif action == 'generic_param': param_items.append(groups[0]) elif action == 'generic_param_type': ptype = groups[0] for i in param_items: generics.append(VhdlParameter(i, 'in', ptype)) param_items = [] last_item = generics[-1] elif action == 'port_param': param_items.append(groups[0]) port_param_index += 1 elif action == 'port_param_type': mode, ptype = groups for i in param_items: ports.append(VhdlParameter(i, mode, ptype)) param_items = [] last_item = ports[-1] elif action == 'port_array_param_type': mode, ptype = groups array_range_start_pos = pos[1] elif action == 'array_range_end': arange = text[array_range_start_pos:pos[0]+1] for i in param_items: ports.append(VhdlParameter(i, mode, ptype + arange)) param_items = [] last_item = ports[-1] elif action == 'end_component': vobj = VhdlComponent(name, cur_package, ports, generics, dict(sections), metacomments) objects.append(vobj) last_item = None metacomments = [] elif action == 'package': objects.append(VhdlPackage(groups[0])) cur_package = groups[0] kind = None name = None elif action == 'type': saved_type = groups[0] elif action in ('array_type', 'file_type', 'access_type', 'record_type', 'range_type', 'enum_type', 'incomplete_type'): vobj = VhdlType(saved_type, cur_package, action, metacomments) objects.append(vobj) kind = None name = None metacomments = [] elif action == 'subtype': vobj = VhdlSubtype(groups[0], cur_package, groups[1], metacomments) objects.append(vobj) kind = None name = None metacomments = [] elif action == 'constant': vobj = VhdlConstant(groups[0], cur_package, groups[1], metacomments) objects.append(vobj) kind = None name = None metacomments = [] return objects
761,647
Generate a canonical prototype string Args: vo (VhdlFunction, VhdlProcedure): Subprogram object Returns: Prototype string.
def subprogram_prototype(vo): plist = '; '.join(str(p) for p in vo.parameters) if isinstance(vo, VhdlFunction): if len(vo.parameters) > 0: proto = 'function {}({}) return {};'.format(vo.name, plist, vo.return_type) else: proto = 'function {} return {};'.format(vo.name, vo.return_type) else: # procedure proto = 'procedure {}({});'.format(vo.name, plist) return proto
761,648
Generate a signature string Args: vo (VhdlFunction, VhdlProcedure): Subprogram object Returns: Signature string.
def subprogram_signature(vo, fullname=None): if fullname is None: fullname = vo.name if isinstance(vo, VhdlFunction): plist = ','.join(p.data_type for p in vo.parameters) sig = '{}[{} return {}]'.format(fullname, plist, vo.return_type) else: # procedure plist = ','.join(p.data_type for p in vo.parameters) sig = '{}[{}]'.format(fullname, plist) return sig
761,649
Extract object declarations from a text buffer Args: text (str): Source code to parse type_filter (class, optional): Object class to filter results Returns: List of parsed objects.
def extract_objects_from_source(self, text, type_filter=None): objects = parse_vhdl(text) self._register_array_types(objects) if type_filter: objects = [o for o in objects if isinstance(o, type_filter)] return objects
761,659
Check if a type is a known array type Args: data_type (str): Name of type to check Returns: True if ``data_type`` is a known array type.
def is_array(self, data_type): # Split off any brackets data_type = data_type.split('[')[0].strip() return data_type.lower() in self.array_types
761,660
Load file of previously extracted data types Args: fname (str): Name of file to load array database from
def load_array_types(self, fname): type_defs = '' with open(fname, 'rt') as fh: type_defs = fh.read() try: type_defs = ast.literal_eval(type_defs) except SyntaxError: type_defs = {} self._add_array_types(type_defs)
761,661
Save array type registry to a file Args: fname (str): Name of file to save array database to
def save_array_types(self, fname): type_defs = {'arrays': sorted(list(self.array_types))} with open(fname, 'wt') as fh: pprint(type_defs, stream=fh)
761,662
Add array type definitions to internal registry Args: objects (list of VhdlType or VhdlSubtype): Array types to track
def _register_array_types(self, objects): # Add all array types directly types = [o for o in objects if isinstance(o, VhdlType) and o.type_of == 'array_type'] for t in types: self.array_types.add(t.name) subtypes = {o.name:o.base_type for o in objects if isinstance(o, VhdlSubtype)} # Find all subtypes of an array type for k,v in subtypes.iteritems(): while v in subtypes: # Follow subtypes of subtypes v = subtypes[v] if v in self.array_types: self.array_types.add(k)
761,663
Add array type definitions from a file list to internal registry Args: source_files (list of str): Files to parse for array definitions
def register_array_types_from_sources(self, source_files): for fname in source_files: if is_vhdl(fname): self._register_array_types(self.extract_objects(fname))
761,664
Create a new lexer Args: tokens (dict(match rules)): Hierarchical dict of states with a list of regex patterns and transitions flags (int): Optional regex flags
def __init__(self, tokens, flags=re.MULTILINE): self.tokens = {} # Pre-process the state definitions for state, patterns in tokens.iteritems(): full_patterns = [] for p in patterns: pat = re.compile(p[0], flags) action = p[1] new_state = p[2] if len(p) >= 3 else None # Convert pops into an integer if new_state and new_state.startswith('#pop'): try: new_state = -int(new_state.split(':')[1]) except IndexError, ValueError: new_state = -1 full_patterns.append((pat, action, new_state)) self.tokens[state] = full_patterns
761,665
Run lexer rules against a source text Args: text (str): Text to apply lexer to Yields: A sequence of lexer matches.
def run(self, text): stack = ['root'] pos = 0 patterns = self.tokens[stack[-1]] while True: for pat, action, new_state in patterns: m = pat.match(text, pos) if m: if action: #print('## MATCH: {} -> {}'.format(m.group(), action)) yield (pos, m.end()-1), action, m.groups() pos = m.end() if new_state: if isinstance(new_state, int): # Pop states del stack[new_state:] else: stack.append(new_state) #print('## CHANGE STATE:', pos, new_state, stack) patterns = self.tokens[stack[-1]] break else: try: if text[pos] == '\n': pos += 1 continue pos += 1 except IndexError: break
761,666
Parse a named Verilog file Args: fname (str): File to parse. Returns: List of parsed objects.
def parse_verilog_file(fname): with open(fname, 'rt') as fh: text = fh.read() return parse_verilog(text)
761,675
Parse a text buffer of Verilog code Args: text (str): Source code to parse Returns: List of parsed objects.
def parse_verilog(text): lex = VerilogLexer name = None kind = None saved_type = None mode = 'input' ptype = 'wire' metacomments = [] parameters = [] param_items = [] generics = [] ports = collections.OrderedDict() sections = [] port_param_index = 0 last_item = None array_range_start_pos = 0 objects = [] for pos, action, groups in lex.run(text): if action == 'metacomment': if last_item is None: metacomments.append(groups[0]) else: last_item.desc = groups[0] if action == 'section_meta': sections.append((port_param_index, groups[0])) elif action == 'module': kind = 'module' name = groups[0] generics = [] ports = collections.OrderedDict() param_items = [] sections = [] port_param_index = 0 elif action == 'parameter_start': net_type, vec_range = groups new_ptype = '' if net_type is not None: new_ptype += net_type if vec_range is not None: new_ptype += ' ' + vec_range ptype = new_ptype elif action == 'param_item': generics.append(VerilogParameter(groups[0], 'in', ptype)) elif action == 'module_port_start': new_mode, net_type, signed, vec_range = groups new_ptype = '' if net_type is not None: new_ptype += net_type if signed is not None: new_ptype += ' ' + signed if vec_range is not None: new_ptype += ' ' + vec_range # Complete pending items for i in param_items: ports[i] = VerilogParameter(i, mode, ptype) param_items = [] if len(ports) > 0: last_item = next(reversed(ports)) # Start with new mode mode = new_mode ptype = new_ptype elif action == 'port_param': ident = groups[0] param_items.append(ident) port_param_index += 1 elif action == 'end_module': # Finish any pending ports for i in param_items: ports[i] = VerilogParameter(i, mode, ptype) vobj = VerilogModule(name, ports.values(), generics, dict(sections), metacomments) objects.append(vobj) last_item = None metacomments = [] return objects
761,676
Extract objects from a source file Args: fname(str): Name of file to read from type_filter (class, optional): Object class to filter results Returns: List of objects extracted from the file.
def extract_objects(self, fname, type_filter=None): objects = [] if fname in self.object_cache: objects = self.object_cache[fname] else: with io.open(fname, 'rt', encoding='utf-8') as fh: text = fh.read() objects = parse_verilog(text) self.object_cache[fname] = objects if type_filter: objects = [o for o in objects if isinstance(o, type_filter)] return objects
761,678
Extract object declarations from a text buffer Args: text (str): Source code to parse type_filter (class, optional): Object class to filter results Returns: List of parsed objects.
def extract_objects_from_source(self, text, type_filter=None): objects = parse_verilog(text) if type_filter: objects = [o for o in objects if isinstance(o, type_filter)] return objects
761,679
Rotates the given texture by a given angle. Args: texture (texture): the texture to rotate rotation (float): the angle of rotation in degrees x_offset (float): the x component of the center of rotation (optional) y_offset (float): the y component of the center of rotation (optional) Returns: texture: A texture.
def rotate_texture(texture, rotation, x_offset=0.5, y_offset=0.5): x, y = texture x = x.copy() - x_offset y = y.copy() - y_offset angle = np.radians(rotation) x_rot = x * np.cos(angle) + y * np.sin(angle) y_rot = x * -np.sin(angle) + y * np.cos(angle) return x_rot + x_offset, y_rot + y_offset
762,010
Fits a layer into a texture by scaling each axis to (0, 1). Does not preserve aspect ratio (TODO: make this an option). Args: layer (layer): the layer to scale Returns: texture: A texture.
def fit_texture(layer): x, y = layer x = (x - np.nanmin(x)) / (np.nanmax(x) - np.nanmin(x)) y = (y - np.nanmin(y)) / (np.nanmax(y) - np.nanmin(y)) return x, y
762,011
Makes a texture from a turtle program. Args: turtle_program (str): a string representing the turtle program; see the docstring of `branching_turtle_generator` for more details turn_amount (float): amount to turn in degrees initial_angle (float): initial orientation of the turtle resolution (int): if provided, interpolation amount for visible lines Returns: texture: A texture.
def turtle_to_texture(turtle_program, turn_amount=DEFAULT_TURN, initial_angle=DEFAULT_INITIAL_ANGLE, resolution=1): generator = branching_turtle_generator( turtle_program, turn_amount, initial_angle, resolution) return texture_from_generator(generator)
762,037
Chains a transformation a given number of times. Args: sequence (str): a string or generator onto which transformations are applied transformations (dict): a dictionary mapping each char to the string that is substituted for it when the rule is applied iterations (int): how many times to repeat the transformation Yields: str: the next character in the output sequence.
def transform_multiple(sequence, transformations, iterations): for _ in range(iterations): sequence = transform_sequence(sequence, transformations) return sequence
762,042
Preview a plot in a jupyter notebook. Args: plot (list): the plot to display (list of layers) width (int): the width of the preview height (int): the height of the preview Returns: An object that renders in Jupyter as the provided plot
def show_plot(plot, width=PREVIEW_WIDTH, height=PREVIEW_HEIGHT): return SVG(data=plot_to_svg(plot, width, height))
762,051
Calculates the size of the SVG viewBox to use. Args: layers (list): the layers in the image aspect_ratio (float): the height of the output divided by the width margin (float): minimum amount of buffer to add around the image, relative to the total dimensions Returns: tuple: a 4-tuple of floats representing the viewBox according to SVG specifications ``(x, y, width, height)``.
def calculate_view_box(layers, aspect_ratio, margin=DEFAULT_VIEW_BOX_MARGIN): min_x = min(np.nanmin(x) for x, y in layers) max_x = max(np.nanmax(x) for x, y in layers) min_y = min(np.nanmin(y) for x, y in layers) max_y = max(np.nanmax(y) for x, y in layers) height = max_y - min_y width = max_x - min_x if height > width * aspect_ratio: adj_height = height * (1. + margin) adj_width = adj_height / aspect_ratio else: adj_width = width * (1. + margin) adj_height = adj_width * aspect_ratio width_buffer = (adj_width - width) / 2. height_buffer = (adj_height - height) / 2. return ( min_x - width_buffer, min_y - height_buffer, adj_width, adj_height )
762,052
Generates an SVG path from a given layer. Args: layer (layer): the layer to convert Yields: str: the next component of the path
def _layer_to_path_gen(layer): draw = False for x, y in zip(*layer): if np.isnan(x) or np.isnan(y): draw = False elif not draw: yield 'M {} {}'.format(x, y) draw = True else: yield 'L {} {}'.format(x, y)
762,053
Converts a plot (list of layers) into an SVG document. Args: plot (list): list of layers that make up the plot width (float): the width of the resulting image height (float): the height of the resulting image unit (str): the units of the resulting image if not pixels Returns: str: A stringified XML document representing the image
def plot_to_svg(plot, width, height, unit=''): flipped_plot = [(x, -y) for x, y in plot] aspect_ratio = height / width view_box = calculate_view_box(flipped_plot, aspect_ratio=aspect_ratio) view_box_str = '{} {} {} {}'.format(*view_box) stroke_thickness = STROKE_THICKNESS * (view_box[2]) svg = ET.Element('svg', attrib={ 'xmlns': 'http://www.w3.org/2000/svg', 'xmlns:inkscape': 'http://www.inkscape.org/namespaces/inkscape', 'width': '{}{}'.format(width, unit), 'height': '{}{}'.format(height, unit), 'viewBox': view_box_str}) for i, layer in enumerate(flipped_plot): group = ET.SubElement(svg, 'g', attrib={ 'inkscape:label': '{}-layer'.format(i), 'inkscape:groupmode': 'layer', }) color = PLOT_COLORS[i % len(PLOT_COLORS)] ET.SubElement(group, 'path', attrib={ 'style': 'stroke-width: {}; stroke: {};'.format(stroke_thickness, color), 'fill': 'none', 'd': layer_to_path(layer) }) try: return ET.tostring(svg, encoding='unicode') except LookupError: # Python 2.x return ET.tostring(svg)
762,054
Writes a plot SVG to a file. Args: plot (list): a list of layers to plot filename (str): the name of the file to write width (float): the width of the output SVG height (float): the height of the output SVG unit (str): the unit of the height and width
def write_plot(plot, filename, width=DEFAULT_PAGE_WIDTH, height=DEFAULT_PAGE_HEIGHT, unit=DEFAULT_PAGE_UNIT): svg = plot_to_svg(plot, width, height, unit) with open(filename, 'w') as outfile: outfile.write(svg)
762,055
Draws a layer on the given matplotlib axis. Args: ax (axis): the matplotlib axis to draw on layer (layer): the layers to plot
def draw_layer(ax, layer): ax.set_aspect('equal', 'datalim') ax.plot(*layer) ax.axis('off')
762,057
Returns values on a surface for points on a texture. Args: texture (texture): the texture to trace over the surface surface (surface): the surface to trace along Returns: an array of surface heights for each point in the texture. Line separators (i.e. values that are ``nan`` in the texture) will be ``nan`` in the output, so the output will have the same dimensions as the x/y axes in the input texture.
def map_texture_to_surface(texture, surface): texture_x, texture_y = texture surface_h, surface_w = surface.shape surface_x = np.clip( np.int32(surface_w * texture_x - 1e-9), 0, surface_w - 1) surface_y = np.clip( np.int32(surface_h * texture_y - 1e-9), 0, surface_h - 1) surface_z = surface[surface_y, surface_x] return surface_z
762,060
Returns the height of the surface when projected at the given angle. Args: surface (surface): the surface to project angle (float): the angle at which to project the surface Returns: surface: A projected surface.
def project_surface(surface, angle=DEFAULT_ANGLE): z_coef = np.sin(np.radians(angle)) y_coef = np.cos(np.radians(angle)) surface_height, surface_width = surface.shape slope = np.tile(np.linspace(0., 1., surface_height), [surface_width, 1]).T return slope * y_coef + surface * z_coef
762,062
Maps a texture onto a surface, then projects to 2D and returns a layer. Args: texture (texture): the texture to project surface (surface): the surface to project onto angle (float): the projection angle in degrees (0 = top-down, 90 = side view) Returns: layer: A layer.
def project_texture_on_surface(texture, surface, angle=DEFAULT_ANGLE): projected_surface = project_surface(surface, angle) texture_x, _ = texture texture_y = map_texture_to_surface(texture, projected_surface) return texture_x, texture_y
762,063
Removes parts of a projected surface that are not visible. Args: projected_surface (surface): the surface to use Returns: surface: A projected surface.
def _remove_hidden_parts(projected_surface): surface = np.copy(projected_surface) surface[~_make_occlusion_mask(projected_surface)] = np.nan return surface
762,064
Projects a texture onto a surface with occluded areas removed. Args: texture (texture): the texture to map to the projected surface surface (surface): the surface to project angle (float): the angle to project at, in degrees (0 = overhead, 90 = side view) Returns: layer: A layer.
def project_and_occlude_texture(texture, surface, angle=DEFAULT_ANGLE): projected_surface = project_surface(surface, angle) projected_surface = _remove_hidden_parts(projected_surface) texture_y = map_texture_to_surface(texture, projected_surface) texture_x, _ = texture return texture_x, texture_y
762,065
Makes a texture consisting of a given number of horizontal lines. Args: num_lines (int): the number of lines to draw resolution (int): the number of midpoints on each line Returns: A texture.
def make_lines_texture(num_lines=10, resolution=50): x, y = np.meshgrid( np.hstack([np.linspace(0, 1, resolution), np.nan]), np.linspace(0, 1, num_lines), ) y[np.isnan(x)] = np.nan return x.flatten(), y.flatten()
762,066
Makes a texture consisting of a grid of vertical and horizontal lines. Args: num_h_lines (int): the number of horizontal lines to draw num_v_lines (int): the number of vertical lines to draw resolution (int): the number of midpoints to draw on each line Returns: A texture.
def make_grid_texture(num_h_lines=10, num_v_lines=10, resolution=50): x_h, y_h = make_lines_texture(num_h_lines, resolution) y_v, x_v = make_lines_texture(num_v_lines, resolution) return np.concatenate([x_h, x_v]), np.concatenate([y_h, y_v])
762,067
Makes a texture consisting of a spiral from the origin. Args: spirals (float): the number of rotations to make ccw (bool): make spirals counter-clockwise (default is clockwise) offset (float): if non-zero, spirals start offset by this amount resolution (int): number of midpoints along the spiral Returns: A texture.
def make_spiral_texture(spirals=6.0, ccw=False, offset=0.0, resolution=1000): dist = np.sqrt(np.linspace(0., 1., resolution)) if ccw: direction = 1. else: direction = -1. angle = dist * spirals * np.pi * 2. * direction spiral_texture = ( (np.cos(angle) * dist / 2.) + 0.5, (np.sin(angle) * dist / 2.) + 0.5 ) return spiral_texture
762,068
Makes a texture consisting on a grid of hexagons. Args: grid_size (int): the number of hexagons along each dimension of the grid resolution (int): the number of midpoints along the line of each hexagon Returns: A texture.
def make_hex_texture(grid_size = 2, resolution=1): grid_x, grid_y = np.meshgrid( np.arange(grid_size), np.arange(grid_size) ) ROOT_3_OVER_2 = np.sqrt(3) / 2 ONE_HALF = 0.5 grid_x = (grid_x * np.sqrt(3) + (grid_y % 2) * ROOT_3_OVER_2).flatten() grid_y = grid_y.flatten() * 1.5 grid_points = grid_x.shape[0] x_offsets = np.interp(np.arange(4 * resolution), np.arange(4) * resolution, [ ROOT_3_OVER_2, 0., -ROOT_3_OVER_2, -ROOT_3_OVER_2, ]) y_offsets = np.interp(np.arange(4 * resolution), np.arange(4) * resolution, [ -ONE_HALF, -1., -ONE_HALF, ONE_HALF ]) tmx = 4 * resolution x_t = np.tile(grid_x, (tmx, 1)) + x_offsets.reshape((tmx, 1)) y_t = np.tile(grid_y, (tmx, 1)) + y_offsets.reshape((tmx, 1)) x_t = np.vstack([x_t, np.tile(np.nan, (1, grid_x.size))]) y_t = np.vstack([y_t, np.tile(np.nan, (1, grid_y.size))]) return fit_texture((x_t.flatten('F'), y_t.flatten('F')))
762,069
Makes a surface by generating random noise and blurring it. Args: dims (pair): the dimensions of the surface to create blur (float): the amount of Gaussian blur to apply seed (int): a random seed to use (optional) Returns: surface: A surface.
def make_noise_surface(dims=DEFAULT_DIMS, blur=10, seed=None): if seed is not None: np.random.seed(seed) return gaussian_filter(np.random.normal(size=dims), blur)
762,081
Makes a pair of gradients to generate textures from numpy primitives. Args: dims (pair): the dimensions of the surface to create Returns: pair: A pair of surfaces.
def make_gradients(dims=DEFAULT_DIMS): return np.meshgrid( np.linspace(0.0, 1.0, dims[0]), np.linspace(0.0, 1.0, dims[1]) )
762,082
Makes a surface from the 3D sine function. Args: dims (pair): the dimensions of the surface to create offset (float): an offset applied to the function scale (float): a scale applied to the sine frequency Returns: surface: A surface.
def make_sine_surface(dims=DEFAULT_DIMS, offset=0.5, scale=1.0): gradients = (np.array(make_gradients(dims)) - offset) * scale * np.pi return np.sin(np.linalg.norm(gradients, axis=0))
762,083
Makes a surface from the product of sine functions on each axis. Args: dims (pair): the dimensions of the surface to create repeat (int): the frequency of the waves is set to ensure this many repetitions of the function Returns: surface: A surface.
def make_bubble_surface(dims=DEFAULT_DIMS, repeat=3): gradients = make_gradients(dims) return ( np.sin((gradients[0] - 0.5) * repeat * np.pi) * np.sin((gradients[1] - 0.5) * repeat * np.pi))
762,084
Solve a path using or-tools' Vehicle Routing Problem solver. Params: path_graph the PathGraph representing the problem initial_solution a solution to start with (list of indices, not including the origin) runtime_seconds how long to search before returning Returns: an ordered list of indices in the graph representing a solution.
def vrp_solver(path_graph, initial_solution=None, runtime_seconds=60): # Create the VRP routing model. The 1 means we are only looking # for a single path. routing = pywrapcp.RoutingModel(path_graph.num_nodes(), 1, path_graph.ORIGIN) # For every path node, add a disjunction so that we do not also # draw its reverse. for disjunction in path_graph.iter_disjunctions(): routing.AddDisjunction(disjunction) # Wrap the distance function so that it converts to an integer, # as or-tools requires. Values are multiplied by COST_MULTIPLIER # prior to conversion to reduce the loss of precision. COST_MULTIPLIER = 1e4 def distance(i, j): return int(path_graph.cost(i, j) * COST_MULTIPLIER) routing.SetArcCostEvaluatorOfAllVehicles(distance) start_time = time() def found_solution(): t = time() - start_time cost = routing.CostVar().Max() / COST_MULTIPLIER print('\rBest solution at {} seconds has cost {} '.format( int(t), cost), end='') routing.AddAtSolutionCallback(found_solution) # If we weren't supplied with a solution initially, construct one by taking # all of the paths in their original direction, in their original order. if not initial_solution: initial_solution = [i for i, _ in path_graph.iter_disjunctions()] # Compute the cost of the initial solution. This is the number we hope to # improve on. initial_assignment = routing.ReadAssignmentFromRoutes([initial_solution], True) # print('Initial distance:', # initial_assignment.ObjectiveValue() / COST_MULTIPLIER) # Set the parameters of the search. search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters() search_parameters.time_limit_ms = runtime_seconds * 1000 search_parameters.local_search_metaheuristic = ( routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH) # Run the optimizer and report the final distance. assignment = routing.SolveFromAssignmentWithParameters(initial_assignment, search_parameters) print() #print('Final distance:', assignment.ObjectiveValue() / COST_MULTIPLIER) # Iterate over the result to produce a list to return as the solution. solution = [] index = routing.Start(0) while not routing.IsEnd(index): index = assignment.Value(routing.NextVar(index)) node = routing.IndexToNode(index) if node != 0: # For compatibility with the greedy solution, exclude the origin. solution.append(node) return solution
762,088
Function path: Memory.setPressureNotificationsSuppressed Domain: Memory Method name: setPressureNotificationsSuppressed Parameters: Required arguments: 'suppressed' (type: boolean) -> If true, memory pressure notifications will be suppressed. No return value. Description: Enable/disable suppressing memory pressure notifications in all processes.
def Memory_setPressureNotificationsSuppressed(self, suppressed): assert isinstance(suppressed, (bool,) ), "Argument 'suppressed' must be of type '['bool']'. Received type: '%s'" % type( suppressed) subdom_funcs = self.synchronous_command( 'Memory.setPressureNotificationsSuppressed', suppressed=suppressed) return subdom_funcs
762,251
Function path: Page.addScriptToEvaluateOnLoad Domain: Page Method name: addScriptToEvaluateOnLoad WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'scriptSource' (type: string) -> No description Returns: 'identifier' (type: ScriptIdentifier) -> Identifier of the added script. Description: Deprecated, please use addScriptToEvaluateOnNewDocument instead.
def Page_addScriptToEvaluateOnLoad(self, scriptSource): assert isinstance(scriptSource, (str,) ), "Argument 'scriptSource' must be of type '['str']'. Received type: '%s'" % type( scriptSource) subdom_funcs = self.synchronous_command('Page.addScriptToEvaluateOnLoad', scriptSource=scriptSource) return subdom_funcs
762,252
Function path: Page.addScriptToEvaluateOnNewDocument Domain: Page Method name: addScriptToEvaluateOnNewDocument WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'source' (type: string) -> No description Returns: 'identifier' (type: ScriptIdentifier) -> Identifier of the added script. Description: Evaluates given script in every frame upon creation (before loading frame's scripts).
def Page_addScriptToEvaluateOnNewDocument(self, source): assert isinstance(source, (str,) ), "Argument 'source' must be of type '['str']'. Received type: '%s'" % type( source) subdom_funcs = self.synchronous_command( 'Page.addScriptToEvaluateOnNewDocument', source=source) return subdom_funcs
762,253
Function path: Page.setAutoAttachToCreatedPages Domain: Page Method name: setAutoAttachToCreatedPages WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'autoAttach' (type: boolean) -> If true, browser will open a new inspector window for every page created from this one. No return value. Description: Controls whether browser will open a new inspector window for connected pages.
def Page_setAutoAttachToCreatedPages(self, autoAttach): assert isinstance(autoAttach, (bool,) ), "Argument 'autoAttach' must be of type '['bool']'. Received type: '%s'" % type( autoAttach) subdom_funcs = self.synchronous_command('Page.setAutoAttachToCreatedPages', autoAttach=autoAttach) return subdom_funcs
762,254
Function path: Page.setAdBlockingEnabled Domain: Page Method name: setAdBlockingEnabled WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'enabled' (type: boolean) -> Whether to block ads. No return value. Description: Enable Chrome's experimental ad filter on all sites.
def Page_setAdBlockingEnabled(self, enabled): assert isinstance(enabled, (bool,) ), "Argument 'enabled' must be of type '['bool']'. Received type: '%s'" % type( enabled) subdom_funcs = self.synchronous_command('Page.setAdBlockingEnabled', enabled=enabled) return subdom_funcs
762,255
Function path: Page.navigateToHistoryEntry Domain: Page Method name: navigateToHistoryEntry WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'entryId' (type: integer) -> Unique id of the entry to navigate to. No return value. Description: Navigates current page to the given history entry.
def Page_navigateToHistoryEntry(self, entryId): assert isinstance(entryId, (int,) ), "Argument 'entryId' must be of type '['int']'. Received type: '%s'" % type( entryId) subdom_funcs = self.synchronous_command('Page.navigateToHistoryEntry', entryId=entryId) return subdom_funcs
762,256
Function path: Page.deleteCookie Domain: Page Method name: deleteCookie WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'cookieName' (type: string) -> Name of the cookie to remove. 'url' (type: string) -> URL to match cooke domain and path. No return value. Description: Deletes browser cookie with given name, domain and path.
def Page_deleteCookie(self, cookieName, url): assert isinstance(cookieName, (str,) ), "Argument 'cookieName' must be of type '['str']'. Received type: '%s'" % type( cookieName) assert isinstance(url, (str,) ), "Argument 'url' must be of type '['str']'. Received type: '%s'" % type( url) subdom_funcs = self.synchronous_command('Page.deleteCookie', cookieName= cookieName, url=url) return subdom_funcs
762,257
Function path: Page.setDocumentContent Domain: Page Method name: setDocumentContent WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'frameId' (type: FrameId) -> Frame id to set HTML for. 'html' (type: string) -> HTML content to set. No return value. Description: Sets given markup as the document's HTML.
def Page_setDocumentContent(self, frameId, html): assert isinstance(html, (str,) ), "Argument 'html' must be of type '['str']'. Received type: '%s'" % type( html) subdom_funcs = self.synchronous_command('Page.setDocumentContent', frameId=frameId, html=html) return subdom_funcs
762,260
Function path: Page.setDeviceOrientationOverride Domain: Page Method name: setDeviceOrientationOverride WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'alpha' (type: number) -> Mock alpha 'beta' (type: number) -> Mock beta 'gamma' (type: number) -> Mock gamma No return value. Description: Overrides the Device Orientation.
def Page_setDeviceOrientationOverride(self, alpha, beta, gamma): assert isinstance(alpha, (float, int) ), "Argument 'alpha' must be of type '['float', 'int']'. Received type: '%s'" % type( alpha) assert isinstance(beta, (float, int) ), "Argument 'beta' must be of type '['float', 'int']'. Received type: '%s'" % type( beta) assert isinstance(gamma, (float, int) ), "Argument 'gamma' must be of type '['float', 'int']'. Received type: '%s'" % type( gamma) subdom_funcs = self.synchronous_command('Page.setDeviceOrientationOverride', alpha=alpha, beta=beta, gamma=gamma) return subdom_funcs
762,262
Function path: Page.screencastFrameAck Domain: Page Method name: screencastFrameAck WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'sessionId' (type: integer) -> Frame number. No return value. Description: Acknowledges that a screencast frame has been received by the frontend.
def Page_screencastFrameAck(self, sessionId): assert isinstance(sessionId, (int,) ), "Argument 'sessionId' must be of type '['int']'. Received type: '%s'" % type( sessionId) subdom_funcs = self.synchronous_command('Page.screencastFrameAck', sessionId=sessionId) return subdom_funcs
762,263
Function path: Overlay.setShowPaintRects Domain: Overlay Method name: setShowPaintRects Parameters: Required arguments: 'result' (type: boolean) -> True for showing paint rectangles No return value. Description: Requests that backend shows paint rectangles
def Overlay_setShowPaintRects(self, result): assert isinstance(result, (bool,) ), "Argument 'result' must be of type '['bool']'. Received type: '%s'" % type( result) subdom_funcs = self.synchronous_command('Overlay.setShowPaintRects', result=result) return subdom_funcs
762,264
Function path: Overlay.setShowDebugBorders Domain: Overlay Method name: setShowDebugBorders Parameters: Required arguments: 'show' (type: boolean) -> True for showing debug borders No return value. Description: Requests that backend shows debug borders on layers
def Overlay_setShowDebugBorders(self, show): assert isinstance(show, (bool,) ), "Argument 'show' must be of type '['bool']'. Received type: '%s'" % type( show) subdom_funcs = self.synchronous_command('Overlay.setShowDebugBorders', show=show) return subdom_funcs
762,265
Function path: Overlay.setShowFPSCounter Domain: Overlay Method name: setShowFPSCounter Parameters: Required arguments: 'show' (type: boolean) -> True for showing the FPS counter No return value. Description: Requests that backend shows the FPS counter
def Overlay_setShowFPSCounter(self, show): assert isinstance(show, (bool,) ), "Argument 'show' must be of type '['bool']'. Received type: '%s'" % type( show) subdom_funcs = self.synchronous_command('Overlay.setShowFPSCounter', show =show) return subdom_funcs
762,266
Function path: Overlay.setShowScrollBottleneckRects Domain: Overlay Method name: setShowScrollBottleneckRects Parameters: Required arguments: 'show' (type: boolean) -> True for showing scroll bottleneck rects No return value. Description: Requests that backend shows scroll bottleneck rects
def Overlay_setShowScrollBottleneckRects(self, show): assert isinstance(show, (bool,) ), "Argument 'show' must be of type '['bool']'. Received type: '%s'" % type( show) subdom_funcs = self.synchronous_command( 'Overlay.setShowScrollBottleneckRects', show=show) return subdom_funcs
762,267
Function path: Overlay.setShowViewportSizeOnResize Domain: Overlay Method name: setShowViewportSizeOnResize Parameters: Required arguments: 'show' (type: boolean) -> Whether to paint size or not. No return value. Description: Paints viewport size upon main frame resize.
def Overlay_setShowViewportSizeOnResize(self, show): assert isinstance(show, (bool,) ), "Argument 'show' must be of type '['bool']'. Received type: '%s'" % type( show) subdom_funcs = self.synchronous_command('Overlay.setShowViewportSizeOnResize' , show=show) return subdom_funcs
762,268
Function path: Overlay.setSuspended Domain: Overlay Method name: setSuspended Parameters: Required arguments: 'suspended' (type: boolean) -> Whether overlay should be suspended and not consume any resources until resumed. No return value.
def Overlay_setSuspended(self, suspended): assert isinstance(suspended, (bool,) ), "Argument 'suspended' must be of type '['bool']'. Received type: '%s'" % type( suspended) subdom_funcs = self.synchronous_command('Overlay.setSuspended', suspended =suspended) return subdom_funcs
762,269
Function path: Emulation.setPageScaleFactor Domain: Emulation Method name: setPageScaleFactor WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'pageScaleFactor' (type: number) -> Page scale factor. No return value. Description: Sets a specified page scale factor.
def Emulation_setPageScaleFactor(self, pageScaleFactor): assert isinstance(pageScaleFactor, (float, int) ), "Argument 'pageScaleFactor' must be of type '['float', 'int']'. Received type: '%s'" % type( pageScaleFactor) subdom_funcs = self.synchronous_command('Emulation.setPageScaleFactor', pageScaleFactor=pageScaleFactor) return subdom_funcs
762,275
Function path: Emulation.setScriptExecutionDisabled Domain: Emulation Method name: setScriptExecutionDisabled WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'value' (type: boolean) -> Whether script execution should be disabled in the page. No return value. Description: Switches script execution in the page.
def Emulation_setScriptExecutionDisabled(self, value): assert isinstance(value, (bool,) ), "Argument 'value' must be of type '['bool']'. Received type: '%s'" % type( value) subdom_funcs = self.synchronous_command( 'Emulation.setScriptExecutionDisabled', value=value) return subdom_funcs
762,277
Function path: Emulation.setEmulatedMedia Domain: Emulation Method name: setEmulatedMedia Parameters: Required arguments: 'media' (type: string) -> Media type to emulate. Empty string disables the override. No return value. Description: Emulates the given media for CSS media queries.
def Emulation_setEmulatedMedia(self, media): assert isinstance(media, (str,) ), "Argument 'media' must be of type '['str']'. Received type: '%s'" % type( media) subdom_funcs = self.synchronous_command('Emulation.setEmulatedMedia', media=media) return subdom_funcs
762,278
Function path: Emulation.setCPUThrottlingRate Domain: Emulation Method name: setCPUThrottlingRate WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'rate' (type: number) -> Throttling rate as a slowdown factor (1 is no throttle, 2 is 2x slowdown, etc). No return value. Description: Enables CPU throttling to emulate slow CPUs.
def Emulation_setCPUThrottlingRate(self, rate): assert isinstance(rate, (float, int) ), "Argument 'rate' must be of type '['float', 'int']'. Received type: '%s'" % type( rate) subdom_funcs = self.synchronous_command('Emulation.setCPUThrottlingRate', rate=rate) return subdom_funcs
762,279
Function path: Emulation.setNavigatorOverrides Domain: Emulation Method name: setNavigatorOverrides WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'platform' (type: string) -> The platform navigator.platform should return. No return value. Description: Overrides value returned by the javascript navigator object.
def Emulation_setNavigatorOverrides(self, platform): assert isinstance(platform, (str,) ), "Argument 'platform' must be of type '['str']'. Received type: '%s'" % type( platform) subdom_funcs = self.synchronous_command('Emulation.setNavigatorOverrides', platform=platform) return subdom_funcs
762,281
Function path: Security.handleCertificateError Domain: Security Method name: handleCertificateError Parameters: Required arguments: 'eventId' (type: integer) -> The ID of the event. 'action' (type: CertificateErrorAction) -> The action to take on the certificate error. No return value. Description: Handles a certificate error that fired a certificateError event.
def Security_handleCertificateError(self, eventId, action): assert isinstance(eventId, (int,) ), "Argument 'eventId' must be of type '['int']'. Received type: '%s'" % type( eventId) subdom_funcs = self.synchronous_command('Security.handleCertificateError', eventId=eventId, action=action) return subdom_funcs
762,283
Function path: Security.setOverrideCertificateErrors Domain: Security Method name: setOverrideCertificateErrors Parameters: Required arguments: 'override' (type: boolean) -> If true, certificate errors will be overridden. No return value. Description: Enable/disable overriding certificate errors. If enabled, all certificate error events need to be handled by the DevTools client and should be answered with handleCertificateError commands.
def Security_setOverrideCertificateErrors(self, override): assert isinstance(override, (bool,) ), "Argument 'override' must be of type '['bool']'. Received type: '%s'" % type( override) subdom_funcs = self.synchronous_command( 'Security.setOverrideCertificateErrors', override=override) return subdom_funcs
762,284
Function path: Network.setUserAgentOverride Domain: Network Method name: setUserAgentOverride Parameters: Required arguments: 'userAgent' (type: string) -> User agent to use. No return value. Description: Allows overriding user agent with the given string.
def Network_setUserAgentOverride(self, userAgent): assert isinstance(userAgent, (str,) ), "Argument 'userAgent' must be of type '['str']'. Received type: '%s'" % type( userAgent) subdom_funcs = self.synchronous_command('Network.setUserAgentOverride', userAgent=userAgent) return subdom_funcs
762,286
Function path: Network.setBlockedURLs Domain: Network Method name: setBlockedURLs WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'urls' (type: array) -> URL patterns to block. Wildcards ('*') are allowed. No return value. Description: Blocks URLs from loading.
def Network_setBlockedURLs(self, urls): assert isinstance(urls, (list, tuple) ), "Argument 'urls' must be of type '['list', 'tuple']'. Received type: '%s'" % type( urls) subdom_funcs = self.synchronous_command('Network.setBlockedURLs', urls=urls) return subdom_funcs
762,287
Function path: Network.setCookies Domain: Network Method name: setCookies WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'cookies' (type: array) -> Cookies to be set. No return value. Description: Sets given cookies.
def Network_setCookies(self, cookies): assert isinstance(cookies, (list, tuple) ), "Argument 'cookies' must be of type '['list', 'tuple']'. Received type: '%s'" % type( cookies) subdom_funcs = self.synchronous_command('Network.setCookies', cookies=cookies ) return subdom_funcs
762,291
Function path: Network.setCacheDisabled Domain: Network Method name: setCacheDisabled Parameters: Required arguments: 'cacheDisabled' (type: boolean) -> Cache disabled state. No return value. Description: Toggles ignoring cache for each request. If <code>true</code>, cache will not be used.
def Network_setCacheDisabled(self, cacheDisabled): assert isinstance(cacheDisabled, (bool,) ), "Argument 'cacheDisabled' must be of type '['bool']'. Received type: '%s'" % type( cacheDisabled) subdom_funcs = self.synchronous_command('Network.setCacheDisabled', cacheDisabled=cacheDisabled) return subdom_funcs
762,293
Function path: Network.setBypassServiceWorker Domain: Network Method name: setBypassServiceWorker WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'bypass' (type: boolean) -> Bypass service worker and load from network. No return value. Description: Toggles ignoring of service worker for each request.
def Network_setBypassServiceWorker(self, bypass): assert isinstance(bypass, (bool,) ), "Argument 'bypass' must be of type '['bool']'. Received type: '%s'" % type( bypass) subdom_funcs = self.synchronous_command('Network.setBypassServiceWorker', bypass=bypass) return subdom_funcs
762,294