docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Encapsulates the render -> parse -> validate -> load process. Args: raw_config (str): the raw stacker configuration string. environment (dict, optional): any environment values that should be passed to the config validate (bool): if provided, the config is validated before being...
def render_parse_load(raw_config, environment=None, validate=True): pre_rendered = render(raw_config, environment) rendered = process_remote_sources(pre_rendered, environment) config = parse(rendered) # For backwards compatibility, if the config doesn't specify a namespace, # we fall back t...
171,730
Renders a config, using it as a template with the environment. Args: raw_config (str): the raw stacker configuration string. environment (dict, optional): any environment values that should be passed to the config Returns: str: the stacker configuration populated with any v...
def render(raw_config, environment=None): t = Template(raw_config) buff = StringIO() if not environment: environment = {} try: substituted = t.substitute(environment) except KeyError as e: raise exceptions.MissingEnvironment(e.args[0]) except ValueError: # S...
171,731
Parse a raw yaml formatted stacker config. Args: raw_config (str): the raw stacker configuration string in yaml format. Returns: :class:`Config`: the parsed stacker config.
def parse(raw_config): # Convert any applicable dictionaries back into lists # This is necessary due to the move from lists for these top level config # values to either lists or OrderedDicts. # Eventually we should probably just make them OrderedDicts only. config_dict = yaml_to_ordered_dict(...
171,732
Loads a stacker configuration by modifying sys paths, loading lookups, etc. Args: config (:class:`Config`): the stacker config to load. Returns: :class:`Config`: the stacker config provided above.
def load(config): if config.sys_path: logger.debug("Appending %s to sys.path.", config.sys_path) sys.path.append(config.sys_path) logger.debug("sys.path is now %s", sys.path) if config.lookups: for key, handler in config.lookups.items(): register_lookup_handler(...
171,733
Dumps a stacker Config object as yaml. Args: config (:class:`Config`): the stacker Config object. stream (stream): an optional stream object to write to. Returns: str: the yaml formatted stacker Config.
def dump(config): return yaml.safe_dump( config.to_primitive(), default_flow_style=False, encoding='utf-8', allow_unicode=True)
171,734
Stage remote package sources and merge in remote configs. Args: raw_config (str): the raw stacker configuration string. environment (dict, optional): any environment values that should be passed to the config Returns: str: the raw stacker configuration string
def process_remote_sources(raw_config, environment=None): config = yaml.safe_load(raw_config) if config and config.get('package_sources'): processor = SourceProcessor( sources=config['package_sources'], stacker_cache_dir=config.get('stacker_cache_dir') ) pro...
171,735
Create the content of DIDL desc element from a uri. Args: uri (str): A uri, eg: ``'x-sonos-http:track%3a3402413.mp3?sid=2&flags=32&sn=4'`` Returns: str: The content of a desc element for that uri, eg ``'SA_RINCON519_email@example.com'``
def desc_from_uri(uri): # # If there is an sn parameter (which is the serial number of an account), # we can obtain all the information we need from that, because we can find # the relevant service_id in the account database (it is the same as the # service_type). Consequently, the sid paramete...
171,760
Fetch the music services data xml from a Sonos device. Args: soco (SoCo): a SoCo instance to query. If none is specified, a random device will be used. Defaults to `None`. Returns: str: a string containing the music services data xml
def _get_music_services_data_xml(soco=None): device = soco or discovery.any_soco() log.debug("Fetching music services data from %s", device) available_services = device.musicServices.ListAvailableServices() descriptor_list_xml = available_services[ 'AvailableServiceD...
171,766
Get the data relating to a named music service. Args: service_name (str): The name of the music service for which data is required. Returns: dict: Data relating to the music service. Raises: `MusicServiceException`: if the music service cann...
def get_data_for_name(cls, service_name): for service in cls._get_music_services_data().values(): if service_name == service["Name"]: return service raise MusicServiceException( "Unknown music service: '%s'" % service_name)
171,769
Get metadata for a media item. Args: item_id (str): The item for which metadata is required. Returns: ~collections.OrderedDict: The item's metadata, or `None` See also: The Sonos `getMediaMetadata API <http://musicpartners.sonos.com/node/83>`_
def get_media_metadata(self, item_id): response = self.soap_client.call( 'getMediaMetadata', [('id', item_id)]) return response.get('getMediaMetadataResult', None)
171,775
Get extended metadata for a media item, such as related items. Args: item_id (str): The item for which metadata is required. Returns: ~collections.OrderedDict: The item's extended metadata or None. See also: The Sonos `getExtendedMetadata API <h...
def get_extended_metadata(self, item_id): response = self.soap_client.call( 'getExtendedMetadata', [('id', item_id)]) return response.get('getExtendedMetadataResult', None)
171,777
Form a music service data structure class from the class key Args: class_key (str): A concatenation of the base class (e.g. MediaMetadata) and the class name Returns: class: Subclass of MusicServiceItem
def get_class(class_key): if class_key not in CLASSES: for basecls in (MediaMetadata, MediaCollection): if class_key.startswith(basecls.__name__): # So MediaMetadataTrack turns into MSTrack class_name = 'MS' + class_key.replace(basecls.__name__, '') ...
171,782
Parse the response to a music service query and return a SearchResult Args: service (MusicService): The music service that produced the response response (OrderedDict): The response from the soap client call search_type (str): A string that indicates the search type that the res...
def parse_response(service, response, search_type): _LOG.debug('Parse response "%s" from service "%s" of type "%s"', response, service, search_type) items = [] # The result to be parsed is in either searchResult or getMetadataResult if 'searchResult' in response: response = r...
171,783
Form and return a music service item uri Args: item_id (str): The item id service (MusicService): The music service that the item originates from is_track (bool): Whether the item_id is from a track or not Returns: str: The music service item uri
def form_uri(item_id, service, is_track): if is_track: uri = service.sonos_uri_from_id(item_id) else: uri = 'x-rincon-cpcontainer:' + item_id return uri
171,784
Init music service item Args: item_id (str): This is the Didl compatible id NOT the music item id desc (str): A DIDL descriptor, default ``'RINCON_AssociatedZPUDN' resources (list): List of DidlResource uri (str): The uri for the location of the item ...
def __init__(self, item_id, desc, # pylint: disable=too-many-arguments resources, uri, metadata_dict, music_service=None): _LOG.debug('%s.__init__ with item_id=%s, desc=%s, resources=%s, ' 'uri=%s, metadata_dict=..., music_service=%s', self.__clas...
171,788
Return an element instantiated from the information that a music service has (alternative constructor) Args: music_service (MusicService): The music service that content_dict originated from content_dict (OrderedDict): The data to instantiate the music ...
def from_music_service(cls, music_service, content_dict): # Form the item_id quoted_id = quote_url(content_dict['id'].encode('utf-8')) # The hex prefix remains a mistery for now item_id = '0fffffff{}'.format(quoted_id) # Form the uri is_track = cls == get_class('...
171,789
Return an ElementTree Element representing this instance. Args: include_namespaces (bool, optional): If True, include xml namespace attributes on the root element Return: ~xml.etree.ElementTree.Element: The (XML) Element representation of this ob...
def to_element(self, include_namespaces=False): # We piggy back on the implementation in DidlItem didl_item = DidlItem( title="DUMMY", # This is ignored. Sonos gets the title from the item_id parent_id="DUMMY", # Ditto item_id=self.item_id, ...
171,791
Fetch the account data from a Sonos device. Args: soco (SoCo): a SoCo instance to query. If soco is `None`, a random device will be used. Returns: str: a byte string containing the account data xml
def _get_account_xml(soco): # It is likely that the same information is available over UPnP as well # via a call to # systemProperties.GetStringX([('VariableName','R_SvcAccounts')])) # This returns an encrypted string, and, so far, we cannot decrypt it device = soco or d...
171,798
Get a list of accounts for a given music service. Args: service_type (str): The service_type to use. Returns: list: A list of `Account` instances.
def get_accounts_for_service(cls, service_type): return [ a for a in cls.get_accounts().values() if a.service_type == service_type ]
171,800
Demo function using soco.snapshot across multiple Sonos players. Args: zones (set): a set of SoCo objects alert_uri (str): uri that Sonos can play as an alert alert_volume (int): volume level for playing alert (0 tp 100) alert_duration (int): length of alert (if zero then length of ...
def play_alert(zones, alert_uri, alert_volume=20, alert_duration=0, fade_back=False): # Use soco.snapshot to capture current state of each zone to allow restore for zone in zones: zone.snap = Snapshot(zone) zone.snap.snapshot() print('snapshot of zone: {}'.format(zone.player_name))...
171,801
Get an item from the cache for this combination of args and kwargs. Args: *args: any arguments. **kwargs: any keyword arguments. Returns: object: The object which has been found in the cache, or `None` if no unexpired item is found. This means that there...
def get(self, *args, **kwargs): if not self.enabled: return None # Look in the cache to see if there is an unexpired item. If there is # we can just return the cached result. cache_key = self.make_key(args, kwargs) # Lock and load with self._cache_loc...
171,804
Ensure an Album Art URI is an absolute URI. Args: url (str): the album art URI. Returns: str: An absolute URI.
def build_album_art_full_uri(self, url): # Add on the full album art link, as the URI version # does not include the ipaddress if not url.startswith(('http:', 'https:')): url = 'http://' + self.soco.ip_address + ':1400' + url return url
171,809
Update an item's Album Art URI to be an absolute URI. Args: item: The item to update the URI for
def _update_album_art_to_full_uri(self, item): if getattr(item, 'album_art_uri', False): item.album_art_uri = self.build_album_art_full_uri( item.album_art_uri)
171,810
Search for an artist, an artist's albums, or specific track. Args: artist (str): an artist's name. album (str, optional): an album name. Default `None`. track (str, optional): a track name. Default `None`. full_album_art_uri (bool): whether the album art URI shou...
def search_track(self, artist, album=None, track=None, full_album_art_uri=False): subcategories = [artist] subcategories.append(album or '') # Perform the search result = self.get_album_artists( full_album_art_uri=full_album_art_uri, ...
171,825
Get an artist's albums. Args: artist (str): an artist's name. full_album_art_uri: whether the album art URI should be absolute (i.e. including the IP address). Default `False`. Returns: A `SearchResult` instance.
def get_albums_for_artist(self, artist, full_album_art_uri=False): subcategories = [artist] result = self.get_album_artists( full_album_art_uri=full_album_art_uri, subcategories=subcategories, complete_result=True) reduced = [item for item in result ...
171,826
Get the tracks of an artist's album. Args: artist (str): an artist's name. album (str): an album name. full_album_art_uri: whether the album art URI should be absolute (i.e. including the IP address). Default `False`. Returns: A `SearchRe...
def get_tracks_for_album(self, artist, album, full_album_art_uri=False): subcategories = [artist, album] result = self.get_album_artists( full_album_art_uri=full_album_art_uri, subcategories=subcategories, complete_result=True) result._metadata['searc...
171,827
Called when a method on the instance cannot be found. Causes an action to be sent to UPnP server. See also `object.__getattr__`. Args: action (str): The name of the unknown method. Returns: callable: The callable to be invoked. .
def __getattr__(self, action): # Define a function to be invoked as the method, which calls # send_command. def _dispatcher(self, *args, **kwargs): return self.send_command(action, *args, **kwargs) # rename the function so it appears to be the called m...
171,834
Extract arguments and their values from a SOAP response. Args: xml_response (str): SOAP/xml response text (unicode, not utf-8). Returns: dict: a dict of ``{argument_name: value}`` items.
def unwrap_arguments(xml_response): # A UPnP SOAP response (including headers) looks like this: # HTTP/1.1 200 OK # CONTENT-LENGTH: bytes in body # CONTENT-TYPE: text/xml; charset="utf-8" DATE: when response was # generated # EXT: # SERVER: OS/version U...
171,836
Disect a UPnP error, and raise an appropriate exception. Args: xml_error (str): a unicode string containing the body of the UPnP/SOAP Fault response. Raises an exception containing the error code.
def handle_upnp_error(self, xml_error): # An error code looks something like this: # HTTP/1.1 500 Internal Server Error # CONTENT-LENGTH: bytes in body # CONTENT-TYPE: text/xml; charset="utf-8" # DATE: when response was generated # EXT: # SERVER: OS/ver...
171,840
Convert any number of `DidlObjects <DidlObject>` to a unicode xml string. Args: *args (DidlObject): One or more `DidlObject` (or subclass) instances. Returns: str: A unicode string representation of DIDL-Lite XML in the form ``'<DIDL-Lite ...>...</DIDL-Lite>'``.
def to_didl_string(*args): didl = XML.Element( 'DIDL-Lite', { 'xmlns': "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/", 'xmlns:dc': "http://purl.org/dc/elements/1.1/", 'xmlns:upnp': "urn:schemas-upnp-org:metadata-1-0/upnp/", 'xmlns:r': "urn:schemas...
171,856
Set the resource properties from a ``<res>`` element. Args: element (~xml.etree.ElementTree.Element): The ``<res>`` element
def from_element(cls, element): def _int_helper(name): result = element.get(name) if result is not None: try: return int(result) except ValueError: raise DIDLMetadataError( ...
171,858
Return a dict representation of the `DidlResource`. Args: remove_nones (bool, optional): Optionally remove dictionary elements when their value is `None`. Returns: dict: a dict representing the `DidlResource`
def to_dict(self, remove_nones=False): content = { 'uri': self.uri, 'protocol_info': self.protocol_info, 'import_uri': self.import_uri, 'size': self.size, 'duration': self.duration, 'bitrate': self.bitrate, 'sample_freq...
171,861
Create a new instance. Args: name (str): Name of the class. bases (tuple): Base classes. attrs (dict): attributes defined for the class.
def __new__(cls, name, bases, attrs): new_cls = super(DidlMetaClass, cls).__new__(cls, name, bases, attrs) # Register all subclasses with the global _DIDL_CLASS_TO_CLASS mapping item_class = attrs.get('item_class', None) if item_class is not None: _DIDL_CLASS_TO_CLAS...
171,863
Create an instance of this class from an ElementTree xml Element. An alternative constructor. The element must be a DIDL-Lite <item> or <container> element, and must be properly namespaced. Args: xml (~xml.etree.ElementTree.Element): An :class:`~xml.etree.ElementTre...
def from_element(cls, element): # pylint: disable=R0914 # We used to check here that we have the right sort of element, # ie a container or an item. But Sonos seems to use both # indiscriminately, eg a playlistContainer can be an item or a # container. So we now just check t...
171,865
Create an instance from a dict. An alternative constructor. Equivalent to ``DidlObject(**content)``. Args: content (dict): a dict containing metadata information. Required. Valid keys are the same as the parameters for `DidlObject`.
def from_dict(cls, content): # Do we really need this constructor? Could use DidlObject(**content) # instead. -- We do now if 'resources' in content: content['resources'] = [DidlResource.from_dict(x) for x in content['resources']] ...
171,866
Return the dict representation of the instance. Args: remove_nones (bool, optional): Optionally remove dictionary elements when their value is `None`. Returns: dict: a dict representation of the `DidlObject`.
def to_dict(self, remove_nones=False): content = {} # Get the value of each attribute listed in _translation, and add it # to the content dict for key in self._translation: if hasattr(self, key): content[key] = getattr(self, key) # also add pa...
171,870
Return an ElementTree Element representing this instance. Args: include_namespaces (bool, optional): If True, include xml namespace attributes on the root element Return: ~xml.etree.ElementTree.Element: an Element.
def to_element(self, include_namespaces=False): elt_attrib = {} if include_namespaces: elt_attrib.update({ 'xmlns': "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/", 'xmlns:dc': "http://purl.org/dc/elements/1.1/", 'xmlns:upnp': "urn:sche...
171,871
Renew the event subscription. You should not try to renew a subscription which has been unsubscribed, or once it has expired. Args: requested_timeout (int, optional): The period for which a renewal request should be made. If None (the default), use the timeout ...
def renew(self, requested_timeout=None): # NB This code is sometimes called from a separate thread (when # subscriptions are auto-renewed. Be careful to ensure thread-safety if self._has_been_unsubscribed: raise SoCoException( 'Cannot renew subscription once...
171,890
Play a track from the queue by index. The index number is required as an argument, where the first index is 0. Args: index (int): 0-based index of the track to play start (bool): If the item that has been set should start playing
def play_from_queue(self, index, start=True): # Grab the speaker's information if we haven't already since we'll need # it in the next step. if not self.speaker_info: self.get_speaker_info() # first, set the queue itself as the source URI uri = 'x-rincon-que...
171,901
Switch the speaker's input to line-in. Args: source (SoCo): The speaker whose line-in should be played. Default is line-in from the speaker itself.
def switch_to_line_in(self, source=None): if source: uid = source.uid else: uid = self.uid self.avTransport.SetAVTransportURI([ ('InstanceID', 0), ('CurrentURI', 'x-rincon-stream:{0}'.format(uid)), ('CurrentURIMetaData', '') ...
171,918
Get information about the Sonos speaker. Arguments: refresh(bool): Refresh the speaker info cache. timeout: How long to wait for the server to send data before giving up, as a float, or a `(connect timeout, read timeout)` tuple e.g. (3, 5)...
def get_speaker_info(self, refresh=False, timeout=None): if self.speaker_info and refresh is False: return self.speaker_info else: response = requests.get('http://' + self.ip_address + ':1400/xml/device_description.xml', ...
171,924
Add a sequence of items to the queue. Args: items (list): A sequence of items to the be added to the queue container (DidlObject, optional): A container object which includes the items.
def add_multiple_to_queue(self, items, container=None): if container is not None: container_uri = container.resources[0].uri container_metadata = to_didl_string(container) else: container_uri = '' # Sonos seems to accept this as well container_me...
171,931
Remove a track from the queue by index. The index number is required as an argument, where the first index is 0. Args: index (int): The (0-based) index of the track to remove
def remove_from_queue(self, index): # TODO: what do these parameters actually do? updid = '0' objid = 'Q:0/' + str(index + 1) self.avTransport.RemoveTrackFromQueue([ ('InstanceID', 0), ('ObjectID', objid), ('UpdateID', updid), ])
171,932
Helper method for `get_favorite_radio_*` methods. Args: favorite_type (str): Specify either `RADIO_STATIONS` or `RADIO_SHOWS`. start (int): Which number to start the retrieval from. Used for paging. max_items (int): The total number of results...
def __get_favorites(self, favorite_type, start=0, max_items=100): if favorite_type not in (RADIO_SHOWS, RADIO_STATIONS): favorite_type = SONOS_FAVORITES response = self.contentDirectory.Browse([ ('ObjectID', 'FV:2' if favorite_type is SONOS_FAVORITES ...
171,936
Create a new empty Sonos playlist. Args: title: Name of the playlist :rtype: :py:class:`~.soco.data_structures.DidlPlaylistContainer`
def create_sonos_playlist(self, title): response = self.avTransport.CreateSavedQueue([ ('InstanceID', 0), ('Title', title), ('EnqueuedURI', ''), ('EnqueuedURIMetaData', ''), ]) item_id = response['AssignedObjectID'] obj_id = item_...
171,937
Create a new Sonos playlist from the current queue. Args: title: Name of the playlist :rtype: :py:class:`~.soco.data_structures.DidlPlaylistContainer`
def create_sonos_playlist_from_queue(self, title): # Note: probably same as Queue service method SaveAsSonosPlaylist # but this has not been tested. This method is what the # controller uses. response = self.avTransport.SaveQueue([ ('InstanceID', 0), ('T...
171,938
Remove a Sonos playlist. Args: sonos_playlist (DidlPlaylistContainer): Sonos playlist to remove or the item_id (str). Returns: bool: True if succesful, False otherwise Raises: SoCoUPnPException: If sonos_playlist does not point to a valid ...
def remove_sonos_playlist(self, sonos_playlist): object_id = getattr(sonos_playlist, 'item_id', sonos_playlist) return self.contentDirectory.DestroyObject([('ObjectID', object_id)])
171,939
Adds a queueable item to a Sonos' playlist. Args: queueable_item (DidlObject): the item to add to the Sonos' playlist sonos_playlist (DidlPlaylistContainer): the Sonos' playlist to which the item should be added
def add_item_to_sonos_playlist(self, queueable_item, sonos_playlist): # Get the update_id for the playlist response, _ = self.music_library._music_lib_search( sonos_playlist.item_id, 0, 1) update_id = response['UpdateID'] # Form the metadata for queueable_item ...
171,940
Make a string unicode. Really. Ensure ``in_string`` is returned as unicode through a series of progressively relaxed decodings. Args: in_string (str): The string to convert. Returns: str: Unicode. Raises: ValueError
def really_unicode(in_string): if isinstance(in_string, StringType): for args in (('utf-8',), ('latin-1',), ('ascii', 'replace')): try: # pylint: disable=star-args in_string = in_string.decode(*args) break except UnicodeDecodeError...
171,947
Convert camelcase to lowercase and underscore. Recipe from http://stackoverflow.com/a/1176023 Args: string (str): The string to convert. Returns: str: The converted string.
def camel_to_underscore(string): string = FIRST_CAP_RE.sub(r'\1_\2', string) return ALL_CAP_RE.sub(r'\1_\2', string).lower()
171,948
Return a pretty-printed version of a unicode XML string. Useful for debugging. Args: unicode_text (str): A text representation of XML (unicode, *not* utf-8). Returns: str: A pretty-printed version of the input.
def prettify(unicode_text): import xml.dom.minidom reparsed = xml.dom.minidom.parseString(unicode_text.encode('utf-8')) return reparsed.toprettyxml(indent=" ", newl="\n")
171,949
Prepare the http headers for sending. Add the SOAPACTION header to the others. Args: http_headers (dict): A dict in the form {'Header': 'Value,..} containing http headers to use for the http request. soap_action (str): The value of the SOAPACTION header. ...
def prepare_headers(self, http_headers, soap_action): headers = {'Content-Type': 'text/xml; charset="utf-8"'} if soap_action is not None: headers.update({'SOAPACTION': '"{}"'.format(soap_action)}) if http_headers is not None: headers.update(http_headers) ...
171,956
Prepare the SOAP message body for sending. Args: method (str): The name of the method to call. parameters (list): A list of (name, value) tuples containing the parameters to pass to the method. namespace (str): tThe XML namespace to use for the method. ...
def prepare_soap_body(self, method, parameters, namespace): tags = [] for name, value in parameters: tag = "<{name}>{value}</{name}>".format( name=name, value=escape("%s" % value, {'"': "&quot;"})) # % converts to unicode because we are using unicode lit...
171,957
Prepare the SOAP Envelope for sending. Args: prepared_soap_header (str): A SOAP Header prepared by `prepare_soap_header` prepared_soap_body (str): A SOAP Body prepared by `prepare_soap_body` Returns: str: A prepared SOAP Envelope
def prepare_soap_envelope(self, prepared_soap_header, prepared_soap_body): # pylint: disable=bad-continuation soap_env_template = ( '<?xml version="1.0"?>' '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"' ' s:encodingStyle="http://schemas.xm...
171,958
Convert a unicode xml string to a list of `DIDLObjects <DidlObject>`. Args: string (str): A unicode string containing an XML representation of one or more DIDL-Lite items (in the form ``'<DIDL-Lite ...> ...</DIDL-Lite>'``) Returns: list: A list of one or more instances...
def from_didl_string(string): items = [] root = XML.fromstring(string.encode('utf-8')) for elt in root: if elt.tag.endswith('item') or elt.tag.endswith('container'): item_class = elt.findtext(ns_tag('upnp', 'class')) # In case this class has an # specified unofficial ...
171,981
Get a set of all alarms known to the Sonos system. Args: zone (`SoCo`, optional): a SoCo instance to query. If None, a random instance is used. Defaults to `None`. Returns: set: A set of `Alarm` instances Note: Any existing `Alarm` instance will have its attributes upd...
def get_alarms(zone=None): # Get a soco instance to query. It doesn't matter which. if zone is None: zone = discovery.any_soco() response = zone.alarmClock.ListAlarms() alarm_list = response['CurrentAlarmList'] tree = XML.fromstring(alarm_list.encode('utf-8')) # An alarm list looks...
172,000
Restore the state of a device to that which was previously saved. For coordinator devices restore everything. For slave devices only restore volume etc., not transport info (transport info comes from the slave's coordinator). Args: fade (bool): Whether volume should be fade...
def restore(self, fade=False): if self.is_coordinator: # Start by ensuring that the speaker is paused as we don't want # things all rolling back when we are changing them, as this could # include things like audio transport_info = self.device.get_current...
172,012
Maps values to colors Args: values (list or list of lists) - list of values to map to colors cmap (str) - color map (default is 'husl') res (int) - resolution of the color map (default: 100) Returns: list of rgb tuples
def vals2colors(vals,cmap='GnBu_d',res=100): # flatten if list of lists if any(isinstance(el, list) for el in vals): vals = list(itertools.chain(*vals)) # get palette from seaborn palette = np.array(sns.color_palette(cmap, res)) ranks = np.digitize(vals, np.linspace(np.min(vals), np.ma...
172,035
Maps values to bins Args: values (list or list of lists) - list of values to map to colors res (int) - resolution of the color map (default: 100) Returns: list of numbers representing bins
def vals2bins(vals,res=100): # flatten if list of lists if any(isinstance(el, list) for el in vals): vals = list(itertools.chain(*vals)) return list(np.digitize(vals, np.linspace(np.min(vals), np.max(vals)+1, res+1)) - 1)
172,036
Build Grab exception from the pycurl exception Args: ex - the original pycurl exception curl - the Curl instance raised the exception
def build_grab_exception(ex, curl): # CURLE_WRITE_ERROR (23) # An error occurred when writing received data to a local file, or # an error was returned to libcurl from a write callback. # This exception should be ignored if grab_callback_interrupted # flag # is enabled (this happens when nohead...
172,085
Generate tuples of pairs of records from a block of records Arguments: blocks -- an iterable sequence of blocked records
def _blockedPairs(self, blocks): block, blocks = core.peek(blocks) self._checkBlock(block) combinations = itertools.combinations pairs = (combinations(sorted(block), 2) for block in blocks) return pairs
172,532
Generate tuples of pairs of records from a block of records Arguments: blocks -- an iterable sequence of blocked records
def _blockedPairs(self, blocks): block, blocks = core.peek(blocks) self._checkBlock(block) product = itertools.product pairs = (product(base, target) for base, target in blocks) return pairs
172,538
Read training from previously built training data file object Arguments: training_file -- file object containing the training data
def readTraining(self, training_file): logger.info('reading training from file') training_pairs = json.load(training_file, cls=serializer.dedupe_decoder) self.markPairs(training_pairs)
172,545
Create a new ``MultipleResults`` object from a dictionary. Keys of the dictionary are unpacked into result names. Args: result_dict (dict) - The dictionary to unpack. Returns: (:py:class:`MultipleResults <dagster.MultipleResults>`) A new ``Multi...
def from_dict(result_dict): check.dict_param(result_dict, 'result_dict', key_type=str) results = [] for name, value in result_dict.items(): results.append(Result(value, name)) return MultipleResults(*results)
172,757
Assigned parameters into the appropiate place in the input notebook Args: nb (NotebookNode): Executable notebook object parameters (dict): Arbitrary keyword arguments to pass to the notebook parameters.
def replace_parameters(context, nb, parameters): # Uma: This is a copy-paste from papermill papermill/execute.py:104 (execute_parameters). # Typically, papermill injects the injected-parameters cell *below* the parameters cell # but we want to *replace* the parameters cell, which is what this function does....
172,927
Get a pipeline by name. Only constructs that pipeline and caches it. Args: name (str): Name of the pipeline to retriever Returns: PipelineDefinition: Instance of PipelineDefinition with that name.
def get_pipeline(self, name): check.str_param(name, 'name') if name in self._pipeline_cache: return self._pipeline_cache[name] try: pipeline = self.pipeline_dict[name]() except KeyError: raise DagsterInvariantViolationError( ...
172,962
The schema for configuration data that describes the type, optionality, defaults, and description. Args: dagster_type (DagsterType): A ``DagsterType`` describing the schema of this field, ie `Dict({'example': Field(String)})` default_value (Any): A default value to use that ...
def Field( dagster_type, default_value=FIELD_NO_DEFAULT_PROVIDED, is_optional=INFER_OPTIONAL_COMPOSITE_FIELD, is_secret=False, description=None, ): config_type = resolve_to_config_type(dagster_type) if not config_type: raise DagsterInvalidDefinitionError( ( ...
173,134
Return the solid named "name". Throws if it does not exist. Args: name (str): Name of solid Returns: SolidDefinition: SolidDefinition with correct name.
def solid_named(self, name): check.str_param(name, 'name') if name not in self._solid_dict: raise DagsterInvariantViolationError( 'Pipeline {pipeline_name} has no solid named {name}.'.format( pipeline_name=self.name, name=name ) ...
173,228
Create a context definition from a pre-existing context. This can be useful in testing contexts where you may want to create a context manually and then pass it into a one-off PipelineDefinition Args: context (ExecutionContext): The context that will provided to the pipeline. ...
def passthrough_context_definition(context_params): check.inst_param(context_params, 'context', ExecutionContext) context_definition = PipelineContextDefinition(context_fn=lambda *_args: context_params) return {DEFAULT_CONTEXT_NAME: context_definition}
173,269
A decorator for annotating a function that can take the selected properties from a ``config_value`` in to an instance of a custom type. Args: config_cls (Selector)
def input_selector_schema(config_cls): config_type = resolve_config_cls_arg(config_cls) check.param_invariant(config_type.is_selector, 'config_cls') def _wrap(func): def _selector(context, config_value): selector_key, selector_value = single_item(config_value) return fu...
173,289
A decorator for a annotating a function that can take the selected properties of a ``config_value`` and an instance of a custom type and materialize it. Args: config_cls (Selector):
def output_selector_schema(config_cls): config_type = resolve_config_cls_arg(config_cls) check.param_invariant(config_type.is_selector, 'config_cls') def _wrap(func): def _selector(context, config_value, runtime_value): selector_key, selector_value = single_item(config_value) ...
173,291
Download an object from s3. Args: info (ExpectationExecutionInfo): Must expose a boto3 S3 client as its `s3` resource. Returns: str: The path to the downloaded object.
def download_from_s3(context): target_file = context.solid_config['target_file'] return context.resources.download_manager.download_file_contents(context, target_file)
173,325
Upload a file to s3. Args: info (ExpectationExecutionInfo): Must expose a boto3 S3 client as its `s3` resource. Returns: (str, str): The bucket and key to which the file was uploaded.
def upload_to_s3(context, file_obj): bucket = context.solid_config['bucket'] key = context.solid_config['key'] context.resources.s3.put_object( Bucket=bucket, Body=file_obj.read(), Key=key, **(context.solid_config.get('kwargs') or {}) ) yield Result(bucket, 'bucket') yield Result(k...
173,326
"Synchronous" version of :py:func:`execute_pipeline_iterator`. Note: raise_on_error is very useful in testing contexts when not testing for error conditions Parameters: pipeline (PipelineDefinition): Pipeline to run environment_dict (dict): The enviroment configuration that parameterizes this ...
def execute_pipeline(pipeline, environment_dict=None, run_config=None): check.inst_param(pipeline, 'pipeline', PipelineDefinition) environment_dict = check.opt_dict_param(environment_dict, 'environment_dict') run_config = check_run_config_param(run_config) environment_config = create_environment_c...
173,415
Schema for configuration data with string keys and typed values via :py:class:`Field` . Args: fields (Dict[str, Field])
def Dict(fields): check_user_facing_fields_dict(fields, 'Dict') class _Dict(_ConfigComposite): def __init__(self): key = 'Dict.' + str(DictCounter.get_next_count()) super(_Dict, self).__init__( name=None, key=key, fields=field...
173,439
Selectors are used when you want to be able present several different options to the user but force them to select one. For example, it would not make much sense to allow them to say that a single input should be sourced from a csv and a parquet file: They must choose. Note that in other type systems this ...
def Selector(fields): check_user_facing_fields_dict(fields, 'Selector') class _Selector(_ConfigSelector): def __init__(self): key = 'Selector.' + str(DictCounter.get_next_count()) super(_Selector, self).__init__( key=key, name=None, ...
173,441
A :py:class`Selector` with a name, allowing it to be referenced by that name. Args: name (str): fields (Dict[str, Field])
def NamedSelector(name, fields, description=None, type_attributes=DEFAULT_TYPE_ATTRIBUTES): check.str_param(name, 'name') check_user_facing_fields_dict(fields, 'NamedSelector named "{}"'.format(name)) class _NamedSelector(_ConfigSelector): def __init__(self): super(_NamedSelector, ...
173,442
Enforces lower and upper bounds for numeric flags. Args: parser: NumericParser (either FloatParser or IntegerParser), provides lower and upper bounds, and help text to display. name: str, name of the flag flag_values: FlagValues.
def _register_bounds_validator_if_needed(parser, name, flag_values): if parser.lower_bound is not None or parser.upper_bound is not None: def checker(value): if value is not None and parser.is_outside_bounds(value): message = '%s is not %s' % (value, parser.syntactic_help) raise _excepti...
175,720
Declares that all flags key to a module are key to the current module. Args: module: module, the module object from which all key flags will be declared as key flags to the current module. flag_values: FlagValues, the FlagValues instance in which the flags will be declared as key flags. This ...
def adopt_module_key_flags(module, flag_values=_flagvalues.FLAGS): if not isinstance(module, types.ModuleType): raise _exceptions.Error('Expected a module object, not %r.' % (module,)) _internal_declare_key_flags( [f.name for f in flag_values.get_key_flags_for_module(module.__name__)], flag_value...
175,725
Changes the Kernel's /proc/self/status process name on Linux. The kernel name is NOT what will be shown by the ps or top command. It is a 15 character string stored in the kernel's process table that is included in the kernel log when a process is OOM killed. The first 15 bytes of name are used. Non-ASCII uni...
def set_kernel_process_name(name): if not isinstance(name, bytes): name = name.encode('ascii', 'replace') try: # This is preferred to using ctypes to try and call prctl() when possible. with open('/proc/self/comm', 'wb') as proc_comm: proc_comm.write(name[:15]) except EnvironmentError: tr...
175,737
Parses the string argument and returns the native value. By default it returns its argument unmodified. Args: argument: string argument passed in the commandline. Raises: ValueError: Raised when it fails to parse the argument. TypeError: Raised when the argument has the wrong type. ...
def parse(self, argument): if not isinstance(argument, six.string_types): raise TypeError('flag value must be a string, found "{}"'.format( type(argument))) return argument
175,739
Initializes EnumParser. Args: enum_values: [str], a non-empty list of string values in the enum. case_sensitive: bool, whether or not the enum is to be case-sensitive. Raises: ValueError: When enum_values is empty.
def __init__(self, enum_values, case_sensitive=True): if not enum_values: raise ValueError( 'enum_values cannot be empty, found "{}"'.format(enum_values)) super(EnumParser, self).__init__() self.enum_values = enum_values self.case_sensitive = case_sensitive
175,746
Initializes EnumParser. Args: enum_class: class, the Enum class with all possible flag values. Raises: TypeError: When enum_class is not a subclass of Enum. ValueError: When enum_class is empty.
def __init__(self, enum_class): # Users must have an Enum class defined before using EnumClass flag. # Therefore this dependency is guaranteed. import enum if not issubclass(enum_class, enum.Enum): raise TypeError('{} is not a subclass of Enum.'.format(enum_class)) if not enum_class.__me...
175,747
Determines validity of argument and returns the correct element of enum. Args: argument: str or Enum class member, the supplied flag value. Returns: The first matching Enum class member in Enum class. Raises: ValueError: Raised when argument didn't match anything in enum.
def parse(self, argument): if isinstance(argument, self.enum_class): return argument if argument not in self.enum_class.__members__: raise ValueError('value should be one of <%s>' % '|'.join(self.enum_class.__members__.keys())) else: return self.enum_class[argum...
175,748
Initializer. Args: comma_compat: bool, whether to support comma as an additional separator. If False then only whitespace is supported. This is intended only for backwards compatibility with flags that used to be comma-separated.
def __init__(self, comma_compat=False): self._comma_compat = comma_compat name = 'whitespace or comma' if self._comma_compat else 'whitespace' super(WhitespaceSeparatedListParser, self).__init__(None, name)
175,754
Parses argument as whitespace-separated list of strings. It also parses argument as comma-separated list of strings if requested. Args: argument: string argument passed in the commandline. Returns: [str], the parsed flag value.
def parse(self, argument): if isinstance(argument, list): return argument elif not argument: return [] else: if self._comma_compat: argument = argument.replace(',', ' ') return argument.split()
175,755
Sets whether or not to use GNU style scanning. GNU style allows mixing of flag and non-flag arguments. See http://docs.python.org/library/getopt.html#getopt.gnu_getopt Args: gnu_getopt: bool, whether or not to use GNU style scanning.
def set_gnu_getopt(self, gnu_getopt=True): self.__dict__['__use_gnu_getopt'] = gnu_getopt self.__dict__['__use_gnu_getopt_explicitly_set'] = True
175,757
Records the module that defines a specific flag. We keep track of which flag is defined by which module so that we can later sort the flags by module. Args: module_name: str, the name of a Python module. flag: Flag, the Flag instance that is key to the module.
def register_flag_by_module(self, module_name, flag): flags_by_module = self.flags_by_module_dict() flags_by_module.setdefault(module_name, []).append(flag)
175,758
Records the module that defines a specific flag. Args: module_id: int, the ID of the Python module. flag: Flag, the Flag instance that is key to the module.
def register_flag_by_module_id(self, module_id, flag): flags_by_module_id = self.flags_by_module_id_dict() flags_by_module_id.setdefault(module_id, []).append(flag)
175,759
Specifies that a flag is a key flag for a module. Args: module_name: str, the name of a Python module. flag: Flag, the Flag instance that is key to the module.
def register_key_flag_for_module(self, module_name, flag): key_flags_by_module = self.key_flags_by_module_dict() # The list of key flags for the module named module_name. key_flags = key_flags_by_module.setdefault(module_name, []) # Add flag, but avoid duplicates. if flag not in key_flags: ...
175,760
Checks whether a Flag object is registered under long name or short name. Args: flag_obj: Flag, the Flag instance to check for. Returns: bool, True iff flag_obj is registered under long name or short name.
def _flag_is_registered(self, flag_obj): flag_dict = self._flags() # Check whether flag_obj is registered under its long name. name = flag_obj.name if flag_dict.get(name, None) == flag_obj: return True # Check whether flag_obj is registered under its short name. short_name = flag_obj....
175,761
Cleans up unregistered flags from all module -> [flags] dictionaries. If flag_obj is registered under either its long name or short name, it won't be removed from the dictionaries. Args: flag_obj: Flag, the Flag instance to clean up for.
def _cleanup_unregistered_flag_from_module_dicts(self, flag_obj): if self._flag_is_registered(flag_obj): return for flags_by_module_dict in (self.flags_by_module_dict(), self.flags_by_module_id_dict(), self.key_flags_by_module_dict()):...
175,762
Returns the list of flags defined by a module. Args: module: module|str, the module to get flags from. Returns: [Flag], a new list of Flag instances. Caller may update this list as desired: none of those changes will affect the internals of this FlagValue instance.
def _get_flags_defined_by_module(self, module): if not isinstance(module, str): module = module.__name__ return list(self.flags_by_module_dict().get(module, []))
175,763
Returns the list of key flags for a module. Args: module: module|str, the module to get key flags from. Returns: [Flag], a new list of Flag instances. Caller may update this list as desired: none of those changes will affect the internals of this FlagValue instance.
def get_key_flags_for_module(self, module): if not isinstance(module, str): module = module.__name__ # Any flag is a key flag for the module that defined it. NOTE: # key_flags is a fresh list: we can update it without affecting the # internals of this FlagValues object. key_flags = self...
175,764
Return the name of the module defining this flag, or default. Args: flagname: str, name of the flag to lookup. default: Value to return if flagname is not defined. Defaults to None. Returns: The name of the module which registered the flag with this name. If no such module ex...
def find_module_defining_flag(self, flagname, default=None): registered_flag = self._flags().get(flagname) if registered_flag is None: return default for module, flags in six.iteritems(self.flags_by_module_dict()): for flag in flags: # It must compare the flag with the one in _flags...
175,765
Return the ID of the module defining this flag, or default. Args: flagname: str, name of the flag to lookup. default: Value to return if flagname is not defined. Defaults to None. Returns: The ID of the module which registered the flag with this name. If no such module exists...
def find_module_id_defining_flag(self, flagname, default=None): registered_flag = self._flags().get(flagname) if registered_flag is None: return default for module_id, flags in six.iteritems(self.flags_by_module_id_dict()): for flag in flags: # It must compare the flag with the one ...
175,766
Returns value if setting flag |name| to |value| returned True. Args: name: str, name of the flag to set. value: Value to set. Returns: Flag value on successful call. Raises: UnrecognizedFlagError IllegalFlagValueError
def _set_unknown_flag(self, name, value): setter = self.__dict__['__set_unknown'] if setter: try: setter(name, value) return value except (TypeError, ValueError): # Flag value is not valid. raise _exceptions.IllegalFlagValueError( '"{1}" is not valid for --{...
175,767
Appends flags registered in another FlagValues instance. Args: flag_values: FlagValues, the FlagValues instance from which to copy flags.
def append_flag_values(self, flag_values): for flag_name, flag in six.iteritems(flag_values._flags()): # pylint: disable=protected-access # Each flags with short_name appears here twice (once under its # normal name, and again with its short name). To prevent # problems (DuplicateFlagError)...
175,768
Asserts if all validators in the list are satisfied. It asserts validators in the order they were created. Args: validators: Iterable(validators.Validator), validators to be verified. Raises: AttributeError: Raised if validators work with a non-existing flag. IllegalFlagValueEr...
def _assert_validators(self, validators): for validator in sorted( validators, key=lambda validator: validator.insertion_index): try: validator.verify(self) except _exceptions.ValidationError as e: message = validator.print_flags_with_values(self) raise _exceptions.I...
175,773
Changes the default value of the named flag object. The flag's current value is also updated if the flag is currently using the default value, i.e. not specified in the command line, and not set by FLAGS.name = value. Args: name: str, the name of the flag to modify. value: The new default ...
def set_default(self, name, value): fl = self._flags() if name not in fl: self._set_unknown_flag(name, value) return fl[name]._set_default(value) # pylint: disable=protected-access self._assert_validators(fl[name].validators)
175,775