code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
error_msg = "Children were never present" if parent else "Elements were never present!" expected_condition = ec.visibility_of_all_elements_located if visible else ec.presence_of_all_elements_located return self._get(locator, expected_condition, params, timeout, error_msg, parent)
def get_present_elements(self, locator, params=None, timeout=None, visible=False, parent=None)
Get elements present in the DOM. If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise TimeoutException should the element not be found. :param locator: element identifier :param params: (optional) locator parameters :param time...
4.515566
5.487807
0.822836
return self.get_present_elements(locator, params, timeout, True)
def get_visible_elements(self, locator, params=None, timeout=None)
Get elements both present AND visible in the DOM. If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise TimeoutException should the element not be found. :param locator: locator tuple :param params: (optional) locator params :pa...
7.008379
16.015465
0.437601
return self.get_present_element(locator, params, timeout, visible, parent=parent)
def get_present_child(self, parent, locator, params=None, timeout=None, visible=False)
Get child-element present in the DOM. If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise TimeoutException should the element not be found. :param parent: parent-element :param locator: locator tuple :param params: (optional) ...
4.384452
8.976297
0.488448
return self.get_present_child(parent, locator, params, timeout, True)
def get_visible_child(self, parent, locator, params=None, timeout=None)
Get child-element both present AND visible in the DOM. If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise TimeoutException should the element not be found. :param parent: parent-element :param locator: locator tuple :param pa...
5.749858
11.765695
0.488697
return self.get_present_elements(locator, params, timeout, visible, parent=parent)
def get_present_children(self, parent, locator, params=None, timeout=None, visible=False)
Get child-elements both present in the DOM. If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise TimeoutException should the element not be found. :param parent: parent-element :param locator: locator tuple :param params: (opti...
4.670551
10.209954
0.457451
return self.get_present_children(parent, locator, params, timeout, True)
def get_visible_children(self, parent, locator, params=None, timeout=None)
Get child-elements both present AND visible in the DOM. If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise TimeoutException should the element not be found. :param parent: parent-element :param locator: locator tuple :param p...
5.856844
12.31473
0.475597
from selenium.webdriver.support.ui import WebDriverWait if not isinstance(locator, WebElement): error_msg += "\nLocator of type <{}> with selector <{}> with params <{params}>".format( *locator, params=params) locator = self.__class__.get_compliant_locato...
def _get(self, locator, expected_condition, params=None, timeout=None, error_msg="", driver=None, **kwargs)
Get elements based on locator with optional parameters. Uses selenium.webdriver.support.expected_conditions to determine the state of the element(s). :param locator: element identifier :param expected_condition: expected condition of element (ie. visible, clickable, etc) :param params:...
3.781716
3.59456
1.052066
element = selector if isinstance(element, WebElement): self.execute_script("arguments[0].scrollIntoView( true );", element) else: self.execute_script("$('{}')[0].scrollIntoView( true );".format(selector[1]))
def scroll_element_into_view(self, selector)
Scrolls an element into view. :param selector: selector of element or WebElement to scroll into view :return: None
3.026242
3.379588
0.895447
element = locator if not isinstance(element, WebElement): element = self.get_visible_element(locator, params) if use_js: self._js_hover('mouseover', element) return element actions = ActionChains(self.driver) actions.move_to_element(e...
def open_hover(self, locator, params=None, use_js=False)
Open a hover or popover. :param locator: locator tuple or WebElement instance :param params: (optional) locator parameters :param use_js: use javascript to open hover :return: element hovered
3.010317
3.283009
0.916939
try: if use_js: self._js_hover('mouseout', element) else: actions = ActionChains(self.driver) actions.move_to_element_with_offset(element, -100, -100) actions.reset_actions() except (StaleElementReferenceExc...
def close_hover(self, element, use_js=False)
Close hover by moving to a set offset "away" from the element being hovered. :param element: element that triggered the hover to open :param use_js: use javascript to close hover :return: None
2.955817
3.073513
0.961707
def _do_hover(): try: with self.hover(locator, params, alt_loc, alt_params): return func(**kwargs) except exc: return False exc = [StaleElementReferenceException] if exceptions is not None: try: ...
def perform_hover_action(self, locator, func, error_msg='', exceptions=None, params=None, alt_loc=None, alt_params=None, **kwargs)
Hovers an element and performs whatever action is specified in the supplied function. NOTE: Specified function MUST return a non-false value upon success! :param locator: locator tuple or WebElement instance :param func: action to perform while hovering :param error_msg: error message ...
4.433101
4.473377
0.990996
# Open hover element = self.open_hover(locator, params, use_js) try: yield finally: # Close hover if alt_loc: element = alt_loc if not isinstance(element, WebElement): element = self.get_visi...
def hover(self, locator, params=None, use_js=False, alt_loc=None, alt_params=None)
Context manager for hovering. Opens and closes the hover. Usage: with self.hover(locator, params): // do something with the hover :param locator: locator tuple or WebElement instance :param params: (optional) locator params :param use_js: use javasc...
3.130129
3.1206
1.003054
exp_cond = eec.invisibility_of if isinstance(locator, WebElement) else ec.invisibility_of_element_located try: self._get(locator, exp_cond, params, timeout, error_msg="Element never disappeared") except (StaleElementReferenceException, NoSuchElementException): re...
def wait_for_element_to_disappear(self, locator, params=None, timeout=None)
Waits until the element is not visible (hidden) or no longer attached to the DOM. Raises TimeoutException if element does not become invisible. :param locator: locator tuple or WebElement instance :param params: (optional) locator params :param timeout: (optional) time to wait for elem...
5.797459
6.028513
0.961673
def _do_wait(): elements = self.get_present_elements(locator, params, timeout=0) for element in elements: if not self.get_text(element): return False return elements return ActionWait(timeout).until(_do_wait, "Element text...
def wait_for_non_empty_text(self, locator, params=None, timeout=5)
Wait and get elements when they're populated with any text. :param locator: locator tuple :param params: (optional) locator params :param timeout: (optional) maximum waiting time (in seconds) (default: 5) :return: list of WebElements
6.565207
6.491766
1.011313
def _do_wait(): element = self.get_present_element(locator, params) return value in self.get_attribute(element, attribute) ActionWait(timeout).until(_do_wait, "Attribute never set!")
def wait_for_attribute(self, locator, attribute, value, params=None, timeout=5)
Waits for an element attribute to get a certain value. Note: This function re-get's the element in a loop to avoid caching or stale element issues. :Example: Wait for the class attribute to get 'board-hidden' value :param locator: locator tuple :param attribute: element at...
7.528279
8.461832
0.889675
from selenium.webdriver.support.ui import WebDriverWait WebDriverWait(self.driver, timeout).until(lambda s: s.execute_script("return jQuery.active === 0"))
def wait_for_ajax_calls_to_complete(self, timeout=5)
Waits until there are no active or pending ajax requests. Raises TimeoutException should silence not be had. :param timeout: time to wait for silence (default: 5 seconds) :return: None
2.9592
3.065099
0.96545
element = locator if not isinstance(element, WebElement): element = self.get_visible_element(locator, params) element.send_keys(path)
def upload_to_file_input(self, locator, path, params=None)
Sends in path in an <input type=file> to upload a file. The <input type=file> must be set to be visible, usually by setting the style of the element to display-block; instead of display-none or nothing at all. Uses WebElement's send_keys instead of ActionChains. :param locator: locator tuple or...
3.963726
3.75787
1.05478
ip = ip.replace('*', '1') try: socket.inet_aton(ip) return True except socket.error: # Not a valid IPv4 address pattern return False
def is_valid_ip_pattern(ip)
Check whether a string matches the outline of an IPv4 address, allowing "*" as a wildcard
3.41139
3.342574
1.020588
yield "255.255.255.255" for interface in netifaces.interfaces(): ifaddresses = netifaces.ifaddresses(interface) for family in ifaddresses: if family == netifaces.AF_INET: address_info = ifaddresses[family] for info in address_info: ...
def _find_ip4_broadcast_addresses()
Yield each IP4 broadcast address, and the all-broadcast
2.280387
2.184
1.044133
global _ip4_addresses proto = socket.AF_INET if _ip4_addresses is None: _ip4_addresses = [] # # Determine the interface for the default gateway # (if any) and, later, prioritise the INET address on # that interface. # default_gateway = netifaces....
def _find_ip4_addresses()
Find all the IP4 addresses currently bound to interfaces
2.8813
2.883123
0.999368
address = str(address or "").strip() # # If the address is an ip:port pair, split into its component parts. # Otherwise, try to determine whether we're looking at an IP # or at a port and leave the other one blank # host_or_ip, port = split_address(address) # # If the port has ...
def address(address=None)
Convert one of a number of inputs into a valid ip:port string. Elements which are not provided are filled in as follows: * IP Address: the system is asked for the set of IP addresses associated with the machine and the first one is used, preferring those matching `address` if it is a w...
4.956012
4.813648
1.029575
if not phone_number: raise ValueError('No phone number provided') if not isinstance(phone_number, str_cls): raise ValueError('Phone number is not a string') phone_number = phone_number.strip() phone_number = re.sub('[^+0-9]', '', phone_number) if not phone_number or phone_nu...
def calculate_rate(phone_number, address_country_code=None, address_exception=None)
Calculates the VAT rate based on a telephone number :param phone_number: The string phone number, in international format with leading + :param address_country_code: The user's country_code, as detected from billing_address or declared_residence. This prevents an UndefinitiveError from...
2.703961
2.37574
1.138155
leading_digit = phone_number[0] if leading_digit not in CALLING_CODE_MAPPING: return None for mapping in CALLING_CODE_MAPPING[leading_digit]: if not re.match(mapping['regex'], phone_number): continue return mapping['country_code'] return None
def _lookup_country_code(phone_number)
Accepts an international form of a phone number (+ followed by digits), and returns a two-character country code. :param phone_number: The string phone number, in international format with leading + :return: A two-character string or None if no match
2.971571
3.28405
0.90485
if isinstance(uristring, bytes): result = SplitResultBytes else: result = SplitResultUnicode return result(*result.RE.match(uristring).groups())
def urisplit(uristring)
Split a well-formed URI reference string into a tuple with five components corresponding to a URI's general structure:: <scheme>://<authority>/<path>?<query>#<fragment>
6.633548
8.575879
0.773512
scheme, authority, path, query, fragment = parts if isinstance(path, bytes): result = SplitResultBytes else: result = SplitResultUnicode return result(scheme, authority, path, query, fragment).geturi()
def uriunsplit(parts)
Combine the elements of a five-item iterable into a URI reference's string representation.
4.00005
4.124139
0.969911
scheme, authority, path, query, fragment = self # RFC 3986 5.3. Component Recomposition result = [] if scheme is not None: result.extend([scheme, self.COLON]) if authority is not None: result.extend([self.SLASH, self.SLASH, authority]) re...
def geturi(self)
Return the re-combined version of the original URI reference as a string.
2.783851
2.560419
1.087264
scheme = self.scheme if scheme is None: return default elif isinstance(scheme, bytes): return scheme.decode('ascii').lower() else: return scheme.lower()
def getscheme(self, default=None)
Return the URI scheme in canonical (lowercase) form, or `default` if the original URI reference did not contain a scheme component.
2.819006
2.60522
1.082061
# TBD: (userinfo, host, port) kwargs, default string? if default is None: default = (None, None, None) elif not isinstance(default, collections.Iterable): raise TypeError('Invalid default type') elif len(default) != 3: raise ValueError('Invali...
def getauthority(self, default=None, encoding='utf-8', errors='strict')
Return the decoded userinfo, host and port subcomponents of the URI authority as a three-item tuple.
4.550188
3.68792
1.233809
userinfo = self.userinfo if userinfo is None: return default else: return uridecode(userinfo, encoding, errors)
def getuserinfo(self, default=None, encoding='utf-8', errors='strict')
Return the decoded userinfo subcomponent of the URI authority, or `default` if the original URI reference did not contain a userinfo field.
3.674206
3.428885
1.071545
host = self.host if host is None or (not host and default is not None): return default elif host.startswith(self.LBRACKET) and host.endswith(self.RBRACKET): return _ip_literal(host[1:-1]) elif host.startswith(self.LBRACKET) or host.endswith(self.RBRACKET)...
def gethost(self, default=None, errors='strict')
Return the decoded host subcomponent of the URI authority as a string or an :mod:`ipaddress` address object, or `default` if the original URI reference did not contain a host.
3.577462
3.5367
1.011525
port = self.port if port: return int(port) else: return default
def getport(self, default=None)
Return the port subcomponent of the URI authority as an :class:`int`, or `default` if the original URI reference did not contain a port or if the port was empty.
3.984242
4.469978
0.891334
path = self.__remove_dot_segments(self.path) return uridecode(path, encoding, errors)
def getpath(self, encoding='utf-8', errors='strict')
Return the normalized decoded URI path.
8.280762
6.234049
1.328312
query = self.query if query is None: return default else: return uridecode(query, encoding, errors)
def getquery(self, default=None, encoding='utf-8', errors='strict')
Return the decoded query string, or `default` if the original URI reference did not contain a query component.
4.081377
3.579465
1.14022
dict = collections.defaultdict(list) for name, value in self.getquerylist(sep, encoding, errors): dict[name].append(value) return dict
def getquerydict(self, sep='&', encoding='utf-8', errors='strict')
Split the query component into individual `name=value` pairs separated by `sep` and return a dictionary of query variables. The dictionary keys are the unique query variable names and the values are lists of values for each name.
2.87661
2.633115
1.092474
if not self.query: return [] elif isinstance(sep, type(self.query)): qsl = self.query.split(sep) elif isinstance(sep, bytes): qsl = self.query.split(sep.decode('ascii')) else: qsl = self.query.split(sep.encode('ascii')) ite...
def getquerylist(self, sep='&', encoding='utf-8', errors='strict')
Split the query component into individual `name=value` pairs separated by `sep`, and return a list of `(name, value)` tuples.
2.496216
2.435009
1.025136
return (self.scheme is None and self.authority is None and self.path.startswith(self.SLASH))
def isabspath(self)
Return :const:`True` if this is an absolute-path reference.
6.395155
5.598602
1.142277
return (self.scheme is None and self.authority is None and not self.path.startswith(self.SLASH))
def isrelpath(self)
Return :const:`True` if this is a relative-path reference.
5.930699
5.001098
1.18588
return (self.scheme is None and self.authority is None and not self.path and self.query is None)
def issamedoc(self)
Return :const:`True` if this is a same-document reference.
8.043255
6.285754
1.279601
scheme, authority, path, query, fragment = self.RE.match(ref).groups() # RFC 3986 5.2.2. Transform References if scheme is not None and (strict or scheme != self.scheme): path = self.__remove_dot_segments(path) elif authority is not None: scheme = self.s...
def transform(self, ref, strict=False)
Transform a URI reference relative to `self` into a :class:`SplitResult` representing its target URI.
2.613153
2.562254
1.019865
if not country_code or not isinstance(country_code, str_cls) or len(country_code) != 2: raise ValueError('Invalidly formatted country code') if exception_name and not isinstance(exception_name, str_cls): raise ValueError('Exception name is not None or a string') country_code = countr...
def calculate_rate(country_code, exception_name)
Calculates the VAT rate for a customer based on their declared country and any declared exception information. :param country_code: The two-character country code where the user resides :param exception_name: The name of an exception for the country, as returned from vat_moss.decla...
3.484738
3.222893
1.081245
if not country_code or not isinstance(country_code, str_cls) or len(country_code) != 2: raise ValueError('Invalidly formatted country code') country_code = country_code.upper() return EXCEPTIONS_BY_COUNTRY.get(country_code, [])
def exceptions_by_country(country_code)
Returns a list of exception names for the given country :param country_code: The two-character country code for the user :raises: ValueError - if country_code is not two characers :return: A list of strings that are VAT exceptions for the country specified
3.351541
3.534129
0.948336
if not vat_id: return None if not isinstance(vat_id, str_cls): raise ValueError('VAT ID is not a string') if len(vat_id) < 3: raise ValueError('VAT ID must be at least three character long') # Normalize the ID for simpler regexes vat_id = re.sub('\\s+', '', vat_id) ...
def normalize(vat_id)
Accepts a VAT ID and normaizes it, getting rid of spaces, periods, dashes etc and converting it to upper case. :param vat_id: The VAT ID to check. Allows "GR" prefix for Greece, even though it should be "EL". :raises: ValueError - If the is not a string or is not in the format of t...
2.777837
2.464162
1.127295
exc = [StaleElementReferenceException] if exceptions is not None: try: exc.extend(iter(exceptions)) except TypeError: # exceptions is not iterable exc.append(exceptions) exc = tuple(exc) if not msg: msg = "Could not recover from Exception(s): {}".fo...
def handle_stale(msg='', exceptions=None)
Decorator to handle stale element reference exceptions. :param msg: Error message :param exceptions: Extra exceptions to handle :return: the result of the decorated function
2.844708
2.872655
0.990271
exc = [StaleElementReferenceException] if exceptions is not None: try: exc.extend(iter(exceptions)) except TypeError: # exceptions is not iterable exc.append(exceptions) exc = tuple(exc) if not msg: msg = "Could not recover from Exception(s): {}".fo...
def wait(msg='', exceptions=None, timeout=10)
Decorator to handle generic waiting situations. Will handle StaleElementReferenceErrors. :param msg: Error message :param exceptions: Extra exceptions to handle :param timeout: time to keep trying (default: 10 seconds) :return: the result of the decorated function
2.856896
2.884028
0.990592
if not country_code or not isinstance(country_code, str_cls): raise ValueError('Invalidly formatted country code') country_code = country_code.strip() if len(country_code) != 2: raise ValueError('Invalidly formatted country code') country_code = country_code.upper() if count...
def calculate_rate(country_code, postal_code, city)
Calculates the VAT rate that should be collected based on address information provided :param country_code: The two-character country code :param postal_code: The postal code for the user :param city: The city name for the user :raises: ValueError - If country cod...
2.555537
2.460919
1.038448
return (yield from self._get('/pods/{}'.format(uid), fields=fields))
def async_get_device(self, uid, fields='*')
Get specific device by ID.
10.623037
9.30414
1.141754
return (yield from self._get('/pods/{}/measurements'.format(uid), fields=fields))[0]
def async_get_measurements(self, uid, fields='*')
Get measurements of a device.
9.248073
8.575738
1.0784
return (yield from self._get('/pods/{}/acStates'.format(uid), limit=limit, fields=fields, offset=offset))
def async_get_ac_states(self, uid, limit=1, offset=0, fields='*')
Get log entries of a device.
5.690823
5.626525
1.011428
return ( yield from self._get('/pods/{}/acStates/{}'.format(uid, log_id), fields=fields))
def async_get_ac_state_log(self, uid, log_id, fields='*')
Get a specific log entry.
8.366721
8.097318
1.033271
if ac_state is None: ac_state = yield from self.async_get_ac_states(uid) ac_state = ac_state[0]['acState'] data = { 'currentAcState': ac_state, 'newValue': value } if assumed_state: data['reason'] = "StateCorrectionByUs...
def async_set_ac_state_property( self, uid, name, value, ac_state=None, assumed_state=False)
Set a specific device property.
3.553537
3.564626
0.996889
n_tries_left = n_tries while n_tries_left > 0: try: return bind_function(*args) except zmq.error.ZMQError as exc: _logger.warn("%s; %d tries remaining", exc, n_tries_left) n_tries_left -= 1 except OSError as exc: if exc.errno == errno....
def _bind_with_timeout(bind_function, args, n_tries=3, retry_interval_s=0.5)
Attempt to bind a socket a number of times with a short interval in between Especially on Linux, crashing out of a networkzero process can leave the sockets lingering and unable to re-bind on startup. We give it a few goes here to see if we can bind within a couple of seconds.
2.261263
2.158618
1.047551
global _beacon if _beacon is None: _logger.debug("About to start beacon with port %s", port) try: _beacon = _Beacon(port) except (OSError, socket.error) as exc: if exc.errno == errno.EADDRINUSE: _logger.warn("Beacon already active on this mach...
def _start_beacon(port=None)
Start a beacon thread within this process if no beacon is currently running on this machine. In general this is called automatically when an attempt is made to advertise or discover. It might be convenient, though, to call this function directly if you want to have a process whose only job is t...
4.142891
3.90137
1.061907
_start_beacon() address = _rpc("advertise", name, address, fail_if_exists, ttl_s) _services_advertised[name] = address return address
def advertise(name, address=None, fail_if_exists=False, ttl_s=config.ADVERT_TTL_S)
Advertise a name at an address Start to advertise service `name` at address `address`. If the address is not supplied, one is constructed and this is returned by the function. ie this is a typical use:: address = nw0.advertise("myservice") :param name: any text :param addr...
6.404926
8.365359
0.765649
_start_beacon() # # It's possible to enter a deadlock situation where the first # process fires off a discovery request and waits for the # second process to advertise. But the second process has to # connect to the rpc port of the first process' beacon and # its advertisement is queued...
def discover(name, wait_for_s=60)
Discover a service by name Look for an advert to a named service:: address = nw0.discover("myservice") :param name: any text :param wait_for_s: how many seconds to wait before giving up :returns: the address found or None
9.228097
9.562924
0.964987
_start_beacon() if exclude is None: names_to_exclude = set() else: names_to_exclude = set(exclude) all_discovered = _rpc("discover_all") return [(name, address) for (name, address) in all_discovered if name.startswith("%s%s" % (group, separator)) and na...
def discover_group(group, separator="/", exclude=None)
Produce a list of all services and their addresses in a group A group is an optional form of namespace within the discovery mechanism. If an advertised name has the form <group><sep><name> it is deemed to belong to <group>. Note that the service's name is still the full string <group><sep><name>. T...
4.314784
3.99018
1.081351
try: message = self.rpc.recv(zmq.NOBLOCK) except zmq.ZMQError as exc: if exc.errno == zmq.EAGAIN: return else: raise _logger.debug("Received command %s", message) segments = _unpack(message) action, par...
def poll_command_request(self)
If the command RPC socket has an incoming request, separate it into its action and its params and put it on the command request queue.
3.503502
2.953429
1.186249
if self._command.response is not Empty: _logger.debug("Sending response %s", self._command.response) self.rpc.send(_pack(self._command.response)) self._command = None
def poll_command_reponse(self)
If the latest request has a response, issue it as a reply to the RPC socket.
6.222618
4.622072
1.346283
_logger.info("Sending message %s to %s", message, address) if isinstance(address, list): raise core.InvalidAddressError("Multiple addresses are not allowed") return sockets._sockets.send_message_to(address, message, wait_for_reply_s)
def send_message_to(address, message=EMPTY, wait_for_reply_s=config.FOREVER)
Send a message and return the reply :param address: a nw0 address (eg from `nw0.discover`) :param message: any simple Python object, including text & tuples :param wait_for_reply_s: how many seconds to wait for a reply [default: forever] :returns: the reply returned from the address or None if...
4.243297
4.973526
0.853177
_logger.info("Waiting for message on %s for %s secs", address, wait_for_s) message = sockets._sockets.wait_for_message_from(address, wait_for_s) if message is not None and autoreply: sockets._sockets.send_reply_to(address, EMPTY) return message
def wait_for_message_from(address, wait_for_s=config.FOREVER, autoreply=False)
Wait for a message :param address: a nw0 address (eg from `nw0.advertise`) :param wait_for_s: how many seconds to wait for a message before giving up [default: forever] :param autoreply: whether to send an empty reply [default: No] :returns: the message received from another address or None if...
3.725253
3.450742
1.079551
_logger.debug("Sending reply %s to %s", reply, address) return sockets._sockets.send_reply_to(address, reply)
def send_reply_to(address, reply=EMPTY)
Reply to a message previously received :param address: a nw0 address (eg from `nw0.advertise`) :param reply: any simple Python object, including text & tuples
5.375235
7.235561
0.742891
_logger.info("Publish topic %s with data %s to %s", topic, data, address) return sockets._sockets.send_news_to(address, topic, data)
def send_news_to(address, topic, data=None)
Publish news to all subscribers :param address: a nw0 address, eg from `nw0.advertise` :param topic: any text object :param data: any simple Python object including test & tuples [default: empty]
5.132441
5.564777
0.922308
_logger.info("Listen on %s for news matching %s waiting for %s secs", address, prefix, wait_for_s) return sockets._sockets.wait_for_news_from(address, prefix, wait_for_s, is_raw)
def wait_for_news_from(address, prefix=config.EVERYTHING, wait_for_s=config.FOREVER, is_raw=False)
Wait for news whose topic starts with `prefix`. :param address: a nw0 address, eg from `nw0.discover` :param prefix: any text object [default: all messages] :param wait_for_s: how many seconds to wait before giving up [default: forever] :returns: a 2-tuple of (topic, data) or (None, None) if o...
4.189015
5.314609
0.788208
if not country_code or not isinstance(country_code, str_cls) or len(country_code) != 2: raise ValueError('Invalidly formatted country code') if not isinstance(subdivision, str_cls): raise ValueError('Subdivision is not a string') if not isinstance(city, str_cls): raise ValueE...
def calculate_rate(country_code, subdivision, city, address_country_code=None, address_exception=None)
Calculates the VAT rate from the data returned by a GeoLite2 database :param country_code: Two-character country code :param subdivision: The first subdivision name :param city: The city name :param address_country_code: The user's country_code, as detected from billi...
2.701525
2.366165
1.141731
project_file = join(getcwd(), project_file) uvproj_dic = xmltodict.parse(file(project_file), dict_constructor=dict) # Generic Target, should get from Target class ! mcu = MCU_TEMPLATE try: mcu['tool_specific'] = { # legacy device ...
def get_mcu_definition(self, project_file)
Parse project file to get mcu definition
3.745182
3.657204
1.024056
# TODO: check the extension here if it's valid IAR project or we # should at least check if syntax is correct check something IAR defines and return error if not project_file = join(getcwd(), project_file) ewp_dic = xmltodict.parse(file(project_file), dict_constructor=dict) ...
def get_mcu_definition(self, project_file)
Parse project file to get mcu definition
3.570162
3.556778
1.003763
xrates.install('money.exchange.SimpleBackend') xrates.base = base for code, value in rates.items(): xrates.setrate(code, value)
def setup_xrates(base, rates)
If using the Python money package, this will set up the xrates exchange rate data. :param base: The string currency code to use as the base :param rates: A dict with keys that are string currency codes and values that are a Decimal of the exchange rate for that currency.
9.69065
7.629563
1.270145
if currency is None and hasattr(amount, 'currency'): currency = amount.currency # Allow Money objects if not isinstance(amount, Decimal) and hasattr(amount, 'amount'): amount = amount.amount if not isinstance(currency, str_cls): raise ValueError('The currency specified is...
def format(amount, currency=None)
Formats a decimal or Money object into an unambiguous string representation for the purpose of invoices in English. :param amount: A Decimal or Money object :param currency: If the amount is a Decimal, the currency of the amount :return: A string representation of the amount i...
2.703986
2.709657
0.997907
if name is None: raise TypeError('\'name\' should not be None') for momentum in self.momenta: if momentum.name == name: return momentum raise KeyError('No such momentum named {0}'.format(name))
def get_momentum_by_name(self, name)
Gets a momentum by the given name. :param name: the momentum name. :returns: a momentum found. :raises TypeError: `name` is ``None``. :raises KeyError: failed to find a momentum named `name`.
3.320426
3.481885
0.953629
momentum = self.get_momentum_by_name(name) self.remove_momentum(momentum) return momentum
def pop_momentum_by_name(self, name)
Removes and returns a momentum by the given name. :param name: the momentum name. :returns: a momentum removed. :raises TypeError: `name` is ``None``. :raises KeyError: failed to find a momentum named `name`.
3.101189
4.479717
0.692273
momentum = self.pop_momentum_by_name(name) velocity, since, until = momentum[:3] velocity = kwargs.get('velocity', velocity) since = kwargs.get('since', since) until = kwargs.get('until', until) return self.add_momentum(velocity, since, until, name)
def update_momentum_by_name(self, name, **kwargs)
Updates a momentum by the given name. :param name: the momentum name. :param velocity: (keyword-only) a new value for `velocity`. :param since: (keyword-only) a new value for `since`. :param until: (keyword-only) a new value for `until`. :returns: a momentum updated. :...
3.402005
2.655148
1.281286
at = now_or(at) self.forget_past(at=at) return self.update_momentum_by_name(name, velocity=velocity, since=at)
def snap_momentum_by_name(self, name, velocity, at=None)
Changes the velocity of a momentum named `name`. :param name: the momentum name. :param velocity: a new velocity. :param at: the time to snap. (default: now) :returns: a momentum updated. :raises TypeError: `name` is ``None``. :raises KeyError: failed to find a momentu...
8.142241
9.996165
0.814537
value = None end_time = time.time() + self._timeout while True: value = func(*args, **kwargs) if self._debug: print("Value from func within ActionWait: {}".format(value)) if value: break time.sleep(self._po...
def until(self, func, message='', *args, **kwargs)
Continues to execute the function until successful or time runs out. :param func: function to execute :param message: message to print if time ran out :param args: arguments :param kwargs: key word arguments :return: result of function or None
3.643174
4.119457
0.884382
devices = [] all_hids = hid.find_all_hid_devices() if all_hids: for index, device in enumerate(all_hids): for device_name,spec in device_specs.items(): if device.vendor_id == spec.hid_id[0] and device.product_id == spec.hid_id[1]: devices.append(d...
def list_devices()
Return a list of the supported devices connected Returns: A list of string names of the devices supported which were found. Empty if no supported devices found
3.35705
3.63857
0.922629
# only used if the module-level functions are used global _active_device # if no device name specified, look for any matching device and choose the first if device==None: all_devices = list_devices() if len(all_devices)>0: device = all_devices[0] else: ...
def open(callback=None, button_callback=None, device=None)
Open a 3D space navigator device. Makes this device the current active device, which enables the module-level read() and close() calls. For multiple devices, use the read() and close() calls on the returned object instead, and don't use the module-level calls. Parameters: callback: If callb...
3.726197
3.43401
1.085086
if self.device==None: return "%s [disconnected]" % (self.name) else: return "%s connected to %s %s version: %s [serial: %s]" % (self.name, self.vendor_name, self.product_name, self.version_number, self.serial_number)
def describe_connection(self)
Return string representation of the device, including the connection state
4.329387
4.032523
1.073617
if self.led_usage in report: report[self.led_usage] = state report.send()
def set_led(self, state): if self.connected: reports = self.device.find_output_reports() for report in reports
Set the LED state to state (True or False)
11.099276
7.35743
1.508581
button_changed = False for name,(chan,b1,b2,flip) in self.mappings.items(): if data[0] == chan: self.dict_state[name] = flip * to_int16(data[b1], data[b2])/float(self.axis_scale) for button_index, (chan, byte, bit) in enumerate(s...
def process(self, data)
Update the state based on the incoming data This function updates the state of the DeviceSpec object, giving values for each axis [x,y,z,roll,pitch,yaw] in range [-1.0, 1.0] The state tuple is only set when all 6 DoF have been read correctly. The timestamp (in fractiona...
6.085984
5.527101
1.101117
interval_exc = "Bad interval format for {0}".format(string) interval_regex = re.compile("^(?P<value>[0-9]+)(?P<unit>[{0}])".format("".join(interval_dict.keys()))) seconds = 0 if string is None: return None while string: match = interval_regex.match(string) if match: ...
def human_to_seconds(string)
Convert internal string like 1M, 1Y3M, 3W to seconds. :type string: str :param string: Interval string like 1M, 1W, 1M3W4h2s... (s => seconds, m => minutes, h => hours, D => days, W => weeks, M => months, Y => Years). :rtype: int :return: The conversion in seconds of string.
2.97715
2.960881
1.005495
if not isinstance(uristring, bytes): uristring = uristring.encode(encoding, errors) if not isinstance(safe, bytes): safe = safe.encode('ascii') try: encoded = _encoded[safe] except KeyError: encoded = _encoded[b''][:] for i in _tointseq(safe): enc...
def uriencode(uristring, safe='', encoding='utf-8', errors='strict')
Encode a URI string or string component.
2.711482
2.735114
0.99136
if not isinstance(uristring, bytes): uristring = uristring.encode(encoding or 'ascii', errors) parts = uristring.split(b'%') result = [parts[0]] append = result.append decode = _decoded.get for s in parts[1:]: append(decode(s[:2], b'%' + s[:2])) append(s[2:]) if ...
def uridecode(uristring, encoding='utf-8', errors='strict')
Decode a URI string or string component.
2.572993
2.522541
1.020001
try: l = len(x) if l != size: raise ValueError( "{0} must be scalar or of length {1}".format( name, size)) except TypeError: # Only one item xa = np.array([x] * size) # Each item is a diff. object. else: xa = np.ar...
def _convert_to_array(x, size, name)
Check length of array or convert scalar to array. Check to see is `x` has the given length `size`. If this is true then return Numpy array equivalent of `x`. If not then raise ValueError, using `name` as an idnetification. If len(x) returns TypeError, then assume it is a scalar and create a Numpy array...
4.94903
4.456976
1.110401
return np.interp(line_wave, wave, flux, **kwargs)
def get_line_flux(line_wave, wave, flux, **kwargs)
Interpolated flux at a given wavelength (calls np.interp).
3.301115
3.091644
1.067754
from collections import defaultdict d = defaultdict(int) for i in line_labels: d[i] += 1 d = dict((i, k) for i, k in d.items() if k != 1) line_labels_u = [] for lab in reversed(line_labels): c = d.get(lab, 0) if c >= 1: v = lab + "_num_" + str(c) ...
def unique_labels(line_labels)
If a label occurs more than once, add num. as suffix.
2.64256
2.43179
1.086673
# Plot boxes in their original x position, at a height given by the # key word box_axes_spacing above the arrow tip. The default # is set to 0.06. This is in figure fraction so that the spacing # doesn't depend on the data y range. box_loc = [] fig_inv_trans = fig.transFigure.inverted() ...
def get_box_loc(fig, ax, line_wave, arrow_tip, box_axes_space=0.06)
Box loc in data coords, given Fig. coords offset from arrow_tip. Parameters ---------- fig: matplotlib Figure artist Figure on which the boxes will be placed. ax: matplotlib Axes artist Axes on which the boxes will be placed. arrow_tip: list or array of floats Location of ti...
4.960084
4.59832
1.078673
# Adjust positions. niter = 0 changed = True nlines = len(line_wave) wlp = line_wave[:] while changed: changed = False for i in range(nlines): if i > 0: diff1 = wlp[i] - wlp[i - 1] separation1 = (box_widths[i] + box_widths[i - 1])...
def adjust_boxes(line_wave, box_widths, left_edge, right_edge, max_iter=1000, adjust_factor=0.35, factor_decrement=3.0, fd_p=0.75)
Ajdust given boxes so that they don't overlap. Parameters ---------- line_wave: list or array of floats Line wave lengths. These are assumed to be the initial y (wave length) location of the boxes. box_widths: list or array of floats Width of box containing labels for each line ...
1.967126
2.011215
0.978078
# Axes location in figure. if not fig: fig = plt.figure() ax = fig.add_axes([ax_lower[0], ax_lower[1], ax_dim[0], ax_dim[1]]) ax.plot(wave, flux) return fig, ax
def prepare_axes(wave, flux, fig=None, ax_lower=(0.1, 0.1), ax_dim=(0.85, 0.65))
Create fig and axes if needed and layout axes in fig.
2.358583
2.261304
1.043019
return dict( xycoords="data", textcoords="data", rotation=90, horizontalalignment="center", verticalalignment="center", arrowprops=dict(arrowstyle="-", relpos=(0.5, 0.0)) )
def initial_annotate_kwargs()
Return default parameters passed to Axes.annotate to create labels.
3.820177
3.394512
1.125398
if np.iscomplexobj(data): phase = interpolate_grid( cin, cout, unwrap.unwrap_phase(np.angle(data)), fillval=0) ampli = interpolate_grid(cin, cout, np.abs(data), fillval=1) return ampli * np.exp(1j * phase) ipol = spinterp.interp2d(x=cin[0], y=cin[1], z=data, ...
def interpolate_grid(cin, cout, data, fillval=0)
Return the 2D field averaged radially w.r.t. the center
2.686943
2.695062
0.996987
# sample the sphere radius with approximately 42px # (rounded to next integer pixel size) samp_mult = radius_sampling * pixel_size / radius sizex = grid_size[0] * samp_mult sizey = grid_size[1] * samp_mult grid_size_sim = [np.int(np.round(sizex)), np.int(np.round(sizey)...
def rytov(radius=5e-6, sphere_index=1.339, medium_index=1.333, wavelength=550e-9, pixel_size=.5e-6, grid_size=(80, 80), center=(39.5, 39.5), focus=0, radius_sampling=42)
Field behind a dielectric sphere in the Rytov approximation Parameters ---------- radius: float Radius of the sphere [m] sphere_index: float Refractive index of the sphere medium_index: float Refractive index of the surrounding medium wavelength: float Vacuum wav...
3.199906
3.035969
1.053998
import imp, sys, random, string, copy class ContextImporter(object): def find_module(self, fullname, path=None): if fullname == '_context': self.path = path return self return None def load_module(self, name): mod = imp.new...
def _run_resources_file(path, stack)
With a bit of import magic, we load the given path as a python module, while providing it access to the given stack under the import name '_context'. This function returns the module's global dictionary.
3.548064
3.544729
1.000941
srcmodule = _run_resources_file(path, stack) # Process the loaded module and find the stack elements elements = self.find_stack_elements(srcmodule) elements = sorted(elements, key=lambda x: x[:-1]) # Assign a name to each element and add to our dictionaries for (...
def load_template_srcmodule(self, stack, path)
This function actually fills the stack with definitions coming from a template file
5.526595
5.611534
0.984863
from types import ModuleType if _visited_modules is None: _visited_modules = [] _visited_modules.append(module) # elements = [] for el_name in dir(module): the_el = module.__getattribute__(el_name) if isinstance(the_el, ModuleType): ...
def find_stack_elements(self, module, module_name="", _visited_modules=None)
This function goes through the given container and returns the stack elements. Each stack element is represented by a tuple: ( container_name, element_name, stack_element) The tuples are returned in an array
2.318253
2.305059
1.005724
if len(self.Parameters) > 0: t['Parameters'] = dict([e.contents(stack) for e in self.Parameters]) if len(self.Mappings) > 0: t['Mappings'] = dict([e.contents(stack) for e in self.Mappings]) if len(self.Resources) > 0: t['Resources'] = dict([e.contents...
def dump_to_template_obj(self, stack, t)
Add resource definitions to the given template object
1.75488
1.704558
1.029522
# Build template t = {} t['AWSTemplateFormatVersion'] = '2010-09-09' if self.description is not None: t['Description'] = self.description self.elements.dump_to_template_obj(self, t) return _CustomJSONEncoder(indent=2 if pretty else None, ...
def dump_json(self, pretty=True)
Return a string representation of this CloudFormation template.
4.70823
4.091138
1.150836
''' Returns path to temporary copy of embedded QuickLook preview, if it exists ''' try: assert(exists(src_path) and isdir(src_path)) preview_list = glob(join(src_path, '[Q|q]uicklook', '[P|p]review.*')) assert(preview_list) # Assert there's at least one preview file preview_path = preview_list[0] ...
def embedded_preview(src_path)
Returns path to temporary copy of embedded QuickLook preview, if it exists
4.714564
3.923397
1.201654
''' Returns the path to small thumbnail preview. ''' try: assert(exists(src_path)) width = '1980' dest_dir = mkdtemp(prefix='pyglass') cmd = [QLMANAGE, '-t', '-s', width, src_path, '-o', dest_dir] assert(check_call(cmd) == 0) src_filename = basename(src_path) dest_list = glob(join(des...
def thumbnail_preview(src_path)
Returns the path to small thumbnail preview.
4.280372
4.013396
1.066521
def idle(): with gdk.lock: return bool(func(*args, **kwargs)) return gobject.idle_add(idle)
def gcall(func, *args, **kwargs)
Calls a function, with the given arguments inside Gtk's main loop. Example:: gcall(lbl.set_text, "foo") If this call would be made in a thread there could be problems, using it inside Gtk's main loop makes it thread safe.
9.455153
9.598595
0.985056
results = queue.Queue() @gcall def run(): try: data = func(*args, **kwargs) results.put(data) results.put(None) except BaseException: # XXX: handle results.put(None) results.put(sys.exc_info()) raise data = r...
def invoke_in_mainloop(func, *args, **kwargs)
Invoke a function in the mainloop, pass the data back.
3.443302
3.212173
1.071954
''' Decorator to make wrapped function threadsafe by forcing it to execute within the GTK main thread. .. versionadded:: 0.18 .. versionchanged:: 0.22 Add support for keyword arguments in callbacks by supporting functions wrapped by `functools.partial()`. Also, ignore callback ret...
def gtk_threadsafe(func)
Decorator to make wrapped function threadsafe by forcing it to execute within the GTK main thread. .. versionadded:: 0.18 .. versionchanged:: 0.22 Add support for keyword arguments in callbacks by supporting functions wrapped by `functools.partial()`. Also, ignore callback return value ...
5.280863
2.064416
2.558042
args = (self.counter,) + args thread = threading.Thread( target=self._work_callback, args=args, kwargs=kwargs ) thread.setDaemon(self.daemon) thread.start()
def start(self, *args, **kwargs)
Start the task. This is: * not threadsave * assumed to be called in the gtk mainloop
4.15408
4.96874
0.836043