Search is not available for this dataset
text
stringlengths
75
104k
def save_results(self, output_dir='.', prefix='', prefix_sep='_', image_list=None): """ Write out any images generated by the meta-analysis. Args: output_dir (str): folder to write images to prefix (str): all image files will be prepended with this string ...
def transform(foci, mat): """ Convert coordinates from one space to another using provided transformation matrix. """ t = linalg.pinv(mat) foci = np.hstack((foci, np.ones((foci.shape[0], 1)))) return np.dot(foci, t)[:, 0:3]
def xyz_to_mat(foci, xyz_dims=None, mat_dims=None): """ Convert an N x 3 array of XYZ coordinates to matrix indices. """ foci = np.hstack((foci, np.ones((foci.shape[0], 1)))) mat = np.array([[-0.5, 0, 0, 45], [0, 0.5, 0, 63], [0, 0, 0.5, 36]]).T result = np.dot(foci, mat)[:, ::-1] # multiply and revers...
def apply(self, name, foci): """ Apply a named transformation to a set of foci. If the named transformation doesn't exist, return foci untransformed. """ if name in self.transformations: return transform(foci, self.transformations[name]) else: logger.info...
def reset(self): """ Reset/remove all layers, keeping only the initial volume. """ self.layers = {} self.stack = [] self.set_mask() self.n_vox_in_vol = len(np.where(self.current_mask)[0])
def add(self, layers, above=None, below=None): """ Add one or more layers to the stack of masking layers. Args: layers: A string, NiBabel image, list, or dict. If anything other than a dict is passed, assigns sequential layer names based on the current positio...
def remove(self, layers): """ Remove one or more layers from the stack of masking layers. Args: layers: An int, string or list of strings and/or ints. Ints are interpreted as indices in the stack to remove; strings are interpreted as names of layers to remove....
def get_image(self, image, output='vector'): """ A flexible method for transforming between different representations of image data. Args: image: The input image. Can be a string (filename of image), NiBabel image, N-dimensional array (must have same shape as ...
def mask(self, image, nan_to_num=True, layers=None, in_global_mask=False): """ Vectorize an image and mask out all invalid voxels. Args: images: The image to vectorize and mask. Input can be any object handled by get_image(). layers: Which mask layers to use (spe...
def unmask(self, data, layers=None, output='array'): """ Reconstruct a masked vector into the original 3D volume. Args: data: The 1D vector to reconstruct. (Can also be a 2D vector where the second dimension is time, but then output will always be set to 'arra...
def get_mask(self, layers=None, output='vector', in_global_mask=True): """ Set the current mask by taking the conjunction of all specified layers. Args: layers: Which layers to include. See documentation for add() for format. include_global_mask: Whether ...
def get_sphere(coords, r=4, vox_dims=(2, 2, 2), dims=(91, 109, 91)): """ # Return all points within r mm of coordinates. Generates a cube and then discards all points outside sphere. Only returns values that fall within the dimensions of the image.""" r = float(r) xx, yy, zz = [slice(-r / vox_dims[i...
def map_peaks_to_image(peaks, r=4, vox_dims=(2, 2, 2), dims=(91, 109, 91), header=None): """ Take a set of discrete foci (i.e., 2-D array of xyz coordinates) and generate a corresponding image, convolving each focus with a hard sphere of radius r.""" data = np.zeros(dims) for ...
def load_imgs(filenames, masker, nan_to_num=True): """ Load multiple images from file into an ndarray. Args: filenames: A single filename or list of filenames pointing to valid images. masker: A Masker instance. nan_to_num: Optional boolean indicating whether to convert NaNs to zero. ...
def save_img(data, filename, masker, header=None): """ Save a vectorized image to file. """ if not header: header = masker.get_header() header.set_data_dtype(data.dtype) # Avoids loss of precision # Update min/max -- this should happen on save, but doesn't seem to header['cal_max'] = data.m...
def threshold_img(data, threshold, mask=None, mask_out='below'): """ Threshold data, setting all values in the array above/below threshold to zero. Args: data (ndarray): The image data to threshold. threshold (float): Numeric threshold to apply to image. mask (ndarray): Optional 1D-a...
def create_grid(image, scale=4, apply_mask=True, save_file=None): """ Creates an image containing labeled cells in a 3D grid. Args: image: String or nibabel image. The image used to define the grid dimensions. Also used to define the mask to apply to the grid. Only voxels with no...
def set_logging_level(level=None): """Set neurosynth's logging level Args level : str Name of the logging level (warning, error, info, etc) known to logging module. If no level provided, it would get that one from environment variable NEUROSYNTH_LOGLEVEL """ if level is N...
def expand_address(address, languages=None, **kw): """ Expand the given address into one or more normalized strings. Required -------- @param address: the address as either Unicode or a UTF-8 encoded string Options ------- @param languages: a tuple or list of ISO language code strings ...
def normalized_tokens(s, string_options=DEFAULT_STRING_OPTIONS, token_options=DEFAULT_TOKEN_OPTIONS, strip_parentheticals=True, whitespace=False, languages=None): ''' Normalizes a string, tokenizes, and normalizes each token with string and t...
def parse_address(address, language=None, country=None): """ Parse address into components. @param address: the address as either Unicode or a UTF-8 encoded string @param language (optional): language code @param country (optional): country code """ address = safe_decode(address, 'utf-8') ...
def near_dupe_hashes(labels, values, languages=None, **kw): """ Hash the given address into normalized strings that can be used to group similar addresses together for more detailed pairwise comparison. This can be thought of as the blocking function in record linkage or locally-sensitive hashing in the...
def has_api_key(file_name): """ Detect whether the file contains an api key in the Token object that is not 40*'0'. See issue #86. :param file: path-to-file to check :return: boolean """ f = open(file_name, 'r') text = f.read() if re.search(real_api_regex, text) is not None and \ ...
def remove_api_key(file_name): """ Change the api key in the Token object to 40*'0'. See issue #86. :param file: path-to-file to change """ with open(file_name, 'r') as fp: text = fp.read() text = re.sub(real_api_regex, zero_token_string, text) with open(file_name, 'w') as fp: ...
def dict_to_object(item, object_name): """Converts a python dict to a namedtuple, saving memory.""" fields = item.keys() values = item.values() return json.loads(json.dumps(item), object_hook=lambda d: namedtuple(object_name, fields)(*values))
def list_tickers(self, assetType): """Return a list of dicts of metadata tickers for all supported tickers of the specified asset type, as well as metadata about each ticker. This includes supported date range, the exchange the ticker is traded on, and the currency the stock ...
def get_ticker_metadata(self, ticker, fmt='json'): """Return metadata for 1 ticker Use TiingoClient.list_tickers() to get available options Args: ticker (str) : Unique identifier for stock """ url = "tiingo/daily/{}".format(ticker) response = self....
def _invalid_frequency(self, frequency): """ Check to see that frequency was specified correctly :param frequency (string): frequency string :return (boolean): """ is_valid = self._is_eod_frequency(frequency) or re.match(self._frequency_pattern, frequency) return ...
def _get_url(self, ticker, frequency): """ Return url based on frequency. Daily, weekly, or yearly use Tiingo EOD api; anything less than daily uses the iex intraday api. :param ticker (string): ticker to be embedded in the url :param frequency (string): valid frequency per Tiin...
def get_ticker_price(self, ticker, startDate=None, endDate=None, fmt='json', frequency='daily'): """By default, return latest EOD Composite Price for a stock ticker. On average, each feed contains 3 data sources. Supported tickers + Avail...
def get_dataframe(self, tickers, startDate=None, endDate=None, metric_name=None, frequency='daily'): """ Return a pandas.DataFrame of historical prices for one or more ticker symbols. By default, return latest EOD Composite Price for a list of stock tickers. On av...
def get_news(self, tickers=[], tags=[], sources=[], startDate=None, endDate=None, limit=100, offset=0, sortBy="publishedDate", fmt='json'): """Return list of news articles matching given search terms https://api.tiingo.com/docs/tiingo/news # Dates are i...
def get_bulk_news(self, file_id=None, fmt='json'): """Only available to institutional clients. If ID is NOT provided, return array of available file_ids. If ID is provided, provides URL which you can use to download your file, as well as some metadata about that file. ...
def _request(self, method, url, **kwargs): """Make HTTP request and return response object Args: method (str): GET, POST, PUT, DELETE url (str): path appended to the base_url to create request **kwargs: passed directly to a requests.request object ...
async def get_bearer_info(self): """Get the application bearer token from client_id and client_secret.""" if self.client_id is None: raise SpotifyException(_GET_BEARER_ERR % 'client_id') elif self.client_secret is None: raise SpotifyException(_GET_BEARER_ERR % 'client_se...
async def request(self, route, **kwargs): """Make a request to the spotify API with the current bearer credentials. Parameters ---------- route : Union[tuple[str, str], Route] A tuple of the method and url or a :class:`Route` object. kwargs : Any keyword ...
def album(self, spotify_id, market='US'): """Get a spotify album by its ID. Parameters ---------- spotify_id : str The spotify_id to search by. market : Optional[str] An ISO 3166-1 alpha-2 country code. Returns ------- album : Dic...
def album_tracks(self, spotify_id, limit=20, offset=0, market='US'): """Get an albums tracks by an ID. Parameters ---------- spotify_id : str The spotify_id to search by. limit : Optional[int] The maximum number of items to return. Default: 20. Minimum: 1...
def albums(self, spotify_ids, market='US'): """Get a spotify album by its ID. Parameters ---------- spotify_ids : List[str] The spotify_ids to search by. market : Optional[str] An ISO 3166-1 alpha-2 country code. """ route = Route('GET', '...
def artist(self, spotify_id): """Get a spotify artist by their ID. Parameters ---------- spotify_id : str The spotify_id to search by. """ route = Route('GET', '/artists/{spotify_id}', spotify_id=spotify_id) return self.request(route)
def artist_albums(self, spotify_id, include_groups=None, limit=20, offset=0, market='US'): """Get an artists tracks by their ID. Parameters ---------- spotify_id : str The spotify_id to search by. include_groups : INCLUDE_GROUPS_TP INCLUDE_GROUPS ...
def artist_top_tracks(self, spotify_id, country): """Get an artists top tracks per country with their ID. Parameters ---------- spotify_id : str The spotify_id to search by. country : COUNTRY_TP COUNTRY """ route = Route('GET', '/artists/{...
def artist_related_artists(self, spotify_id): """Get related artists for an artist by their ID. Parameters ---------- spotify_id : str The spotify_id to search by. """ route = Route('GET', '/artists/{spotify_id}/related-artists', spotify_id=spotify_id) ...
def artists(self, spotify_ids): """Get a spotify artists by their IDs. Parameters ---------- spotify_id : List[str] The spotify_ids to search with. """ route = Route('GET', '/artists') payload = {'ids': spotify_ids} return self.request(route, ...
def category(self, category_id, country=None, locale=None): """Get a single category used to tag items in Spotify. Parameters ---------- category_id : str The Spotify category ID for the category. country : COUNTRY_TP COUNTRY locale : LOCALE_TP ...
def category_playlists(self, category_id, limit=20, offset=0, country=None): """Get a list of Spotify playlists tagged with a particular category. Parameters ---------- category_id : str The Spotify category ID for the category. limit : Optional[int] The ...
def categories(self, limit=20, offset=0, country=None, locale=None): """Get a list of categories used to tag items in Spotify. Parameters ---------- limit : Optional[int] The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50. offset : Optional[i...
def featured_playlists(self, locale=None, country=None, timestamp=None, limit=20, offset=0): """Get a list of Spotify featured playlists. Parameters ---------- locale : LOCALE_TP LOCALE country : COUNTRY_TP COUNTRY timestamp : TIMESTAMP_TP ...
def new_releases(self, *, country=None, limit=20, offset=0): """Get a list of new album releases featured in Spotify. Parameters ---------- limit : Optional[int] The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50. offset : Optional[int] ...
def recommendations(self, seed_artists, seed_genres, seed_tracks, *, limit=20, market=None, **filters): """Get Recommendations Based on Seeds. Parameters ---------- seed_artists : str A comma separated list of Spotify IDs for seed artists. Up to 5 seed values may be provided...
def following_artists_or_users(self, ids, *, type='artist'): """Check to see if the current user is following one or more artists or other Spotify users. Parameters ---------- ids : List[str] A comma-separated list of the artist or the user Spotify IDs to check. ...
async def get_albums(self, *, limit: Optional[int] = 20, offset: Optional[int] = 0, include_groups=None, market: Optional[str] = None) -> List[Album]: """Get the albums of a Spotify artist. Parameters ---------- limit : Optional[int] The maximum number of items to return. De...
async def get_all_albums(self, *, market='US') -> List[Album]: """loads all of the artists albums, depending on how many the artist has this may be a long operation. Parameters ---------- market : Optional[str] An ISO 3166-1 alpha-2 country code. Returns ---...
async def total_albums(self, *, market: str = None) -> int: """get the total amout of tracks in the album. Parameters ---------- market : Optional[str] An ISO 3166-1 alpha-2 country code. Returns ------- total : int The total amount of al...
async def top_tracks(self, country: str = 'US') -> List[Track]: """Get Spotify catalog information about an artist’s top tracks by country. Parameters ---------- country : str The country to search for, it defaults to 'US'. Returns ------- tracks : L...
async def related_artists(self) -> List[Artist]: """Get Spotify catalog information about artists similar to a given artist. Similarity is based on analysis of the Spotify community’s listening history. Returns ------- artists : List[Artits] The artists deemed simil...
async def currently_playing(self) -> Tuple[Context, Track]: """Get the users currently playing track. Returns ------- context, track : Tuple[Context, Track] A tuple of the context and track. """ data = await self.http.currently_playing() if data.get(...
async def get_player(self) -> Player: """Get information about the users current playback. Returns ------- player : Player A player object representing the current playback. """ self._player = player = Player(self.__client, self, await self.http.current_playe...
async def get_devices(self) -> List[Device]: """Get information about the users avaliable devices. Returns ------- devices : List[Device] The devices the user has available. """ data = await self.http.available_devices() return [Device(item) for item ...
async def recently_played(self) -> List[Dict[str, Union[Track, Context, str]]]: """Get tracks from the current users recently played tracks. Returns ------- playlist_history : List[Dict[str, Union[Track, Context, str]]] A list of playlist history object. Each obj...
async def add_tracks(self, playlist: Union[str, Playlist], *tracks) -> str: """Add one or more tracks to a user’s playlist. Parameters ---------- playlist : Union[str, Playlist] The playlist to modify tracks : Sequence[Union[str, Track]] Tracks to add to ...
async def replace_tracks(self, playlist, *tracks) -> str: """Replace all the tracks in a playlist, overwriting its existing tracks. This powerful request can be useful for replacing tracks, re-ordering existing tracks, or clearing the playlist. Parameters ---------- playlist : ...
async def remove_tracks(self, playlist, *tracks): """Remove one or more tracks from a user’s playlist. Parameters ---------- playlist : Union[str, Playlist] The playlist to modify tracks : Sequence[Union[str, Track]] Tracks to remove from the playlist ...
async def reorder_tracks(self, playlist, start, insert_before, length=1, *, snapshot_id=None): """Reorder a track or a group of tracks in a playlist. Parameters ---------- playlist : Union[str, Playlist] The playlist to modify start : int The position of ...
async def edit_playlist(self, playlist, *, name=None, public=None, collaborative=None, description=None): """Change a playlist’s name and public/private, collaborative state and description. Parameters ---------- playlist : Union[str, Playlist] The playlist to modify ...
async def create_playlist(self, name, *, public=True, collaborative=False, description=None): """Create a playlist for a Spotify user. Parameters ---------- name : str The name of the playlist. public : Optional[bool] The public/private status of the play...
async def get_playlists(self, *, limit=20, offset=0): """get the users playlists from spotify. Parameters ---------- limit : Optional[int] The limit on how many playlists to retrieve for this user (default is 20). offset : Optional[int] The offset fro...
async def get_tracks(self, *, limit: Optional[int] = 20, offset: Optional[int] = 0) -> List[Track]: """get the albums tracks from spotify. Parameters ---------- limit : Optional[int] The limit on how many tracks to retrieve for this album (default is 20). offset : Op...
async def get_all_tracks(self, *, market: Optional[str] = 'US') -> List[Track]: """loads all of the albums tracks, depending on how many the album has this may be a long operation. Parameters ---------- market : Optional[str] An ISO 3166-1 alpha-2 country code. Provide this ...
def oauth2_url(self, redirect_uri: str, scope: Optional[str] = None, state: Optional[str] = None) -> str: """Generate an outh2 url for user authentication. Parameters ---------- redirect_uri : str Where spotify should redirect the user to after authentication. scope ...
async def get_album(self, spotify_id: str, *, market: str = 'US') -> Album: """Retrive an album with a spotify ID. Parameters ---------- spotify_id : str The ID to search for. market : Optional[str] An ISO 3166-1 alpha-2 country code Returns ...
async def get_artist(self, spotify_id: str) -> Artist: """Retrive an artist with a spotify ID. Parameters ---------- spotify_id : str The ID to search for. Returns ------- artist : Artist The artist from the ID """ data = ...
async def get_track(self, spotify_id: str) -> Track: """Retrive an track with a spotify ID. Parameters ---------- spotify_id : str The ID to search for. Returns ------- track : Track The track from the ID """ data = await ...
async def get_user(self, spotify_id: str) -> User: """Retrive an user with a spotify ID. Parameters ---------- spotify_id : str The ID to search for. Returns ------- user : User The user from the ID """ data = await self.h...
async def get_albums(self, *ids: List[str], market: str = 'US') -> List[Album]: """Retrive multiple albums with a list of spotify IDs. Parameters ---------- ids : List[str] the ID to look for market : Optional[str] An ISO 3166-1 alpha-2 country code ...
async def get_artists(self, *ids: List[str]) -> List[Artist]: """Retrive multiple artists with a list of spotify IDs. Parameters ---------- ids : List[str] the IDs to look for Returns ------- artists : List[Artist] The artists from the ID...
async def search(self, q: str, *, types: Optional[Iterable[str]] = ['track', 'playlist', 'artist', 'album'], limit: Optional[int] = 20, offset: Optional[int] = 0, market: Optional[str] = None) -> Dict[str, List[Union[Track, Playlist, Artist, Album]]]: """Access the spotify search functionality. Paramet...
async def contains_albums(self, *albums: Sequence[Union[str, Album]]) -> List[bool]: """Check if one or more albums is already saved in the current Spotify user’s ‘Your Music’ library. Parameters ---------- albums : Union[Album, str] A sequence of artist objects or spotify I...
async def contains_tracks(self, *tracks: Sequence[Union[str, Track]]) -> List[bool]: """Check if one or more tracks is already saved in the current Spotify user’s ‘Your Music’ library. Parameters ---------- tracks : Union[Track, str] A sequence of track objects or spotify ID...
async def get_tracks(self, *, limit=20, offset=0) -> List[Track]: """Get a list of the songs saved in the current Spotify user’s ‘Your Music’ library. Parameters ---------- limit : Optional[int] The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50. ...
async def get_albums(self, *, limit=20, offset=0) -> List[Album]: """Get a list of the albums saved in the current Spotify user’s ‘Your Music’ library. Parameters ---------- limit : Optional[int] The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50. ...
async def remove_albums(self, *albums): """Remove one or more albums from the current user’s ‘Your Music’ library. Parameters ---------- albums : Sequence[Union[Album, str]] A sequence of artist objects or spotify IDs """ _albums = [(obj if isinstance(obj, st...
async def remove_tracks(self, *tracks): """Remove one or more tracks from the current user’s ‘Your Music’ library. Parameters ---------- tracks : Sequence[Union[Track, str]] A sequence of track objects or spotify IDs """ _tracks = [(obj if isinstance(obj, str...
async def save_albums(self, *albums): """Save one or more albums to the current user’s ‘Your Music’ library. Parameters ---------- albums : Sequence[Union[Album, str]] A sequence of artist objects or spotify IDs """ _albums = [(obj if isinstance(obj, str) els...
async def save_tracks(self, *tracks): """Save one or more tracks to the current user’s ‘Your Music’ library. Parameters ---------- tracks : Sequence[Union[Track, str]] A sequence of track objects or spotify IDs """ _tracks = [(obj if isinstance(obj, str) else...
def to_id(string: str) -> str: """Get a spotify ID from a URI or open.spotify URL. Paramters --------- string : str The string to operate on. Returns ------- id : str The Spotify ID from the string. """ string = string.strip() match = _URI_RE.match(string) ...
def assert_hasattr(attr: str, msg: str, tp: BaseException = SpotifyException) -> Callable: """decorator to assert an object has an attribute when run.""" def decorator(func: Callable) -> Callable: @functools.wraps(func) def decorated(self, *args, **kwargs): if not hasattr(self, attr)...
def from_client(cls, client, *args, **kwargs): """Construct a OAuth2 object from a `spotify.Client`.""" return cls(client.http.client_id, *args, **kwargs)
def url_(client_id: str, redirect_uri: str, *, scope: str = None, state: str = None, secure: bool = True) -> str: """Construct a OAuth2 URL instead of an OAuth2 object.""" attrs = { 'client_id': client_id, 'redirect_uri': quote(redirect_uri) } if scope is not Non...
def attrs(self): """Attributes used when constructing url parameters.""" data = { 'client_id': self.client_id, 'redirect_uri': quote(self.redirect_uri), } if self.scope is not None: data['scope'] = quote(self.scope) if self.state is not None:...
def parameters(self) -> str: """URL parameters used.""" return '&'.join('{0}={1}'.format(*item) for item in self.attrs.items())
async def build(self): """get the track object for each link in the partial tracks data Returns ------- tracks : List[Track] The tracks """ data = await self.__func() return list(PlaylistTrack(self.__client, track) for track in data['items'])
async def get_all_tracks(self) -> List[PlaylistTrack]: """Get all playlist tracks from the playlist. Returns ------- tracks : List[PlaylistTrack] The playlists tracks. """ if isinstance(self._tracks, PartialTracks): return await self._tracks.build...
async def pause(self, *, device: Optional[SomeDevice] = None): """Pause playback on the user’s account. Parameters ---------- device : Optional[:obj:`SomeDevice`] The Device object or id of the device this command is targeting. If not supplied, the user’s current...
async def resume(self, *, device: Optional[SomeDevice] = None): """Resume playback on the user's account. Parameters ---------- device : Optional[:obj:`SomeDevice`] The Device object or id of the device this command is targeting. If not supplied, the user’s curre...
async def seek(self, pos, *, device: Optional[SomeDevice] = None): """Seeks to the given position in the user’s currently playing track. Parameters ---------- pos : int The position in milliseconds to seek to. Must be a positive number. Passing in a p...
async def set_repeat(self, state, *, device: Optional[SomeDevice] = None): """Set the repeat mode for the user’s playback. Parameters ---------- state : str Options are repeat-track, repeat-context, and off device : Optional[:obj:`SomeDevice`] The Device ...
async def set_volume(self, volume: int, *, device: Optional[SomeDevice] = None): """Set the volume for the user’s current playback device. Parameters ---------- volume : int The volume to set. Must be a value from 0 to 100 inclusive. device : Optional[:obj:`SomeDevic...
async def next(self, *, device: Optional[SomeDevice] = None): """Skips to next track in the user’s queue. Parameters ---------- device : Optional[:obj:`SomeDevice`] The Device object or id of the device this command is targeting. If not supplied, the user’s curre...
async def previous(self, *, device: Optional[SomeDevice] = None): """Skips to previous track in the user’s queue. Note that this will ALWAYS skip to the previous track, regardless of the current track’s progress. Returning to the start of the current track should be performed using :meth:`seek`...