docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Parse the given CL function into a SimpleCLFunction object. Args: cl_function (str): the function we wish to turn into an object dependencies (list or tuple of CLLibrary): The list of CL libraries this function depends on Returns: SimpleCLFunction: the CL data type ...
def from_string(cls, cl_function, dependencies=()): return_type, function_name, parameter_list, body = split_cl_function(cl_function) return SimpleCLFunction(return_type, function_name, parameter_list, body, dependencies=dependencies)
623,812
Creates a new function parameter for the CL functions. Args: declaration (str): the declaration of this parameter. For example ``global int foo``.
def __init__(self, declaration): self._address_space = None self._type_qualifiers = [] self._basic_ctype = '' self._vector_type_length = None self._nmr_pointer_stars = 0 self._pointer_qualifiers = [] self._name = '' self._array_sizes = [] ...
623,820
Convenience function for building the kernel for this worker. Args: kernel_source (str): the kernel source to use for building the kernel Returns: cl.Program: a compiled CL kernel
def _build_kernel(self, kernel_source, compile_flags=()): return cl.Program(self._cl_context, kernel_source).build(' '.join(compile_flags))
623,826
Get the numpy dtype of the given cl_type string. Args: cl_type (str): the CL data type to match, for example 'float' or 'float4'. mot_float_type (str): the C name of the ``mot_float_type``. The dtype will be looked up recursively. Returns: dtype: the numpy datatype
def ctype_to_dtype(cl_type, mot_float_type='float'): if is_vector_ctype(cl_type): raw_type, vector_length = split_vector_ctype(cl_type) if raw_type == 'mot_float_type': if is_vector_ctype(mot_float_type): raw_type, _ = split_vector_ctype(mot_float_type) ...
623,842
Convert the given input data to the correct numpy type. Args: data (ndarray): The value to convert to the correct numpy type data_type (str): the data type we need to convert the data to mot_float_type (str): the data type of the current ``mot_float_type`` Returns: ndarray: the...
def convert_data_to_dtype(data, data_type, mot_float_type='float'): scalar_dtype = ctype_to_dtype(data_type, mot_float_type) if isinstance(data, numbers.Number): data = scalar_dtype(data) if is_vector_ctype(data_type): shape = data.shape dtype = ctype_to_dtype(data_type, mot_f...
623,843
Split a vector ctype into a raw ctype and the vector length. If the given ctype is not a vector type, we raise an error. I Args: ctype (str): the ctype to possibly split into a raw ctype and the vector length Returns: tuple: the raw ctype and the vector length
def split_vector_ctype(ctype): if not is_vector_ctype(ctype): raise ValueError('The given ctype is not a vector type.') for vector_length in [2, 3, 4, 8, 16]: if ctype.endswith(str(vector_length)): vector_str_len = len(str(vector_length)) return ctype[:-vector_str_le...
623,844
Converts values like ``gpu`` to a pyopencl device type string. Supported values are: ``accelerator``, ``cpu``, ``custom``, ``gpu``. If ``all`` is given, None is returned. Args: cl_device_type_str (str): The string we want to convert to a device type. Returns: cl.device_type: the pyopencl ...
def device_type_from_string(cl_device_type_str): cl_device_type_str = cl_device_type_str.upper() if hasattr(cl.device_type, cl_device_type_str): return getattr(cl.device_type, cl_device_type_str) return None
623,845
Get the model floating point type definition. Args: double_precision (boolean): if True we will use the double type for the mot_float_type type. Else, we will use the single precision float type for the mot_float_type type. include_complex (boolean): if we include support for complex nu...
def get_float_type_def(double_precision, include_complex=True): if include_complex: with open(os.path.abspath(resource_filename('mot', 'data/opencl/complex.h')), 'r') as f: complex_number_support = f.read() else: complex_number_support = '' scipy_constants = if double...
623,846
Topological sort the given dictionary structure. Args: data (dict); dictionary structure where the value is a list of dependencies for that given key. For example: ``{'a': (), 'b': ('a',)}``, where ``a`` depends on nothing and ``b`` depends on ``a``. Returns: tuple: the dependencie...
def topological_sort(data): def check_self_dependencies(input_data): for k, v in input_data.items(): if k in v: raise ValueError('Self-dependency, {} depends on itself.'.format(k)) def prepare_input_data(input_data): return {k: set(v) for k, v...
623,847
Test if the given value is a scalar. This function also works with memory mapped array values, in contrast to the numpy is_scalar method. Args: value: the value to test for being a scalar value Returns: boolean: if the given value is a scalar or not
def is_scalar(value): return np.isscalar(value) or (isinstance(value, np.ndarray) and (len(np.squeeze(value).shape) == 0))
623,848
Checks if all elements in the given value are equal to each other. If the input is a single value the result is trivial. If not, we compare all the values to see if they are exactly the same. Args: value (ndarray or number): a numpy array or a single number. Returns: bool: true if all...
def all_elements_equal(value): if is_scalar(value): return True return np.array(value == value.flatten()[0]).all()
623,849
Get a single value out of the given value. This is meant to be used after a call to :func:`all_elements_equal` that returned True. With this function we return a single number from the input value. Args: value (ndarray or number): a numpy array or a single number. Returns: number: a s...
def get_single_value(value): if not all_elements_equal(value): raise ValueError('Not all values are equal to each other.') if is_scalar(value): return value return value.item(0)
623,850
Disable all logging temporarily. A context manager that will prevent any logging messages triggered during the body from being processed. Args: highest_level: the maximum logging level that is being blocked
def all_logging_disabled(highest_level=logging.CRITICAL): previous_level = logging.root.manager.disable logging.disable(highest_level) try: yield finally: logging.disable(previous_level)
623,851
Transform a covariance matrix into a correlations matrix. This can be seen as dividing a covariance matrix by the outer product of the diagonal. As post processing we replace the infinities and the NaNs with zeros and clip the result to [-1, 1]. Args: covariance (ndarray): a matrix of shape (n, p...
def covariance_to_correlations(covariance): diagonal_ind = np.arange(covariance.shape[1]) diagonal_els = covariance[:, diagonal_ind, diagonal_ind] result = covariance / np.sqrt(diagonal_els[:, :, None] * diagonal_els[:, None, :]) result[np.isinf(result)] = 0 return np.clip(np.nan_to_num(result)...
623,853
Multiprocess mapping the given function on the given iterable. This only works in Linux and Mac systems since Windows has no forking capability. On Windows we fall back on single processing. Also, if we reach memory limits we fall back on single cpu processing. Args: func (func): the function to a...
def multiprocess_mapping(func, iterable): if os.name == 'nt': # In Windows there is no fork. return list(map(func, iterable)) try: p = multiprocessing.Pool() return_data = list(p.imap(func, iterable)) p.close() p.join() return return_data except OSError:...
623,854
Parse the given OpenCL string to a single SimpleCLFunction. If the string contains more than one function, we will return only the last, with all the other added as a dependency. Args: cl_code (str): the input string containing one or more functions. dependencies (Iterable[CLCodeObject]): ...
def parse_cl_function(cl_code, dependencies=()): from mot.lib.cl_function import SimpleCLFunction def separate_cl_functions(input_str): class Semantics: def __init__(self): self._functions = [] def result(self, ast): return self._f...
623,855
Split an CL function into a return type, function name, parameters list and the body. Args: cl_str (str): the CL code to parse and plit into components Returns: tuple: string elements for the return type, function name, parameter list and the body
def split_cl_function(cl_str): class Semantics: def __init__(self): self._return_type = '' self._function_name = '' self._parameter_list = [] self._cl_body = '' def result(self, ast): return self._return_type, self._function_name, se...
623,856
Storage unit for an OpenCL environment. Args: platform (pyopencl platform): An PyOpenCL platform. device (pyopencl device): An PyOpenCL device
def __init__(self, platform, device): self._platform = platform self._device = device if (self._platform, self._device) not in _context_cache: context = cl.Context([device]) _context_cache[(self._platform, self._device)] = context self._context = _conte...
623,858
Get a sample generator from the given polymorphic input. Args: samples (ndarray, dict or generator): either an matrix of shape (d, p, n) with d problems, p parameters and n samples, or a dictionary with for every parameter a matrix with shape (d, n) or, finally, a generator function...
def _get_sample_generator(samples): if isinstance(samples, Mapping): def samples_generator(): for ind in range(samples[list(samples.keys())[0]].shape[0]): yield np.array([samples[s][ind, :] for s in sorted(samples)]) elif isinstance(samples, np.ndarray): def samp...
623,870
A kernel input scalar. This will insert the given value directly into the kernel's source code, and will not load it as a buffer. Args: value (number): the number to insert into the kernel as a scalar. ctype (str): the desired c-type for in use in the kernel, like ``int``, ``fl...
def __init__(self, value, ctype=None): if isinstance(value, str) and value == 'INFINITY': self._value = np.inf elif isinstance(value, str) and value == '-INFINITY': self._value = -np.inf else: self._value = np.array(value) self._ctype = ctype ...
623,894
Adds a private memory array of the indicated size to the kernel data elements. This is useful if you want to have private memory arrays in kernel data structs. Args: nmr_items (int): the size of the private memory array ctype (str): the desired c-type for this local memory obje...
def __init__(self, nmr_items, ctype): self._ctype = ctype self._mot_float_dtype = None self._nmr_items = nmr_items
623,900
Calculates the mean and the standard deviation of the given samples. Args: samples (ndarray): a one or two dimensional array. If one dimensional we calculate the fit using all values. If two dimensional, we fit the Gaussian for every set of samples over the first dimension. ddof (int): ...
def fit_gaussian(samples, ddof=0): if len(samples.shape) == 1: return np.mean(samples), np.std(samples, ddof=ddof) return np.mean(samples, axis=1), np.std(samples, axis=1, ddof=ddof)
623,922
Compute the circular mean for samples in a range Args: samples (ndarray): a one or two dimensional array. If one dimensional we calculate the fit using all values. If two dimensional, we fit the Gaussian for every set of samples over the first dimension. high (float): The maximum wrap p...
def fit_circular_gaussian(samples, high=np.pi, low=0): cl_func = SimpleCLFunction.from_string() def run_cl(samples): data = {'samples': Array(samples, 'mot_float_type'), 'means': Zeros(samples.shape[0], 'mot_float_type'), 'stds': Zeros(samples.shape[0], 'mot_float_t...
623,923
The partial derivative with respect to the mean. Args: mu (float): the mean of the truncated normal sigma (float): the std of the truncated normal low (float): the lower truncation bound high (float): the upper truncation bound data (ndarray): the one...
def partial_derivative_mu(mu, sigma, low, high, data): pd_mu = np.sum(data - mu) / sigma ** 2 pd_mu -= len(data) * ((norm.pdf(low, mu, sigma) - norm.pdf(high, mu, sigma)) / (norm.cdf(high, mu, sigma) - norm.cdf(low, mu, sigma))) return -pd_mu
623,931
The partial derivative with respect to the standard deviation. Args: mu (float): the mean of the truncated normal sigma (float): the std of the truncated normal low (float): the lower truncation bound high (float): the upper truncation bound data (nda...
def partial_derivative_sigma(mu, sigma, low, high, data): pd_sigma = np.sum(-(1 / sigma) + ((data - mu) ** 2 / (sigma ** 3))) pd_sigma -= len(data) * (((low - mu) * norm.pdf(low, mu, sigma) - (high - mu) * norm.pdf(high, mu, sigma)) / (sigma * (norm.cdf(high, mu...
623,932
A CL functions for calculating the Euclidian distance between n values. Args: memspace (str): The memory space of the memtyped array (private, constant, global). memtype (str): the memory type to use, double, float, mot_float_type, ...
def __init__(self, memspace='private', memtype='mot_float_type'): super().__init__( memtype, self.__class__.__name__ + '_' + memspace + '_' + memtype, [], resource_filename('mot', 'data/opencl/euclidian_norm.cl'), var_replace_dict={'MEMSPACE':...
623,934
The NMSimplex algorithm as a reusable library component. Args: function_name (str): the name of the evaluation function to call, defaults to 'evaluate'. This should point to a function with signature: ``double evaluate(local mot_float_type* x, void* data_void);`...
def __init__(self, function_name): params = { 'FUNCTION_NAME': function_name } super().__init__( 'int', 'lib_nmsimplex', [], resource_filename('mot', 'data/opencl/lib_nmsimplex.cl'), var_replace_dict=params)
623,936
Return a dictionary with the default options for the given minimization method. Args: method (str): the name of the method we want the options off Returns: dict: a dictionary with the default options
def get_minimizer_options(method): if method == 'Powell': return {'patience': 2, 'patience_line_search': None, 'reset_method': 'EXTRAPOLATED_POINT'} elif method == 'Nelder-Mead': return {'patience': 200, 'alpha': 1.0, 'beta': 0.5, 'gamma': 2....
623,952
Clean the given input options. This will make sure that all options are present, either with their default values or with the given values, and that no other options are present then those supported. Args: method (str): the method name provided_options (dict): the given options Return...
def _clean_options(method, provided_options): provided_options = provided_options or {} default_options = get_minimizer_options(method) result = {} for name, default in default_options.items(): if name in provided_options: result[name] = provided_options[name] else: ...
623,953
Get a numerical differentiated Jacobian function. This computes the Jacobian of the observations (function vector) with respect to the parameters. Args: eval_func (mot.lib.cl_function.CLFunction): the evaluation function nmr_params (int): the number of parameters nmr_observations (int)...
def _lm_numdiff_jacobian(eval_func, nmr_params, nmr_observations): return SimpleCLFunction.from_string(r + str(nmr_params) + + str(nmr_observations) + , dependencies=[eval_func, SimpleCLFunction.from_string( + str(nmr_observations) + + eval_func.get_cl_function_name() + + eval_func.get_cl_function_name() + ...
623,955
Parse the given CL function into a SimpleCLFunction object. Args: cl_function (str): the function we wish to turn into an object dependencies (list or tuple of CLLibrary): The list of CL libraries this function depends on Returns: SimpleCLFunction: the CL data type ...
def from_string(cls, cl_function, dependencies=(), nmr_constraints=None): return_type, function_name, parameter_list, body = split_cl_function(cl_function) return SimpleConstraintFunction(return_type, function_name, parameter_list, body, dependencies=dependencies, ...
623,958
Create a CL function for a library function. These functions are not meant to be optimized, but can be used a helper functions in models. Args: cl_function_name (str): The name of the CL function cl_code_file (str): The location of the code file var_replace_dict (di...
def __init__(self, return_type, cl_function_name, parameter_list, cl_code_file, var_replace_dict=None, **kwargs): self._var_replace_dict = var_replace_dict with open(os.path.abspath(cl_code_file), 'r') as f: code = f.read() if var_replace_dict is not None:...
623,971
Get the MCMC algorithm as a computable function. Args: nmr_samples (int): the number of samples we will draw thinning (int): the thinning factor we want to use return_output (boolean): if the kernel should return output Returns: mot.lib.cl_function.CLFun...
def _get_compute_func(self, nmr_samples, thinning, return_output): cl_func = + ( if return_output else '') + if return_output: cl_func += + str(thinning) + + str(thinning) + + str(thinning) + + str(self._nmr_params) + + str(thinning) + + str(nmr_samples) + cl_func +...
623,981
Download a song from a Google Music library. Parameters: song (dict): A song dict. Returns: tuple: Song content as bytestring, suggested filename.
def download(self, song): song_id = song['id'] response = self._call( mm_calls.Export, self.uploader_id, song_id) audio = response.body suggested_filename = unquote( response.headers['Content-Disposition'].split("filename*=UTF-8''")[-1] ) return (audio, suggested_filename)
624,011
Get a paged iterator of Music Library songs. Parameters: continuation_token (str, Optional): The token of the page to return. Default: Not sent to get first page. export_type (int, Optional): The type of tracks to return. 1 for all tracks, 2 for promotional and purchased. Default: ``1`` Yields: l...
def songs_iter(self, *, continuation_token=None, export_type=1): def track_info_to_dict(track_info): return dict( (field.name, value) for field, value in track_info.ListFields() ) while True: response = self._call( mm_calls.ExportIDs, self.uploader_id, continuation_token=continuati...
624,014
Log in to Google Music. Parameters: username (str, Optional): Your Google Music username. Used for keeping stored OAuth tokens for multiple accounts separate. device_id (str, Optional): A mobile device ID or music manager uploader ID. Default: MAC address is used. token (dict, Optional): An OAuth to...
def login(self, username, *, token=None): self._username = username self._oauth(username, token=token) return self.is_authenticated
624,018
Log in to Google Music with a different user. Parameters: username (str, Optional): Your Google Music username. Used for keeping stored OAuth tokens for multiple accounts separate. token (dict, Optional): An OAuth token compatible with ``requests-oauthlib``. Returns: bool: ``True`` if successfully au...
def switch_user(self, username='', *, token=None): if self.logout(): return self.login(username, token=token) return False
624,019
Get information about an album. Parameters: album_id (str): An album ID. Album IDs start with a 'B'. include_description (bool, Optional): Include description of the album in the returned dict. include_songs (bool, Optional): Include songs from the album in the returned dict. Default: ``True``. Retur...
def album(self, album_id, *, include_description=True, include_songs=True): response = self._call( mc_calls.FetchAlbum, album_id, include_description=include_description, include_tracks=include_songs ) album_info = response.body return album_info
624,032
Get information about an artist. Parameters: artist_id (str): An artist ID. Artist IDs start with an 'A'. include_albums (bool, Optional): Include albums by the artist in returned dict. Default: ``True``. num_related_artists (int, Optional): Include up to given number of related artists in returned dict...
def artist( self, artist_id, *, include_albums=True, num_related_artists=5, num_top_tracks=5 ): response = self._call( mc_calls.FetchArtist, artist_id, include_albums=include_albums, num_related_artists=num_related_artists, num_top_tracks=num_top_tracks ) artist_info = response.body retur...
624,033
Get the podcasts for a genre from the Podcasts browse tab. Parameters: podcast_genre_id (str, Optional): A podcast genre ID as found in :meth:`browse_podcasts_genres`. Default: ``'JZCpodcasttopchartall'``. Returns: list: Podcast dicts.
def browse_podcasts(self, podcast_genre_id='JZCpodcasttopchartall'): response = self._call( mc_calls.PodcastBrowse, podcast_genre_id=podcast_genre_id ) podcast_series_list = response.body.get('series', []) return podcast_series_list
624,034
Get the stations for a category from Browse Stations. Parameters: station_category_id (str): A station category ID as found with :meth:`browse_stations_categories`. Returns: list: Station dicts.
def browse_stations(self, station_category_id): response = self._call( mc_calls.BrowseStations, station_category_id ) stations = response.body.get('stations', []) return stations
624,036
Set device used by :class:`MobileClient` instance. Parameters: device (dict): A device dict as returned by :meth:`devices`.
def device_set(self, device): if device['id'].startswith('0x'): self.device_id = device['id'][2:] elif device['id'].startswith('ios:'): self.device_id = device['id'].replace(':', '') else: self.device_id = device['id']
624,039
Get a listing of song genres. Parameters: parent_genre_id (str, Optional): A genre ID. If given, a listing of this genre's sub-genres is returned. Returns: list: Genre dicts.
def explore_genres(self, parent_genre_id=None): response = self._call( mc_calls.ExploreGenres, parent_genre_id ) genre_list = response.body.get('genres', []) return genre_list
624,041
Get a listing of explore tabs. Parameters: num_items (int, Optional): Number of items per tab to return. Default: ``100`` genre_id (genre_id, Optional): Genre ID from :meth:`explore_genres` to explore. Default: ``None``. Returns: dict: Explore tabs content.
def explore_tabs(self, *, num_items=100, genre_id=None): response = self._call( mc_calls.ExploreTabs, num_items=num_items, genre_id=genre_id ) tab_list = response.body.get('tabs', []) explore_tabs = {} for tab in tab_list: explore_tabs[tab['tab_type'].lower()] = tab return explore_tabs
624,042
Get information about a playlist song. Note: This returns the playlist entry information only. For full song metadata, use :meth:`song` with the ``'trackId'`` field. Parameters: playlist_song_id (str): A playlist song ID. Returns: dict: Playlist song information.
def playlist_song(self, playlist_song_id): playlist_song_info = next( ( playlist_song for playlist in self.playlists(include_songs=True) for playlist_song in playlist['tracks'] if playlist_song['id'] == playlist_song_id ), None ) return playlist_song_info
624,046
Delete song from playlist. Parameters: playlist_song (str): A playlist song dict. Returns: dict: Playlist dict including songs.
def playlist_song_delete(self, playlist_song): self.playlist_songs_delete([playlist_song]) return self.playlist(playlist_song['playlistId'], include_songs=True)
624,049
Delete songs from playlist. Parameters: playlist_songs (list): A list of playlist song dicts. Returns: dict: Playlist dict including songs.
def playlist_songs_delete(self, playlist_songs): if not more_itertools.all_equal( playlist_song['playlistId'] for playlist_song in playlist_songs ): raise ValueError( "All 'playlist_songs' must be from the same playlist." ) mutations = [mc_calls.PlaylistEntriesBatch.delete(playlist_song['id']...
624,050
Get information about a playlist. Parameters: playlist_id (str): A playlist ID. include_songs (bool, Optional): Include songs from the playlist in the returned dict. Default: ``False`` Returns: dict: Playlist information.
def playlist(self, playlist_id, *, include_songs=False): playlist_info = next( ( playlist for playlist in self.playlists(include_songs=include_songs) if playlist['id'] == playlist_id ), None ) return playlist_info
624,054
Create a playlist. Parameters: name (str): Name to give the playlist. description (str): Description to give the playlist. make_public (bool, Optional): If ``True`` and account has a subscription, make playlist public. Default: ``False`` songs (list, Optional): A list of song dicts to add to the ...
def playlist_create( self, name, description='', *, make_public=False, songs=None ): share_state = 'PUBLIC' if make_public else 'PRIVATE' playlist = self._call( mc_calls.PlaylistsCreate, name, description, share_state ).body if songs: playlist = self.playlist_songs_add(songs, p...
624,055
Edit playlist(s). Parameters: playlist (dict): A playlist dict. name (str): Name to give the playlist. description (str, Optional): Description to give the playlist. make_public (bool, Optional): If ``True`` and account has a subscription, make playlist public. Default: ``False`` Returns: d...
def playlist_edit(self, playlist, *, name=None, description=None, public=None): if all( value is None for value in (name, description, public) ): raise ValueError( 'At least one of name, description, or public must be provided' ) playlist_id = playlist['id'] playlist = self.playlist(playlis...
624,056
Subscribe to a public playlist. Parameters: playlist (dict): A public playlist dict. Returns: dict: Playlist information.
def playlist_subscribe(self, playlist): mutation = mc_calls.PlaylistBatch.create( playlist['name'], playlist['description'], 'SHARED', owner_name=playlist.get('ownerName', ''), share_token=playlist['shareToken'] ) response_body = self._call( mc_calls.PlaylistBatch, mutation ).body p...
624,057
Get a listing of library playlists. Parameters: include_songs (bool, Optional): Include songs in the returned playlist dicts. Default: ``False``. Returns: list: A list of playlist dicts.
def playlists(self, *, include_songs=False): playlist_list = [] for chunk in self.playlists_iter(page_size=49995): for playlist in chunk: if include_songs: playlist['tracks'] = self.playlist_songs(playlist) playlist_list.append(playlist) return playlist_list
624,058
Get a paged iterator of library playlists. Parameters: start_token (str): The token of the page to return. Default: Not sent to get first page. page_size (int, Optional): The maximum number of results per returned page. Max allowed is ``49995``. Default: ``250`` Yields: list: Playlist dicts.
def playlists_iter(self, *, start_token=None, page_size=250): start_token = None while True: response = self._call( mc_calls.PlaylistFeed, max_results=page_size, start_token=start_token ) items = response.body.get('data', {}).get('items', []) if items: yield items start_token =...
624,059
Get information about a podcast series. Parameters: podcast_series_id (str): A podcast series ID. max_episodes (int, Optional): Include up to given number of episodes in returned dict. Default: ``50`` Returns: dict: Podcast series information.
def podcast(self, podcast_series_id, *, max_episodes=50): podcast_info = self._call( mc_calls.PodcastFetchSeries, podcast_series_id, max_episodes=max_episodes ).body return podcast_info
624,060
Get a paged iterator of subscribed podcast series. Parameters: device_id (str, Optional): A mobile device ID. Default: Use ``device_id`` of the :class:`MobileClient` instance. page_size (int, Optional): The maximum number of results per returned page. Max allowed is ``49995``. Default: ``250`` Y...
def podcasts_iter(self, *, device_id=None, page_size=250): if device_id is None: device_id = self.device_id start_token = None prev_items = None while True: response = self._call( mc_calls.PodcastSeries, device_id, max_results=page_size, start_token=start_token ) items = respon...
624,062
Get information about a podcast_episode. Parameters: podcast_episode_id (str): A podcast episode ID. Returns: dict: Podcast episode information.
def podcast_episode(self, podcast_episode_id): response = self._call( mc_calls.PodcastFetchEpisode, podcast_episode_id ) podcast_episode_info = [ podcast_episode for podcast_episode in response.body if not podcast_episode['deleted'] ] return podcast_episode_info
624,063
Get a paged iterator of podcast episode for all subscribed podcasts. Parameters: device_id (str, Optional): A mobile device ID. Default: Use ``device_id`` of the :class:`MobileClient` instance. page_size (int, Optional): The maximum number of results per returned page. Max allowed is ``49995``. Def...
def podcast_episodes_iter(self, *, device_id=None, page_size=250): if device_id is None: device_id = self.device_id start_token = None prev_items = None while True: response = self._call( mc_calls.PodcastEpisode, device_id, max_results=page_size, start_token=start_token ) items...
624,065
Get search query suggestions for query. Parameters: query (str): Search text. Returns: list: Suggested query strings.
def search_suggestion(self, query): response = self._call( mc_calls.QuerySuggestion, query ) suggested_queries = response.body.get('suggested_queries', []) return [ suggested_query['suggestion_string'] for suggested_query in suggested_queries ]
624,069
Get a listing of situations. Parameters: tz_offset (int, Optional): A time zone offset from UTC in seconds.
def situations(self, *, tz_offset=None): response = self._call( mc_calls.ListenNowSituations, tz_offset ) situation_list = response.body.get('situations', []) return situation_list
624,073
Get information about a song. Parameters: song_id (str): A song ID. Returns: dict: Song information.
def song(self, song_id): if song_id.startswith('T'): song_info = self._call( mc_calls.FetchTrack, song_id ).body else: song_info = next( ( song for song in self.songs() if song['id'] == song_id ), None ) return song_info
624,074
Add store songs to your library. Parameters: songs (list): A list of store song dicts. Returns: list: Songs' library IDs.
def songs_add(self, songs): mutations = [mc_calls.TrackBatch.add(song) for song in songs] response = self._call( mc_calls.TrackBatch, mutations ) success_ids = [ res['id'] for res in response.body['mutate_response'] if res['response_code'] == 'OK' ] return success_ids
624,075
Delete songs from library. Parameters: song (list): A list of song dicts. Returns: list: Successfully deleted song IDs.
def songs_delete(self, songs): mutations = [mc_calls.TrackBatch.delete(song['id']) for song in songs] response = self._call( mc_calls.TrackBatch, mutations ) success_ids = [ res['id'] for res in response.body['mutate_response'] if res['response_code'] == 'OK' ] # TODO: Report failures. ...
624,076
Add play to song play count. Parameters: song (dict): A song dict. Returns: bool: ``True`` if successful, ``False`` if not.
def song_play(self, song): if 'storeId' in song: song_id = song['storeId'] elif 'trackId' in song: song_id = song['trackId'] else: song_id = song['id'] song_duration = song['durationMillis'] event = mc_calls.ActivityRecordRealtime.play(song_id, song_duration) response = self._call( mc_call...
624,077
Rate song. Parameters: song (dict): A song dict. rating (int): 0 (not rated), 1 (thumbs down), or 5 (thumbs up). Returns: bool: ``True`` if successful, ``False`` if not.
def song_rate(self, song, rating): if 'storeId' in song: song_id = song['storeId'] elif 'trackId' in song: song_id = song['trackId'] else: song_id = song['id'] event = mc_calls.ActivityRecordRealtime.rate(song_id, rating) response = self._call( mc_calls.ActivityRecordRealtime, event ) ...
624,078
Get a paged iterator of library songs. Parameters: page_size (int, Optional): The maximum number of results per returned page. Max allowed is ``49995``. Default: ``250`` Yields: list: Song dicts.
def songs_iter(self, *, page_size=250): start_token = None while True: response = self._call( mc_calls.TrackFeed, max_results=page_size, start_token=start_token ) items = response.body.get('data', {}).get('items', []) if items: yield items start_token = response.body.get('nextP...
624,080
Get information about a station. Parameters: station_id (str): A station ID. Use 'IFL' for I'm Feeling Lucky. num_songs (int, Optional): The maximum number of songs to return from the station. Default: ``25`` recently_played (list, Optional): A list of dicts in the form of {'id': '', 'type'} where `...
def station(self, station_id, *, num_songs=25, recently_played=None): station_info = { 'station_id': station_id, 'num_entries': num_songs, 'library_content_only': False } if recently_played is not None: station_info['recently_played'] = recently_played response = self._call( mc_calls.RadioS...
624,081
Generate stations. Note: A Google Music subscription is required. Parameters: num_songs (int, Optional): The total number of songs to return. Default: ``25`` num_stations (int, Optional): The number of stations to return when no station_infos is provided. Default: ``5`` Returns: list: Station i...
def station_feed(self, *, num_songs=25, num_stations=4): response = self._call( mc_calls.RadioStationFeed, num_entries=num_songs, num_stations=num_stations ) station_feed = response.body.get('data', {}).get('stations', []) return station_feed
624,082
Get a listing of songs from a station. Parameters: station (str): A station dict. num_songs (int, Optional): The maximum number of songs to return from the station. Default: ``25`` recently_played (list, Optional): A list of dicts in the form of {'id': '', 'type'} where ``id`` is a song ID and ``type`` ...
def station_songs(self, station, *, num_songs=25, recently_played=None): station_id = station['id'] station = self.station( station_id, num_songs=num_songs, recently_played=recently_played ) return station.get('tracks', [])
624,083
Get a listing of library stations. The listing can contain stations added to the library and generated from the library. Parameters: generated (bool, Optional): Include generated stations. Default: True library (bool, Optional): Include library stations. Default: True Returns: list: Station in...
def stations(self, *, generated=True, library=True): station_list = [] for chunk in self.stations_iter(page_size=49995): for station in chunk: if ( (generated and not station.get('inLibrary')) or (library and station.get('inLibrary')) ): station_list.append(station) return station_l...
624,084
Get a paged iterator of library stations. Parameters: page_size (int, Optional): The maximum number of results per returned page. Max allowed is ``49995``. Default: ``250`` Yields: list: Station dicts.
def stations_iter(self, *, page_size=250): start_token = None while True: response = self._call( mc_calls.RadioStation, max_results=page_size, start_token=start_token ) yield response.body.get('data', {}).get('items', []) start_token = response.body.get('nextPageToken') if start_tok...
624,085
Get a listing of 'Thumbs Up' store songs. Parameters: library (bool, Optional): Include 'Thumbs Up' songs from library. Default: True generated (bool, Optional): Include 'Thumbs Up' songs from store. Default: True Returns: list: Dicts of 'Thumbs Up' songs.
def thumbs_up_songs(self, *, library=True, store=True): thumbs_up_songs = [] if library is True: thumbs_up_songs.extend( song for song in self.songs() if song.get('rating', '0') == '5' ) if store is True: response = self._call(mc_calls.EphemeralTop) thumbs_up_songs.extend(response.bo...
624,088
Get a listing of top charts for a top chart genre. Parameters: genre_id (str): A top chart genre ID as found with :meth:`top_charts_genres`.
def top_charts_for_genre(self, genre_id): response = self._call(mc_calls.BrowseTopChartForGenre, genre_id) top_chart_for_genre = response.body return top_chart_for_genre
624,090
Search for a record on the remote and return the results. Args: five9 (five9.Five9): The authenticated Five9 remote. filters (dict): A dictionary of search parameters, keyed by the name of the field to search. This should conform to the schema defined in ...
def search(cls, five9, filters): return cls._name_search(five9.configuration.getWebConnectors, filters)
625,051
Return a record singleton for the ID. Args: five9 (five9.Five9): The authenticated Five9 remote. external_id (mixed): The identified on Five9. This should be the value that is in the ``__uid_field__`` field on the record. Returns: BaseModel: The reco...
def read(cls, five9, external_id): results = cls.search(five9, {cls.__uid_field__: external_id}) if not results: return None return results[0]
625,053
Update the current memory record with the given data dict. Args: data (dict): Data dictionary to update the record attributes with.
def update(self, data): for key, value in data.items(): setattr(self, key, value)
625,054
Helper for search methods that use name filters. Args: method (callable): The Five9 API method to call with the name filters. filters (dict): A dictionary of search parameters, keyed by the name of the field to search. This should conform to the ...
def _name_search(cls, method, filters): filters = cls._get_name_filters(filters) return [ cls.deserialize(cls._zeep_to_dict(row)) for row in method(filters) ]
625,059
Create a field mapping for use in API updates and creates. Args: record (BaseModel): Record that should be mapped. keys (list[str]): Fields that should be mapped as keys. Returns: dict: Dictionary with keys: * ``field_mappings``: Field mappings as r...
def create_mapping(record, keys): ordered = OrderedDict() field_mappings = [] for key, value in record.items(): ordered[key] = value field_mappings.append({ 'columnNumber': len(ordered), # Five9 is not zero indexed. 'fieldName':...
625,076
Search Five9 given a filter. Args: filters (dict): A dictionary of search strings, keyed by the name of the field to search. Returns: Environment: An environment representing the recordset.
def search(self, filters): records = self.__model__.search(self.__five9__, filters) return self.__class__( self.__five9__, self.__model__, records, )
625,091
Search for a record on the remote and return the results. Args: five9 (five9.Five9): The authenticated Five9 remote. filters (dict): A dictionary of search parameters, keyed by the name of the field to search. This should conform to the schema defined in ...
def search(cls, five9, filters): return cls._name_search(five9.configuration.getDispositions, filters)
625,117
Call the supplied function with the supplied arguments, catching and returning any exception that it throws. Arguments: func: the function to run. *args: positional arguments to pass into the function. **kwargs: keyword arguments to pass into the function. Returns: If the fu...
def catch(func, *args, **kwargs): try: func(*args, **kwargs) except Exception as e: return e
625,649
Call the supplied function with the supplied arguments, and return the total execution time as a float in seconds. The precision of the returned value depends on the precision of `time.time()` on your platform. Arguments: func: the function to run. *args: positional arguments to pass i...
def time(func, *args, **kwargs): start_time = time_module.time() func(*args, **kwargs) end_time = time_module.time() return end_time - start_time
625,650
Carry out a test run with the supplied list of plugin instances. The plugins are expected to identify the object to run. Parameters: plugin_list: a list of plugin instances (objects which implement some subset of PluginInterface) Returns: exit code as an integer. The default behaviour (whic...
def run_with_plugins(plugin_list): composite = core.PluginComposite(plugin_list) to_run = composite.get_object_to_run() test_run = core.TestRun(to_run, composite) test_run.run() return composite.get_exit_code()
625,760
Find stations for given queries Args: station (str): search query limit (int): limit number of results
def stations(self, station, limit=10): query = { 'start': 1, 'S': station + '?', 'REQ0JourneyStopsB': limit } rsp = requests.get('http://reiseauskunft.bahn.de/bin/ajax-getstop.exe/dn', params=query) return parse_stations(rsp.text)
625,890
Find connections between two stations Args: origin (str): origin station destination (str): destination station dt (datetime): date and time for query only_direct (bool): only direct connections
def connections(self, origin, destination, dt=datetime.now(), only_direct=False): query = { 'S': origin, 'Z': destination, 'date': dt.strftime("%d.%m.%y"), 'time': dt.strftime("%H:%M"), 'start': 1, 'REQ0JourneyProduct_opt0': 1 if o...
625,891
Initialize the parts needed to start making database connections parameters: config - the complete config for the app. If a real app, this would be where a logger or other resources could be found. local_config - this is the namespace within th...
def __init__(self, config, local_config): super(Postgres, self).__init__() self.dsn = ("host=%(database_host)s " "dbname=%(database_name)s " "port=%(database_port)s " "user=%(database_user)s " "password=%(database_p...
625,952
return a named connection. This function will return a named connection by either finding one in its pool by the name or creating a new one. If no name is given, it will use the name of the current executing thread as the name of the connection. parameters: name - ...
def connection(self, name=None): if not name: name = threading.currentThread().getName() if name in self.pool: return self.pool[name] self.pool[name] = FakeDatabaseConnection(self.dsn) return self.pool[name]
625,955
the constructor allows for initialization from another mapping. parameters: initializer - a mapping of keys and values to be added to this mapping.
def __init__(self, initializer=None): self.__dict__['_key_order'] = OrderedSet() if isinstance(initializer, collections.Mapping): for key, value in iteritems_breadth_first( initializer, include_dicts=True ): if isinstance(v...
626,004
Python 2.4 compatible memoize decorator. It creates a cache that has a maximum size. If the cache exceeds the max, it is thrown out and a new one made. With such behavior, it is wise to set the cache just a little larger that the maximum expected need. Parameters: max_cache_size - the size to w...
def memoize(max_cache_size=1000): def wrapper(f): @wraps(f) def fn(*args, **kwargs): if kwargs: key = (args, tuple(kwargs.items())) else: key = args try: return fn.cache[key] except KeyError: ...
626,018
outputs a usage tip and the list of acceptable commands. This is useful as the output of the 'help' option. parameters: output_stream - an open file-like object suitable for use as the target of a print function
def output_summary(self, output_stream=sys.stdout): if self.app_name or self.app_description: print('Application: ', end='', file=output_stream) if self.app_name: print(self.app_name, self.app_version, file=output_stream) if self.app_description: prin...
626,038
write a config file to the pathname specified in the parameter. The file extention determines the type of file written and must match a registered type. parameters: config_pathname - the full path and filename of the target config file.
def print_conf(self): config_file_type = self._get_option('admin.print_conf').value @contextlib.contextmanager def stdout_opener(): yield sys.stdout skip_keys = [ k for (k, v) in six.iteritems(self.option_definitions) if isinsta...
626,039
write a config file to the pathname specified in the parameter. The file extention determines the type of file written and must match a registered type. parameters: config_pathname - the full path and filename of the target config file.
def dump_conf(self, config_pathname=None): if not config_pathname: config_pathname = self._get_option('admin.dump_conf').value opener = functools.partial(open, config_pathname, 'w') config_file_type = os.path.splitext(config_pathname)[1][1:] skip_keys = [ ...
626,040
write out the current configuration to a log-like object. parameters: logger - a object that implements a method called 'info' with the same semantics as the call to 'logger.info
def log_config(self, logger): logger.info("app_name: %s", self.app_name) logger.info("app_version: %s", self.app_version) logger.info("current configuration:") config = [(key, self.option_definitions[key].value) for key in self.option_definitions.keys_breadth_...
626,042
return upscaled image array Arguments: image -- a (H,W,C) numpy.ndarray ratio -- scaling factor (>1)
def upscale(image, ratio): if not isinstance(image, np.ndarray): raise ValueError('Expected ndarray') if ratio < 1: raise ValueError('Ratio must be greater than 1 (ratio=%f)' % ratio) width = int(math.floor(image.shape[1] * ratio)) height = int(math.floor(image.shape[0] * ratio)) ...
626,657
Resizes an image and returns it as a np.array Arguments: image -- a PIL.Image or numpy.ndarray height -- height of new image width -- width of new image Keyword Arguments: channels -- channels of new image (stays unchanged if not specified) resize_mode -- can be crop, squash, fill or half_cr...
def resize_image(image, height, width, channels=None, resize_mode=None ): if resize_mode is None: resize_mode = 'squash' if resize_mode not in ['crop', 'squash', 'fill', 'half_crop']: raise ValueError('resize_mode "%s" not supported' % resi...
626,658
Returns an image embedded in HTML base64 format (Based on Caffe's web_demo) Arguments: image -- a PIL.Image or np.ndarray
def embed_image_html(image): if image is None: return None elif isinstance(image, PIL.Image.Image): pass elif isinstance(image, np.ndarray): image = PIL.Image.fromarray(image) else: raise ValueError('image must be a PIL.Image or a np.ndarray') # Read format from...
626,659
Draw rectangles on the image for the bounding boxes Returns a PIL.Image Arguments: image -- input image bboxes -- bounding boxes in the [((l, t), (r, b)), ...] format Keyword arguments: color -- color to draw the rectangles width -- line width of the rectangles Example: image = Image...
def add_bboxes_to_image(image, bboxes, color='red', width=1): def expanded_bbox(bbox, n): l = min(bbox[0][0], bbox[1][0]) r = max(bbox[0][0], bbox[1][0]) t = min(bbox[0][1], bbox[1][1]) b = max(bbox[0][1], bbox[1][1]) return ((l - n, t - n), (r + n, b + n)) ...
626,660
Returns a vis_square for the given layer data Arguments: data -- a np.ndarray Keyword arguments: allow_heatmap -- if True, convert single channel images to heatmaps normalize -- whether to normalize the data when visualizing max_width -- maximum width for the vis_square
def get_layer_vis_square(data, allow_heatmap=True, normalize=True, min_img_dim=100, max_width=1200, channel_order='RGB', colormap='jet', ): ...
626,661
Return a colormap as (redmap, greenmap, bluemap) Arguments: name -- the name of the colormap. If unrecognized, will default to 'jet'.
def get_color_map(name): redmap = [0] greenmap = [0] bluemap = [0] if name == 'white': # essentially a noop redmap = [0, 1] greenmap = [0, 1] bluemap = [0, 1] elif name == 'simple': redmap = [0, 1, 1, 1] greenmap = [0, 0, 1, 1] bluemap = [...
626,664
Parse a date expression into a tuple of: (start_date, span_type, span_format) Arguments: datestr -- A date specification, in the format of YYYY-MM-DD (dashes optional)
def parse_date(datestr): match = re.match( r'([0-9]{4})(-?([0-9]{1,2}))?(-?([0-9]{1,2}))?(_w)?$', datestr) if not match: return (arrow.get(datestr, tzinfo=config.timezone).replace(tzinfo=config.timezone), 'day', 'YYYY-MM-DD') year, month, day,...
627,550
Shorthand for returning a URL for the requested static file. Arguments: path -- the path to the file (relative to the static files directory) absolute -- whether the link should be absolute or relative
def static_url(path, absolute=False): if os.sep != '/': path = '/'.join(path.split(os.sep)) return flask.url_for('static', filename=path, _external=absolute)
627,553