_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q270200 | feature_selection | test | def feature_selection(feat_select, X, y):
"""" Implements various kinds of feature selection """
# K-best
if re.match('.*-best', feat_select) is not None:
n = int(feat_select.split('-')[0])
selector = SelectKBest(k=n)
import warnings
with warnings.catch_warnings():
... | python | {
"resource": ""
} |
q270201 | get_studies_by_regions | test | def get_studies_by_regions(dataset, masks, threshold=0.08, remove_overlap=True,
studies=None, features=None,
regularization="scale"):
""" Set up data for a classification task given a set of masks
Given a set of masks, this function retrieves studies as... | python | {
"resource": ""
} |
q270202 | get_feature_order | test | def get_feature_order(dataset, features):
""" Returns a list with the order that features requested appear in
dataset """
all_features = dataset.get_feature_names()
i = [all_features.index(f) for f in features]
return i | python | {
"resource": ""
} |
q270203 | classify_regions | test | def classify_regions(dataset, masks, method='ERF', threshold=0.08,
remove_overlap=True, regularization='scale',
output='summary', studies=None, features=None,
class_weight='auto', classifier=None,
cross_val='4-Fold', param_grid=None, sc... | python | {
"resource": ""
} |
q270204 | classify | test | def classify(X, y, clf_method='ERF', classifier=None, output='summary_clf',
cross_val=None, class_weight=None, regularization=None,
param_grid=None, scoring='accuracy', refit_all=True,
feat_select=None):
""" Wrapper for scikit-learn classification functions
Imlements vario... | python | {
"resource": ""
} |
q270205 | Classifier.fit | test | def fit(self, X, y, cv=None, class_weight='auto'):
""" Fits X to outcomes y, using clf """
# Incorporate error checking such as :
# if isinstance(self.classifier, ScikitClassifier):
# do one thingNone
# otherwiseNone.
self.X = X
self.y = y
self.set_... | python | {
"resource": ""
} |
q270206 | Classifier.set_class_weight | test | def set_class_weight(self, class_weight='auto', y=None):
""" Sets the class_weight of the classifier to match y """
if class_weight is None:
cw = None
try:
self.clf.set_params(class_weight=cw)
except ValueError:
pass
elif cla... | python | {
"resource": ""
} |
q270207 | Classifier.cross_val_fit | test | def cross_val_fit(self, X, y, cross_val='4-Fold', scoring='accuracy',
feat_select=None, class_weight='auto'):
""" Fits X to outcomes y, using clf and cv_method """
from sklearn import cross_validation
self.X = X
self.y = y
self.set_class_weight(class_weig... | python | {
"resource": ""
} |
q270208 | Classifier.fit_dataset | test | def fit_dataset(self, dataset, y, features=None,
feature_type='features'):
""" Given a dataset, fits either features or voxels to y """
# Get data from dataset
if feature_type == 'features':
X = np.rot90(dataset.feature_table.data.toarray())
elif feature... | python | {
"resource": ""
} |
q270209 | average_within_regions | test | def average_within_regions(dataset, regions, masker=None, threshold=None,
remove_zero=True):
""" Aggregates over all voxels within each ROI in the input image.
Takes a Dataset and a Nifti image that defines distinct regions, and
returns a numpy matrix of ROIs x mappables, where ... | python | {
"resource": ""
} |
q270210 | get_random_voxels | test | def get_random_voxels(dataset, n_voxels):
""" Returns mappable data for a random subset of voxels.
May be useful as a baseline in predictive analyses--e.g., to compare
performance of a more principled feature selection method with simple
random selection.
Args:
dataset: A Dataset instance
... | python | {
"resource": ""
} |
q270211 | _get_top_words | test | def _get_top_words(model, feature_names, n_top_words=40):
""" Return top forty words from each topic in trained topic model.
"""
topic_words = []
for topic in model.components_:
top_words = [feature_names[i] for i in topic.argsort()[:-n_top_words-1:-1]]
topic_words += [top_words]
ret... | python | {
"resource": ""
} |
q270212 | pearson | test | def pearson(x, y):
""" Correlates row vector x with each row vector in 2D array y. """
data = np.vstack((x, y))
ms = data.mean(axis=1)[(slice(None, None, None), None)]
datam = data - ms
datass = np.sqrt(np.sum(datam**2, axis=1))
temp = np.dot(datam[1:], datam[0].T)
rs = temp / (datass[1:] * ... | python | {
"resource": ""
} |
q270213 | fdr | test | def fdr(p, q=.05):
""" Determine FDR threshold given a p value array and desired false
discovery rate q. """
s = np.sort(p)
nvox = p.shape[0]
null = np.array(range(1, nvox + 1), dtype='float') * q / nvox
below = np.where(s <= null)[0]
return s[max(below)] if len(below) else -1 | python | {
"resource": ""
} |
q270214 | Dataset._load_activations | test | def _load_activations(self, filename):
""" Load activation data from a text file.
Args:
filename (str): a string pointing to the location of the txt file
to read from.
"""
logger.info("Loading activation data from %s..." % filename)
activations = pd.... | python | {
"resource": ""
} |
q270215 | Dataset.create_image_table | test | def create_image_table(self, r=None):
""" Create and store a new ImageTable instance based on the current
Dataset. Will generally be called privately, but may be useful as a
convenience method in cases where the user wants to re-generate the
table with a new smoothing kernel of different... | python | {
"resource": ""
} |
q270216 | Dataset.get_studies | test | def get_studies(self, features=None, expression=None, mask=None,
peaks=None, frequency_threshold=0.001,
activation_threshold=0.0, func=np.sum, return_type='ids',
r=6
):
""" Get IDs or data for studies that meet specific criteria.
... | python | {
"resource": ""
} |
q270217 | Dataset.add_features | test | def add_features(self, features, append=True, merge='outer',
duplicates='ignore', min_studies=0.0, threshold=0.001):
""" Construct a new FeatureTable from file.
Args:
features: Feature data to add. Can be:
(a) A text file containing the feature data, whe... | python | {
"resource": ""
} |
q270218 | Dataset.get_feature_names | test | def get_feature_names(self, features=None):
""" Returns names of features. If features is None, returns all
features. Otherwise assumes the user is trying to find the order of the
features. """
if features:
return self.feature_table.get_ordered_names(features)
else:
... | python | {
"resource": ""
} |
q270219 | Dataset.get_feature_counts | test | def get_feature_counts(self, threshold=0.001):
""" Returns a dictionary, where the keys are the feature names
and the values are the number of studies tagged with the feature. """
counts = np.sum(self.get_feature_data() >= threshold, 0)
return dict(zip(self.get_feature_names(), list(coun... | python | {
"resource": ""
} |
q270220 | Dataset.load | test | def load(cls, filename):
""" Load a pickled Dataset instance from file. """
try:
dataset = pickle.load(open(filename, 'rb'))
except UnicodeDecodeError:
# Need to try this for python3
dataset = pickle.load(open(filename, 'rb'), encoding='latin')
if has... | python | {
"resource": ""
} |
q270221 | Dataset.save | test | def save(self, filename):
""" Pickle the Dataset instance to the provided file.
"""
if hasattr(self, 'feature_table'):
self.feature_table._sdf_to_csr()
pickle.dump(self, open(filename, 'wb'), -1)
if hasattr(self, 'feature_table'):
self.feature_table._csr... | python | {
"resource": ""
} |
q270222 | ImageTable.get_image_data | test | def get_image_data(self, ids=None, voxels=None, dense=True):
""" Slices and returns a subset of image data.
Args:
ids (list, array): A list or 1D numpy array of study ids to
return. If None, returns data for all studies.
voxels (list, array): A list or 1D numpy a... | python | {
"resource": ""
} |
q270223 | FeatureTable.get_feature_data | test | def get_feature_data(self, ids=None, features=None, dense=True):
""" Slices and returns a subset of feature data.
Args:
ids (list, array): A list or 1D numpy array of study ids to
return rows for. If None, returns data for all studies
(i.e., all rows in array... | python | {
"resource": ""
} |
q270224 | FeatureTable.get_ordered_names | test | def get_ordered_names(self, features):
""" Given a list of features, returns features in order that they
appear in database.
Args:
features (list): A list or 1D numpy array of named features to
return.
Returns:
A list of features in order they appear... | python | {
"resource": ""
} |
q270225 | FeatureTable.get_ids | test | def get_ids(self, features, threshold=0.0, func=np.sum, get_weights=False):
""" Returns a list of all studies in the table that meet the desired
feature-based criteria.
Will most commonly be used to retrieve studies that use one or more
features with some minimum frequency; e.g.,:
... | python | {
"resource": ""
} |
q270226 | FeatureTable.search_features | test | def search_features(self, search):
''' Returns all features that match any of the elements in the input
list.
Args:
search (str, list): A string or list of strings defining the query.
Returns:
A list of matching feature names.
'''
if isinstance(s... | python | {
"resource": ""
} |
q270227 | FeatureTable.get_ids_by_expression | test | def get_ids_by_expression(self, expression, threshold=0.001, func=np.sum):
""" Use a PEG to parse expression and return study IDs."""
lexer = lp.Lexer()
lexer.build()
parser = lp.Parser(
lexer, self.dataset, threshold=threshold, func=func)
parser.build()
retur... | python | {
"resource": ""
} |
q270228 | FeatureTable._sdf_to_csr | test | def _sdf_to_csr(self):
""" Convert FeatureTable to SciPy CSR matrix. """
data = self.data.to_dense()
self.data = {
'columns': list(data.columns),
'index': list(data.index),
'values': sparse.csr_matrix(data.values)
} | python | {
"resource": ""
} |
q270229 | deprecated | test | def deprecated(*args):
""" Deprecation warning decorator. Takes optional deprecation message,
otherwise will use a generic warning. """
def wrap(func):
def wrapped_func(*args, **kwargs):
warnings.warn(msg, category=DeprecationWarning)
return func(*args, **kwargs)
retu... | python | {
"resource": ""
} |
q270230 | transform | test | 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] | python | {
"resource": ""
} |
q270231 | xyz_to_mat | test | 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... | python | {
"resource": ""
} |
q270232 | Transformer.apply | test | 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... | python | {
"resource": ""
} |
q270233 | Masker.mask | test | 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... | python | {
"resource": ""
} |
q270234 | Masker.get_mask | test | 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 ... | python | {
"resource": ""
} |
q270235 | load_imgs | test | 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.
... | python | {
"resource": ""
} |
q270236 | save_img | test | 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... | python | {
"resource": ""
} |
q270237 | set_logging_level | test | 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... | python | {
"resource": ""
} |
q270238 | expand_address | test | 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 ... | python | {
"resource": ""
} |
q270239 | normalized_tokens | test | 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... | python | {
"resource": ""
} |
q270240 | parse_address | test | 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')
... | python | {
"resource": ""
} |
q270241 | near_dupe_hashes | test | 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... | python | {
"resource": ""
} |
q270242 | dict_to_object | test | 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)) | python | {
"resource": ""
} |
q270243 | TiingoClient.get_ticker_price | test | 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... | python | {
"resource": ""
} |
q270244 | TiingoClient.get_dataframe | test | 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... | python | {
"resource": ""
} |
q270245 | TiingoClient.get_bulk_news | test | 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.
... | python | {
"resource": ""
} |
q270246 | RestClient._request | test | 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
... | python | {
"resource": ""
} |
q270247 | HTTPClient.get_bearer_info | test | 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... | python | {
"resource": ""
} |
q270248 | HTTPClient.request | test | 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 ... | python | {
"resource": ""
} |
q270249 | HTTPClient.album_tracks | test | 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... | python | {
"resource": ""
} |
q270250 | HTTPClient.artist | test | 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) | python | {
"resource": ""
} |
q270251 | HTTPClient.artist_albums | test | 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
... | python | {
"resource": ""
} |
q270252 | HTTPClient.artist_top_tracks | test | 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/{... | python | {
"resource": ""
} |
q270253 | HTTPClient.artist_related_artists | test | 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)
... | python | {
"resource": ""
} |
q270254 | HTTPClient.artists | test | 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, ... | python | {
"resource": ""
} |
q270255 | HTTPClient.category | test | 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
... | python | {
"resource": ""
} |
q270256 | HTTPClient.category_playlists | test | 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 ... | python | {
"resource": ""
} |
q270257 | HTTPClient.categories | test | 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... | python | {
"resource": ""
} |
q270258 | HTTPClient.featured_playlists | test | 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
... | python | {
"resource": ""
} |
q270259 | HTTPClient.new_releases | test | 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]
... | python | {
"resource": ""
} |
q270260 | HTTPClient.recommendations | test | 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... | python | {
"resource": ""
} |
q270261 | HTTPClient.following_artists_or_users | test | 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.
... | python | {
"resource": ""
} |
q270262 | Artist.get_albums | test | 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... | python | {
"resource": ""
} |
q270263 | Artist.get_all_albums | test | 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
---... | python | {
"resource": ""
} |
q270264 | Artist.total_albums | test | 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... | python | {
"resource": ""
} |
q270265 | Artist.related_artists | test | 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... | python | {
"resource": ""
} |
q270266 | User.currently_playing | test | 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(... | python | {
"resource": ""
} |
q270267 | User.get_player | test | 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... | python | {
"resource": ""
} |
q270268 | User.get_devices | test | 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 ... | python | {
"resource": ""
} |
q270269 | User.recently_played | test | 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... | python | {
"resource": ""
} |
q270270 | User.replace_tracks | test | 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 : ... | python | {
"resource": ""
} |
q270271 | User.reorder_tracks | test | 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 ... | python | {
"resource": ""
} |
q270272 | User.create_playlist | test | 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... | python | {
"resource": ""
} |
q270273 | User.get_playlists | test | 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... | python | {
"resource": ""
} |
q270274 | Album.get_tracks | test | 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... | python | {
"resource": ""
} |
q270275 | Album.get_all_tracks | test | 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 ... | python | {
"resource": ""
} |
q270276 | Client.oauth2_url | test | 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 ... | python | {
"resource": ""
} |
q270277 | Client.get_album | test | 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
... | python | {
"resource": ""
} |
q270278 | Client.get_artist | test | 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 = ... | python | {
"resource": ""
} |
q270279 | Client.get_track | test | 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 ... | python | {
"resource": ""
} |
q270280 | Client.get_user | test | 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... | python | {
"resource": ""
} |
q270281 | Client.get_albums | test | 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
... | python | {
"resource": ""
} |
q270282 | Client.get_artists | test | 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... | python | {
"resource": ""
} |
q270283 | Client.search | test | 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... | python | {
"resource": ""
} |
q270284 | to_id | test | 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)
... | python | {
"resource": ""
} |
q270285 | assert_hasattr | test | 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)... | python | {
"resource": ""
} |
q270286 | OAuth2.from_client | test | def from_client(cls, client, *args, **kwargs):
"""Construct a OAuth2 object from a `spotify.Client`."""
return cls(client.http.client_id, *args, **kwargs) | python | {
"resource": ""
} |
q270287 | OAuth2.url_ | test | 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... | python | {
"resource": ""
} |
q270288 | OAuth2.attrs | test | 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:... | python | {
"resource": ""
} |
q270289 | OAuth2.parameters | test | def parameters(self) -> str:
"""URL parameters used."""
return '&'.join('{0}={1}'.format(*item) for item in self.attrs.items()) | python | {
"resource": ""
} |
q270290 | PartialTracks.build | test | 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']) | python | {
"resource": ""
} |
q270291 | Playlist.get_all_tracks | test | 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... | python | {
"resource": ""
} |
q270292 | Player.resume | test | 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... | python | {
"resource": ""
} |
q270293 | Player.transfer | test | async def transfer(self, device: SomeDevice, ensure_playback: bool = False):
"""Transfer playback to a new device and determine if it should start playing.
Parameters
----------
device : :obj:`SomeDevice`
The device on which playback should be started/transferred.
en... | python | {
"resource": ""
} |
q270294 | SpotifyBase.from_href | test | async def from_href(self):
"""Get the full object from spotify with a `href` attribute."""
if not hasattr(self, 'href'):
raise TypeError('Spotify object has no `href` attribute, therefore cannot be retrived')
elif hasattr(self, 'http'):
return await self.http.request(('G... | python | {
"resource": ""
} |
q270295 | ExpirationDate.get | test | def get(self): # pragma: no cover
"""
Execute the logic behind the meaning of ExpirationDate + return the matched status.
:return:
The status of the tested domain.
Can be one of the official status.
:rtype: str
"""
# We get the status of the dom... | python | {
"resource": ""
} |
q270296 | ExpirationDate._convert_or_shorten_month | test | def _convert_or_shorten_month(cls, data):
"""
Convert a given month into our unified format.
:param data: The month to convert or shorten.
:type data: str
:return: The unified month name.
:rtype: str
"""
# We map the different month and their possible r... | python | {
"resource": ""
} |
q270297 | Production._update_code_urls | test | def _update_code_urls(self):
"""
Read the code and update all links.
"""
to_ignore = [".gitignore", ".keep"]
for root, _, files in PyFunceble.walk(
PyFunceble.CURRENT_DIRECTORY
+ PyFunceble.directory_separator
+ "PyFunceble"
+ PyF... | python | {
"resource": ""
} |
q270298 | Production._is_version_greater | test | def _is_version_greater(self):
"""
Check if the current version is greater as the older older one.
"""
# we compare the 2 versions.
checked = Version(True).check_versions(
self.current_version[0], self.version_yaml
)
if checked is not None and not ch... | python | {
"resource": ""
} |
q270299 | Production.is_dev_version | test | def is_dev_version(cls):
"""
Check if the current branch is `dev`.
"""
# We initiate the command we have to run in order to
# get the branch we are currently working with.
command = "git branch"
# We execute and get the command output.
command_result = C... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.