code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if owner is None: raise ValueError("Invalid value for `owner`, must not be `None`") if owner is not None and not re.search('[a-z0-9](?:-(?!-)|[a-z0-9])+[a-z0-9]', owner): raise ValueError("Invalid value for `owner`, must be a follow pattern or equal to `/[a-z0-9](?:-(?!-...
def owner(self, owner)
Sets the owner of this LinkedDatasetCreateOrUpdateRequest. User name and unique identifier of the creator of the dataset. :param owner: The owner of this LinkedDatasetCreateOrUpdateRequest. :type: str
1.755225
1.682021
1.043521
if 'w' == self._mode and isinstance(value, str): self._queue.put(value.encode('utf-8')) elif self._mode in {'w', 'wb'}: if isinstance(value, (bytes, bytearray)): self._queue.put(value) else: raise TypeError( ...
def write(self, value)
write the given value to the stream - if the object is a bytearray, write it as-is - otherwise, convert the object to a string with `str()` and write the UTF-8 bytes :param value: the value to write :type value: str or bytearray :raises TypeError: if the type of the value provid...
3.149458
3.082875
1.021597
if 'r' == self._mode: return self._read_response.text elif 'rb' == self._mode: return self._read_response.content else: raise IOError("File not opened in read mode.")
def read(self)
read the contents of the file that's been opened in read mode
4.582434
3.51614
1.303257
ownerid, datasetid = parse_dataset_key(self._dataset_key) response = requests.get( '{}/file_download/{}/{}/{}'.format( self._query_host, ownerid, datasetid, self._file_name), headers={ 'User-Agent': self._user_agent, 'Autho...
def _open_for_read(self)
open the file in read mode
3.879737
3.757161
1.032625
def put_request(body): ownerid, datasetid = parse_dataset_key(self._dataset_key) response = requests.put( "{}/uploads/{}/{}/files/{}".format( self._api_host, ownerid, datasetid, self._file_name), data=body, ...
def _open_for_write(self)
open the file in write mode
3.994759
3.91046
1.021557
if self._mode.find('w') >= 0: self._queue.put(self._sentinel) self._thread.join(timeout=self._timeout) if self._thread.is_alive(): raise RemoteFileException("Closing file timed out.") response = self._response_queue.get_nowait() ...
def close(self)
in write mode, closing the handle adds the sentinel value into the queue and joins the thread executing the HTTP request. in read mode, this clears out the read response object so there are no references to it, and the resources can be reclaimed.
4.995241
3.826761
1.305344
json_context = json.dumps(context, cls=self.json_encoder_class) return HttpResponse(json_context, content_type=self.get_content_type(), status=status)
def render_json_response(self, context, status=200)
Serialize the context dictionary as JSON and return it as a HTTP Repsonse object. This method only allows serialization of simple objects (i.e. no model instances)
2.762517
2.554527
1.08142
context = self.chart_instance.chartjs_configuration(*args, **kwargs) return self.render_json_response(context)
def get(self, request, *args, **kwargs)
Main entry. This View only responds to GET requests.
9.015642
7.763496
1.161286
# TODO: handle syntax errors contents = self._get_contents(contents, filename) request = ParseRequest(filename=os.path.basename(filename), content=contents, mode=mode, language=self._scramble_language(language)) resp...
def parse(self, filename: str, language: Optional[str]=None, contents: Optional[str]=None, mode: Optional[ModeType]=None, timeout: Optional[int]=None) -> ResultContext
Queries the Babelfish server and receives the UAST response for the specified file. :param filename: The path to the file. Can be arbitrary if contents \ is not None. :param language: The programming language of the file. Refer to \ https://doc....
4.867379
5.685805
0.856058
self._channel.close() self._channel = self._stub_v1 = self._stub_v2 = None
def close(self) -> None
Close the gRPC channel and free the acquired resources. Using a closed client is not supported.
9.533978
5.888887
1.618978
if isinstance(n, CompatNodeIterator): return CompatNodeIterator(n._nodeit.iterate(order), only_nodes=True) elif isinstance(n, Node): nat_it = native_iterator(n.internal_node, order) return CompatNodeIterator(NodeIterator(nat_it), only_nodes=True) elif isinstance(n, dict): ...
def iterator(n: Union[Node, CompatNodeIterator, dict], order: TreeOrder = TreeOrder.PRE_ORDER) -> CompatNodeIterator
This function has the same signature as the pre-v3 iterator() call returning a compatibility CompatNodeIterator.
4.083013
4.028321
1.013577
ctx = uast() return CompatNodeIterator(NodeIterator(ctx.filter(query, n.internal_node), ctx))
def filter(n: Node, query: str) -> CompatNodeIterator
This function has the same signature as the pre-v3 filter() returning a compatibility CompatNodeIterator.
19.997358
22.930704
0.872078
return CompatNodeIterator(filter(n, query)._nodeit, only_nodes=True)
def filter_nodes(n: Node, query: str) -> CompatNodeIterator
Utility function. Same as filter() but will only filter for nodes (i. e. it will exclude scalars and positions).
21.777618
18.209805
1.195928
return _scalariter2item(n, query, str)
def filter_string(n: Node, query: str) -> str
Filter and ensure that the returned value is of string type.
146.273392
62.296604
2.348015
return _scalariter2item(n, query, bool)
def filter_bool(n: Node, query: str) -> bool
Filter and ensure that the returned value is of type bool.
119.410202
53.784325
2.220167
return _scalariter2item(n, query, int)
def filter_int(n: Node, query: str) -> int
Filter and ensure that the returned value is of type int.
100.402451
47.749447
2.102693
return _scalariter2item(n, query, float)
def filter_float(n: Node, query: str) -> float
Filter and ensure that the returned value is of type int.
84.237885
45.310345
1.859131
return self._parse(filename, language, contents, timeout, Mode.Value('ANNOTATED'))
def parse(self, filename: str, language: str = None, contents: str = None, timeout: float = None) -> CompatParseResponse
Parse the specified filename or contents and return a CompatParseResponse.
20.478344
16.521963
1.239462
if not self._last_node: return None return filter(self._last_node, query)
def filter(self, query: str) -> Optional['CompatNodeIterator']
Further filter the results using this iterator as base.
6.383351
5.073153
1.258261
if isinstance(self._last_node, dict): return self._last_node.keys() else: return {}
def properties(self) -> dict
Returns the properties of the current node in the iteration.
6.6644
4.124389
1.615852
xml = XmlWriter(f, indentAmount=' ') xml.prolog() xml.start('playlist', { 'xmlns': 'http://xspf.org/ns/0/', 'version': '1' }) xml.start('trackList') for tupe in tuples: xml.start('track') xml.elem('creator',tupe[0]) xml.elem('title',tupe[1]) xml.elem('location',...
def write_xspf(f, tuples)
send me a list of (artist,title,mp3_url)
2.742068
2.667195
1.028072
try: param_dict['api_key'] = config.ECHO_NEST_API_KEY param_list = [] if not socket_timeout: socket_timeout = config.CALL_TIMEOUT for key,val in param_dict.iteritems(): if isinstance(val, list): param_list.extend( [(key,subval) for subval...
def callm(method, param_dict, POST=False, socket_timeout=None, data=None)
Call the api! Param_dict is a *regular* *python* *dictionary* so if you want to have multi-valued params put them in a list. ** note, if we require 2.6, we can get rid of this timeout munging.
2.643242
2.641408
1.000694
try: import oauth2 # lazy import this so oauth2 is not a hard dep except ImportError: raise Exception("You must install the python-oauth2 library to use this method.") def build_request(url): params = { 'oauth_version': "1.0", 'oauth_nonce': oauth2.gener...
def oauthgetm(method, param_dict, socket_timeout=None)
Call the api! With Oauth! Param_dict is a *regular* *python* *dictionary* so if you want to have multi-valued params put them in a list. ** note, if we require 2.6, we can get rid of this timeout munging.
2.713415
2.714102
0.999747
params = urllib.urlencode(fields) url = 'http://%s%s?%s' % (host, selector, params) u = urllib2.urlopen(url, files) result = u.read() [fp.close() for (key, fp) in files] return result
def postChunked(host, selector, fields, files)
Attempt to replace postMultipart() with nearly-identical interface. (The files tuple no longer requires the filename, and we only return the response body.) Uses the urllib2_file.py originally from http://fabien.seisen.org which was also drawn heavily from http://code.activestate.com/recipes/1463...
2.612786
2.720033
0.960572
result = util.callm("catalog/create", {}, POST=True, data={"name":name, "type":T}) result = result['response'] return Catalog(result['id'], **dict( (k,result[k]) for k in ('name', 'type')))
def create_catalog_by_name(name, T="general")
Creates a catalog object, with a given name. Does not check to see if the catalog already exists. Create a catalog object like
6.557281
8.475001
0.77372
kwargs = { 'name' : name, } result = util.callm("%s/%s" % ('catalog', 'profile'), kwargs) return Catalog(**util.fix(result['response']['catalog']))
def get_catalog_by_name(name)
Grabs a catalog by name, if its there on the api key. Otherwise, an error is thrown (mirroring the API)
11.570127
10.473521
1.104703
result = util.callm("%s/%s" % ('catalog', 'list'), {'results': results, 'start': start}) cats = [Catalog(**util.fix(d)) for d in result['response']['catalogs']] start = result['response']['start'] total = result['response']['total'] return ResultList(cats, start, total)
def list_catalogs(results=30, start=0)
Returns list of all catalogs created on this API key Args: Kwargs: results (int): An integer number of results to return start (int): An integer starting value for the result set Returns: A list of catalog objects Example: >>> catalog.list_catalogs() [<catalog - tes...
5.108976
6.900051
0.740426
post_data = {} items_json = json.dumps(items, default=dthandler) post_data['data'] = items_json response = self.post_attribute("update", data=post_data) return response['ticket']
def update(self, items)
Update a catalog object Args: items (list): A list of dicts describing update data and action codes (see api docs) Kwargs: Returns: A ticket id Example: >>> c = catalog.Catalog('my_songs', type='song') >>> items [{'action': 'update', ...
5.913669
6.857282
0.862393
warnings.warn("catalog.read_items() is depreciated. Please use catalog.get_item_dicts() instead.") kwargs = {} kwargs['bucket'] = buckets or [] kwargs['item_id'] = item_ids or [] response = self.get_attribute("read", results=results, start=start, **kwargs) rval =...
def read_items(self, buckets=None, results=15, start=0,item_ids=None)
Returns data from the catalog; also expanded for the requested buckets. This method is provided for backwards-compatibility Args: Kwargs: buckets (list): A list of strings specifying which buckets to retrieve results (int): An integer number of results to return ...
2.778522
2.855634
0.972997
kwargs = {} kwargs['bucket'] = buckets or [] kwargs['item_id'] = item_ids or [] response = self.get_attribute("read", results=results, start=start, **kwargs) rval = ResultList(response['catalog']['items']) if item_ids: rval.start=0; rval.t...
def get_item_dicts(self, buckets=None, results=15, start=0,item_ids=None)
Returns data from the catalog; also expanded for the requested buckets Args: Kwargs: buckets (list): A list of strings specifying which buckets to retrieve results (int): An integer number of results to return start (int): An integer starting value for the result ...
3.648356
3.827244
0.953259
kwargs = {} kwargs['bucket'] = buckets or [] if since: kwargs['since']=since response = self.get_attribute("feed", results=results, start=start, **kwargs) rval = ResultList(response['feed']) return rval
def get_feed(self, buckets=None, since=None, results=15, start=0)
Returns feed (news, blogs, reviews, audio, video) for the catalog artists; response depends on requested buckets Args: Kwargs: buckets (list): A list of strings specifying which feed items to retrieve results (int): An integer number of results to return start (in...
5.698831
7.300504
0.780608
"given an audio file, print out the artist, title and some audio attributes of the song" print 'File: ', audio_file pytrack = track.track_from_filename(audio_file) print 'Artist: ', pytrack.artist if hasattr(pytrack, 'artist') else 'Unknown' print 'Title: ', pytrack.title if hasatt...
def _show_one(audio_file)
given an audio file, print out the artist, title and some audio attributes of the song
3.216148
2.779665
1.157027
"print out the tempo for each audio file in the given directory" for f in os.listdir(directory): if _is_audio(f): path = os.path.join(directory, f) _show_one(path)
def show_attrs(directory)
print out the tempo for each audio file in the given directory
5.511551
3.353715
1.643417
kwargs = {} if ids: if not isinstance(ids, list): ids = [ids] kwargs['id'] = ids if track_ids: if not isinstance(track_ids, list): track_ids = [track_ids] kwargs['track_id'] = track_ids buckets = buckets or [] if buckets: kwargs...
def profile(ids=None, track_ids=None, buckets=None, limit=False)
get the profiles for multiple songs at once Args: ids (str or list): a song ID or list of song IDs Kwargs: buckets (list): A list of strings specifying which buckets to retrieve limit (bool): A boolean indicating whether or not to limit the results to one of the id spaces ...
2.725005
3.304687
0.824588
if not (cache and ('audio_summary' in self.cache)): response = self.get_attribute('profile', bucket='audio_summary') if response['songs'] and 'audio_summary' in response['songs'][0]: self.cache['audio_summary'] = response['songs'][0]['audio_summary'] ...
def get_audio_summary(self, cache=True)
Get an audio summary of a song containing mode, tempo, key, duration, time signature, loudness, danceability, energy, and analysis_url. Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. ...
2.985229
3.263863
0.914631
if not (cache and ('song_hotttnesss' in self.cache)): response = self.get_attribute('profile', bucket='song_hotttnesss') self.cache['song_hotttnesss'] = response['songs'][0]['song_hotttnesss'] return self.cache['song_hotttnesss']
def get_song_hotttnesss(self, cache=True)
Get our numerical description of how hottt a song currently is Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: A float representing hotttnesss. ...
2.96751
3.46508
0.856405
if not (cache and ('song_type' in self.cache)): response = self.get_attribute('profile', bucket='song_type') if response['songs'][0].has_key('song_type'): self.cache['song_type'] = response['songs'][0]['song_type'] else: self.cache['s...
def get_song_type(self, cache=True)
Get the types of a song. Args: cache (boolean): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: A list of strings, each representing a song type: 'christmas', for example. ...
3.108064
3.320465
0.936033
if not (cache and ('artist_hotttnesss' in self.cache)): response = self.get_attribute('profile', bucket='artist_hotttnesss') self.cache['artist_hotttnesss'] = response['songs'][0]['artist_hotttnesss'] return self.cache['artist_hotttnesss']
def get_artist_hotttnesss(self, cache=True)
Get our numerical description of how hottt a song's artist currently is Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: A float representing hotttnesss. ...
2.983986
3.350185
0.890693
if not (cache and ('artist_familiarity' in self.cache)): response = self.get_attribute('profile', bucket='artist_familiarity') self.cache['artist_familiarity'] = response['songs'][0]['artist_familiarity'] return self.cache['artist_familiarity']
def get_artist_familiarity(self, cache=True)
Get our numerical estimation of how familiar a song's artist currently is to the world Args: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: A float representing familiarity. ...
3.32111
3.894886
0.852685
if not (cache and ('artist_location' in self.cache)): response = self.get_attribute('profile', bucket='artist_location') self.cache['artist_location'] = response['songs'][0]['artist_location'] return self.cache['artist_location']
def get_artist_location(self, cache=True)
Get the location of a song's artist. Args: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: An artist location object. Example: >>> s = song.Song('SOQKVPH12A...
4.096179
5.025835
0.815025
if not (cache and ('song_discovery' in self.cache)): response = self.get_attribute('profile', bucket='song_discovery') self.cache['song_discovery'] = response['songs'][0]['song_discovery'] return self.cache['song_discovery']
def get_song_discovery(self, cache=True)
Args: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: A float representing a song's discovery rank. Example: >>> s = song.Song('SOQKVPH12A58A7AF4D') >>> s.get_song_discovery() ...
4.374842
5.050946
0.866143
if not (cache and ('song_currency' in self.cache)): response = self.get_attribute('profile', bucket='song_currency') self.cache['song_currency'] = response['songs'][0]['song_currency'] return self.cache['song_currency']
def get_song_currency(self, cache=True)
Args: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: A float representing a song's currency rank. Example: >>> s = song.Song('SOQKVPH12A58A7AF4D') >>> s.get...
4.118402
4.941402
0.833448
if not (cache and ('tracks' in self.cache) and (catalog in [td['catalog'] for td in self.cache['tracks']])): kwargs = { 'bucket':['tracks', 'id:%s' % catalog], } response = self.get_attribute('profile', **kwargs) i...
def get_tracks(self, catalog, cache=True)
Get the tracks for a song given a catalog. Args: catalog (str): a string representing the catalog whose track you want to retrieve. Returns: A list of Track dicts. Example: >>> s = song.Song('SOWDASQ12A6310F24F') >>> s.ge...
4.538798
4.323358
1.049832
limit = str(limit).lower() dmca = str(dmca).lower() kwargs = locals() kwargs['bucket'] = kwargs['buckets'] del kwargs['buckets'] kwargs['genre'] = kwargs['genres'] del kwargs['genres'] result = util.callm("%s/%s" % ('playlist', 'basic'), kwargs) return [Song(**util.fix(s_dict...
def basic(type='artist-radio', artist_id=None, artist=None, song_id=None, song=None, track_id=None, dmca=False, results=15, buckets=None, limit=False,genres=None,)
Get a basic playlist Args: Kwargs: type (str): a string representing the playlist type ('artist-radio' or 'song-radio') artist_id (str): the artist_id to seed the playlist artist (str): the name of an artist to seed the playlist song_id (str):...
4.445827
5.335792
0.833208
response = result['response'] status = response['track']['status'].lower() if status == 'pending': # Need to wait for async upload or analyze call to finish. result = _wait_for_pending_track(response['track']['id'], timeout) response = result['response'] status = respon...
def _track_from_response(result, timeout)
This is the function that actually creates the track object
4.900472
4.783424
1.024469
param_dict['format'] = 'json' param_dict['wait'] = 'true' param_dict['bucket'] = 'audio_summary' result = util.callm('track/upload', param_dict, POST = True, socket_timeout = 300, data = data) return _track_from_response(result, timeout)
def _upload(param_dict, timeout, data)
Calls upload either with a local audio file, or a url. Returns a track object.
7.396581
6.113484
1.20988
if not force_upload: try: # Check if this file has already been uploaded. # This is much faster than uploading. md5 = hashlib.md5(file_object.read()).hexdigest() return track_from_md5(md5) except util.EchoNestAPIError: # Fall through t...
def track_from_file(file_object, filetype, timeout=DEFAULT_ASYNC_TIMEOUT, force_upload=False)
Create a track object from a file-like object. NOTE: Does not create the detailed analysis for the Track. Call Track.get_analysis() for that. Args: file_object: a file-like Python object filetype: the file type. Supported types include mp3, ogg, wav, m4a, mp4, au force_upload: skip...
4.152387
4.836733
0.858511
filetype = filetype or filename.split('.')[-1] file_object = open(filename, 'rb') result = track_from_file(file_object, filetype, timeout, force_upload) file_object.close() return result
def track_from_filename(filename, filetype = None, timeout=DEFAULT_ASYNC_TIMEOUT, force_upload=False)
Create a track object from a filename. NOTE: Does not create the detailed analysis for the Track. Call Track.get_analysis() for that. Args: filename: A string containing the path to the input file. filetype: A string indicating the filetype; Defaults to None (type determined by file extens...
2.121013
3.527555
0.60127
param_dict = dict(url = url) return _upload(param_dict, timeout, data=None)
def track_from_url(url, timeout=DEFAULT_ASYNC_TIMEOUT)
Create a track object from a public http URL. NOTE: Does not create the detailed analysis for the Track. Call Track.get_analysis() for that. Args: url: A string giving the URL to read from. This must be on a public machine accessible by HTTP. Example: >>> t = track.track_from_url("htt...
10.989295
29.199274
0.376355
param_dict = dict(id = identifier) return _profile(param_dict, timeout)
def track_from_id(identifier, timeout=DEFAULT_ASYNC_TIMEOUT)
Create a track object from an Echo Nest track ID. NOTE: Does not create the detailed analysis for the Track. Call Track.get_analysis() for that. Args: identifier: A string containing the ID of a previously analyzed track. Example: >>> t = track.track_from_id("TRWFIDS128F92CC4CA") ...
12.811315
40.868458
0.313477
param_dict = dict(md5 = md5) return _profile(param_dict, timeout)
def track_from_md5(md5, timeout=DEFAULT_ASYNC_TIMEOUT)
Create a track object from an md5 hash. NOTE: Does not create the detailed analysis for the Track. Call Track.get_analysis() for that. Args: md5: A string 32 characters long giving the md5 checksum of a track already analyzed. Example: >>> t = track.track_from_md5('b8abf85746ab3416ada...
9.633066
29.483824
0.326724
if self.analysis_url: try: # Try the existing analysis_url first. This expires shortly # after creation. try: json_string = urllib2.urlopen(self.analysis_url).read() except urllib2.HTTPError: ...
def get_analysis(self)
Retrieve the detailed analysis for the track, if available. Raises Exception if unable to create the detailed analysis.
3.75821
3.371435
1.114721
"gets the tempo for a song" results = song.search(artist=artist, title=title, results=1, buckets=['audio_summary']) if len(results) > 0: return results[0].audio_summary['tempo'] else: return None
def get_tempo(artist, title)
gets the tempo for a song
4.671271
4.65591
1.003299
result = util.callm("%s/%s" % ('sandbox', 'list'), {'sandbox':sandbox_name, 'results': results, 'start': start}) assets = result['response']['assets'] start = result['response']['start'] total = result['response']['total'] return ResultList(assets, start, total)
def list(sandbox_name, results=15, start=0)
Returns a list of all assets available in this sandbox Args: sandbox_name (str): A string representing the name of the sandbox Kwargs: results (int): An integer number of results to return start (int): An integer starting value for the result set Returns: ...
4.949996
6.364689
0.777728
limit = str(limit).lower() fuzzy_match = str(fuzzy_match).lower() kwargs = locals() kwargs['bucket'] = buckets or [] del kwargs['buckets'] result = util.callm("%s/%s" % ('artist', 'search'), kwargs) return [Artist(**util.fix(a_dict)) for a_dict in result['response']['artists']]
def search(name=None, description=None, style=None, mood=None, start=0, \ results=15, buckets=None, limit=False, \ fuzzy_match=False, sort=None, max_familiarity=None, min_familiarity=None, \ max_hotttnesss=None, min_hotttnesss=None, test_new_things=None, rank_type=None, \ ...
Search for artists by name, description, or constraint. Args: Kwargs: name (str): the name of an artist description (str): A string describing the artist style (str): A string describing the style/genre of the artist mood (str): A string descr...
5.123016
7.419118
0.690516
buckets = buckets or [] kwargs = {} if start: kwargs['start'] = start if results: kwargs['results'] = results if buckets: kwargs['bucket'] = buckets if limit: kwargs['limit'] = 'true' result = util.callm("%s/%s" % ('artist', 'top_hottt'), kwargs...
def top_hottt(start=0, results=15, buckets = None, limit=False)
Get the top hotttest artists, according to The Echo Nest Args: Kwargs: results (int): An integer number of results to return start (int): An integer starting value for the result set buckets (list): A list of strings specifying which buckets to retrieve ...
4.061638
4.492228
0.904148
kwargs = {} if results: kwargs['results'] = results result = util.callm("%s/%s" % ('artist', 'top_terms'), kwargs) return result['response']['terms']
def top_terms(results=15)
Get a list of the top overall terms Args: Kwargs: results (int): An integer number of results to return Returns: A list of term document dicts Example: >>> terms = artist.top_terms(results=5) >>> terms [{u'frequency': 1.0, u'name': u'rock'}, ...
10.789482
10.956903
0.98472
buckets = buckets or [] kwargs = {} if ids: if not isinstance(ids, list): ids = [ids] kwargs['id'] = ids if names: if not isinstance(names, list): names = [names] kwargs['name'] = names if max_familiarity is not None: kwargs[...
def similar(names=None, ids=None, start=0, results=15, buckets=None, limit=False, max_familiarity=None, min_familiarity=None, max_hotttnesss=None, min_hotttnesss=None, seed_catalog=None,artist_start_year_before=None, \ artist_start_year_after=None,artist_end_year_before=None,artist_end_year_afte...
Return similar artists to this one Args: Kwargs: ids (str/list): An artist id or list of ids names (str/list): An artist name or list of names results (int): An integer number of results to return buckets (list): A list of strings specifying w...
1.477974
1.591486
0.928675
buckets = buckets or [] kwargs = {} kwargs['text'] = text if max_familiarity is not None: kwargs['max_familiarity'] = max_familiarity if min_familiarity is not None: kwargs['min_familiarity'] = min_familiarity if max_hotttnesss is not None: kwargs['max_hot...
def extract(text='', start=0, results=15, buckets=None, limit=False, max_familiarity=None, min_familiarity=None, max_hotttnesss=None, min_hotttnesss=None)
Extract artist names from a block of text. Args: Kwargs: text (str): The text to extract artists from start (int): An integer starting value for the result set results (int): An integer number of results to return buckets (list): A list of strings specify...
2.081919
2.193518
0.949123
buckets = buckets or [] kwargs = {} kwargs['q'] = q if max_familiarity is not None: kwargs['max_familiarity'] = max_familiarity if min_familiarity is not None: kwargs['min_familiarity'] = min_familiarity if max_hotttnesss is not None: kwargs['max_hotttnesss'] = ma...
def suggest(q='', results=15, buckets=None, limit=False, max_familiarity=None, min_familiarity=None, max_hotttnesss=None, min_hotttnesss=None)
Suggest artists based upon partial names. Args: Kwargs: q (str): The text to suggest artists from results (int): An integer number of results to return buckets (list): A list of strings specifying which buckets to retrieve limit (bool): A boolean indicating whether or not to...
2.034309
2.256215
0.901647
if cache and ('biographies' in self.cache) and results==15 and start==0 and license==None: return self.cache['biographies'] else: response = self.get_attribute('biographies', results=results, start=start, license=license) if results==15 and start==0 and licen...
def get_biographies(self, results=15, start=0, license=None, cache=True)
Get a list of artist biographies Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. results (int): An integer number of results to return start (...
2.43325
2.797423
0.869818
if not (cache and ('familiarity' in self.cache)): response = self.get_attribute('familiarity') self.cache['familiarity'] = response['artist']['familiarity'] return self.cache['familiarity']
def get_familiarity(self, cache=True)
Get our numerical estimation of how familiar an artist currently is to the world Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: A float representing fami...
3.284745
4.447724
0.738523
if not (cache and ('foreign_ids' in self.cache) and filter(lambda d: d.get('catalog') == idspace, self.cache['foreign_ids'])): response = self.get_attribute('profile', bucket=['id:'+idspace]) foreign_ids = response['artist'].get("foreign_ids", []) self.cache['foreign...
def get_foreign_id(self, idspace='musicbrainz', cache=True)
Get the foreign id for this artist for a specific id space Args: Kwargs: idspace (str): A string indicating the idspace to fetch a foreign id for. Returns: A foreign ID string Example: >>> a = artist.Artist('fab...
4.102266
4.244253
0.966546
if not (cache and ('twitter' in self.cache)): response = self.get_attribute('twitter') self.cache['twitter'] = response['artist'].get('twitter') return self.cache['twitter']
def get_twitter_id(self, cache=True)
Get the twitter id for this artist if it exists Args: Kwargs: Returns: A twitter ID string Example: >>> a = artist.Artist('big boi') >>> a.get_twitter_id() u'BigBoi' >>>
5.222138
6.200173
0.842257
if not (cache and ('hotttnesss' in self.cache)): response = self.get_attribute('hotttnesss') self.cache['hotttnesss'] = response['artist']['hotttnesss'] return self.cache['hotttnesss']
def get_hotttnesss(self, cache=True)
Get our numerical description of how hottt an artist currently is Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: float: the hotttnesss value ...
2.890868
3.412634
0.847107
if cache and ('images' in self.cache) and results==15 and start==0 and license==None: return self.cache['images'] else: response = self.get_attribute('images', results=results, start=start, license=license) total = response.get('total') or 0 ...
def get_images(self, results=15, start=0, license=None, cache=True)
Get a list of artist images Args: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. results (int): An integer number of results to return start (int): An integer starting valu...
2.939605
3.239257
0.907494
if cache and ('news' in self.cache) and results==15 and start==0 and not high_relevance: return self.cache['news'] else: high_relevance = 'true' if high_relevance else 'false' response = self.get_attribute('news', results=results, start=start, high_relevance=...
def get_news(self, results=15, start=0, cache=True, high_relevance=False)
Get a list of news articles found on the web related to an artist Args: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. results (int): An integer number of results to return ...
2.650637
2.997481
0.884288
buckets = buckets or [] kwargs = {} if max_familiarity: kwargs['max_familiarity'] = max_familiarity if min_familiarity: kwargs['min_familiarity'] = min_familiarity if max_hotttnesss: kwargs['max_hotttnesss'] = max_hotttnesss if...
def get_similar(self, results=15, start=0, buckets=None, limit=False, cache=True, max_familiarity=None, min_familiarity=None, \ max_hotttnesss=None, min_hotttnesss=None, min_results=None, reverse=False, artist_start_year_before=None, \ artist_start_year_after=None,artist_end_year...
Return similar artists to this one Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. results (int): An integer number of results to return start...
1.564819
1.647794
0.949645
if cache and ('songs' in self.cache) and results==15 and start==0: if not isinstance(self.cache['songs'][0], Song): song_objects = [] for s in self.cache["songs"]: song_objects.append(Song(id=s['id'], ...
def get_songs(self, cache=True, results=15, start=0)
Get the songs associated with an artist Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. results (int): An integer number of results to return ...
2.70971
2.736457
0.990226
if cache and ('terms' in self.cache) and sort=='weight': return self.cache['terms'] else: response = self.get_attribute('terms', sort=sort) if sort=='weight': self.cache['terms'] = response['terms'] return response['terms']
def get_terms(self, sort='weight', cache=True)
Get the terms associated with an artist Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. sort (str): A string specifying the desired sorting type (weight or frequency) ...
2.79619
3.280112
0.852468
if not (cache and ('urls' in self.cache)): response = self.get_attribute('urls') self.cache['urls'] = response['urls'] return self.cache['urls']
def get_urls(self, cache=True)
Get the urls for an artist Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Results: A url document dict Example: >>> a = artist.A...
3.557356
5.000115
0.711455
if cache and ('video' in self.cache) and results==15 and start==0: return self.cache['video'] else: response = self.get_attribute('video', results=results, start=start) if results==15 and start==0: self.cache['video'] = ResultList(response['vi...
def get_video(self, results=15, start=0, cache=True)
Get a list of video documents found on the web related to an artist Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. results (int): An integer number of results to retu...
3.135012
3.569282
0.878331
if cache and ('years_active' in self.cache): return self.cache['years_active'] else: response = self.get_attribute('profile', bucket=['years_active']) self.cache['years_active'] = response['artist']['years_active'] return response['artist']['years...
def get_years_active(self, cache=True)
Get a list of years active dictionaries for an artist Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: A list of years active dictionaries; list contains a...
3.745977
4.0955
0.914657
if not cache or not ('doc_counts' in self.cache): response = self.get_attribute("profile", bucket='doc_counts') self.cache['doc_counts'] = response['artist']['doc_counts'] return self.cache['doc_counts']
def get_doc_counts(self, cache=True)
Get the number of related documents of various types for the artist. The types include audio, biographies, blogs, images, news, reviews, songs, videos. Note that these documents can be retrieved by calling artist.<document type>, for example, artist.biographies. Args: ...
5.574224
5.659121
0.984998
''' run is a wrapper to create, start, attach, and delete a container. Equivalent command line example: singularity oci run -b ~/bundle mycontainer Parameters ========== bundle: the full path to the bundle folder container_id: an optional container_id. If n...
def run(self, bundle, container_id=None, log_path=None, pid_file=None, log_format="kubernetes")
run is a wrapper to create, start, attach, and delete a container. Equivalent command line example: singularity oci run -b ~/bundle mycontainer Parameters ========== bundle: the full path to the bundle folder container_id: an optional container_id. If not provid...
6.085235
1.439508
4.227303
def create(self, bundle, container_id=None, empty_process=False, log_path=None, pid_file=None, sync_socket=None, log_format="kubernetes"): ''' use the client to create a container from a bundle directory. The bun...
use the client to create a container from a bundle directory. The bundle directory should have a config.json. You must be the root user to create a runtime. Equivalent command line example: singularity oci create [create options...] <container_ID> Parameters ==...
null
null
null
bot.exit('Bundle not found at %s' % bundle) # Add the bundle cmd = cmd + ['--bundle', bundle] # Additional Logging Files cmd = cmd + ['--log-format', log_format] if log_path != None: cmd = cmd + ['--log-path', log_path] if pid_file != None: cmd = cmd + ['--pid-file', p...
def _run(self, bundle, container_id=None, empty_process=False, log_path=None, pid_file=None, sync_socket=None, command="run", log_format="kubernetes"): ''' _run is the base function for run and create, the onl...
_run is the base function for run and create, the only difference between the two being that run does not have an option for sync_socket. Equivalent command line example: singularity oci create [create options...] <container_ID> Parameters ========== bundle: th...
3.855765
4.060985
0.949466
'''delete an instance based on container_id. Parameters ========== container_id: the container_id to delete sudo: whether to issue the command with sudo (or not) a container started with sudo will belong to the root user If started by a user, the user needs to ...
def delete(self, container_id=None, sudo=None)
delete an instance based on container_id. Parameters ========== container_id: the container_id to delete sudo: whether to issue the command with sudo (or not) a container started with sudo will belong to the root user If started by a user, the user needs to control...
8.901788
2.65102
3.357873
'''attach to a container instance based on container_id Parameters ========== container_id: the container_id to delete sudo: whether to issue the command with sudo (or not) a container started with sudo will belong to the root user If started by a user, the use...
def attach(self, container_id=None, sudo=False)
attach to a container instance based on container_id Parameters ========== container_id: the container_id to delete sudo: whether to issue the command with sudo (or not) a container started with sudo will belong to the root user If started by a user, the user needs...
8.850534
3.028266
2.922641
'''execute a command to a container instance based on container_id Parameters ========== container_id: the container_id to delete command: the command to execute to the container sudo: whether to issue the command with sudo (or not) a container started with sudo will...
def execute(self, command=None, container_id=None, sudo=False, stream=False)
execute a command to a container instance based on container_id Parameters ========== container_id: the container_id to delete command: the command to execute to the container sudo: whether to issue the command with sudo (or not) a container started with sudo will belong...
6.691752
2.273421
2.943472
'''update container cgroup resources for a specific container_id, The container must have state "running" or "created." Singularity Example: singularity oci update [update options...] <container_ID> singularity oci update --from-file cgroups-update.json mycontainer Param...
def update(self, container_id, from_file=None)
update container cgroup resources for a specific container_id, The container must have state "running" or "created." Singularity Example: singularity oci update [update options...] <container_ID> singularity oci update --from-file cgroups-update.json mycontainer Parameters ...
7.845707
2.747705
2.855368
''' get the client and perform imports not on init, in case there are any initialization or import errors. Parameters ========== quiet: if True, suppress most output about the client debug: turn on debugging mode ''' from spython.utils import get_singularity_vers...
def get_client(quiet=False, debug=False)
get the client and perform imports not on init, in case there are any initialization or import errors. Parameters ========== quiet: if True, suppress most output about the client debug: turn on debugging mode
5.360266
4.202589
1.275468
'''build a singularity image, optionally for an isolated build (requires sudo). If you specify to stream, expect the image name and an iterator to be returned. image, builder = Client.build(...) Parameters ========== recipe: the path to the recipe file (or source...
def build(self, recipe=None, image=None, isolated=False, sandbox=False, writable=False, build_folder=None, robot_name=False, ext='simg', sudo=True, stream=False)
build a singularity image, optionally for an isolated build (requires sudo). If you specify to stream, expect the image name and an iterator to be returned. image, builder = Client.build(...) Parameters ========== recipe: the path to the recipe file (or source to buil...
6.458857
2.732858
2.363408
'''start an instance. This is done by default when an instance is created. Parameters ========== image: optionally, an image uri (if called as a command from Client) name: a name for the instance sudo: if the user wants to run the command with sudo capture: capture output,...
def start(self, image=None, name=None, args=None, sudo=False, options=[], capture=False)
start an instance. This is done by default when an instance is created. Parameters ========== image: optionally, an image uri (if called as a command from Client) name: a name for the instance sudo: if the user wants to run the command with sudo capture: capture output, defaul...
7.304107
3.667905
1.991356
'''import will import (stdin) to the image Parameters ========== image_path: path to image to import to. input_source: input source or file import_type: if not specified, imports whatever function is given ''' from spython.utils import check_install check_ins...
def importcmd(self, image_path, input_source)
import will import (stdin) to the image Parameters ========== image_path: path to image to import to. input_source: input source or file import_type: if not specified, imports whatever function is given
11.528694
4.345716
2.652887
'''inspect will show labels, defile, runscript, and tests for an image Parameters ========== image: path of image to inspect json: print json instead of raw text (default True) quiet: Don't print result to the screen (default True) app: if defined, return help in conte...
def inspect(self, image=None, json=True, app=None, quiet=True)
inspect will show labels, defile, runscript, and tests for an image Parameters ========== image: path of image to inspect json: print json instead of raw text (default True) quiet: Don't print result to the screen (default True) app: if defined, return help in context of a...
7.010474
4.356123
1.609338
'''fix up the labels, meaning parse to json if needed, and return original updated object Parameters ========== result: the json object to parse from inspect ''' if "data" in result: labels = result['data']['attributes'].get('labels') or {} elif 'attributes' in res...
def parse_labels(result)
fix up the labels, meaning parse to json if needed, and return original updated object Parameters ========== result: the json object to parse from inspect
6.293994
2.865786
2.196254
'''give the user an ipython shell ''' # The client will announce itself (backend/database) unless it's get from spython.main import get_client from spython.main.parse import ( DockerRecipe, SingularityRecipe ) client = get_client() client.load(image) # Add recipe parsers client.Do...
def ipython(image)
give the user an ipython shell
15.395097
14.058626
1.095064
'''parse_env will parse a single line (with prefix like ENV removed) to a list of commands in the format KEY=VALUE For example: ENV PYTHONBUFFER 1 --> [PYTHONBUFFER=1] ::Notes Docker: https://docs.docker.com/engine/reference/builder/#env ''' if not isinstance(envlist, list): ...
def parse_env(envlist)
parse_env will parse a single line (with prefix like ENV removed) to a list of commands in the format KEY=VALUE For example: ENV PYTHONBUFFER 1 --> [PYTHONBUFFER=1] ::Notes Docker: https://docs.docker.com/engine/reference/builder/#env
5.162757
2.847352
1.813178
'''setup required adding content from the host to the rootfs, so we try to capture with with ADD. ''' bot.warning('SETUP is error prone, please check output.') for line in lines: # For all lines, replace rootfs with actual root / line = re.sub('[$]{?S...
def _setup(self, lines)
setup required adding content from the host to the rootfs, so we try to capture with with ADD.
12.855629
7.167491
1.793602
''' get the FROM container image name from a FROM line! Parameters ========== line: the line from the recipe file to parse for FROM ''' self.fromHeader = line bot.debug('FROM %s' %self.fromHeader)
def _from(self, line)
get the FROM container image name from a FROM line! Parameters ========== line: the line from the recipe file to parse for FROM
21.110697
5.590123
3.776428
'''env will parse a list of environment lines and simply remove any blank lines, or those with export. Dockerfiles don't usually have exports. Parameters ========== lines: A list of environment pair lines. ''' environ = [x for x in lines ...
def _env(self, lines)
env will parse a list of environment lines and simply remove any blank lines, or those with export. Dockerfiles don't usually have exports. Parameters ========== lines: A list of environment pair lines.
22.041903
3.550969
6.207293
''' comments is a wrapper for comment, intended to be given a list of comments. Parameters ========== lines: the list of lines to parse ''' for line in lines: comment = self._comment(line) self.comments.append(co...
def _comments(self, lines)
comments is a wrapper for comment, intended to be given a list of comments. Parameters ========== lines: the list of lines to parse
10.42958
3.352263
3.111205
'''_parse the runscript to be the Docker CMD. If we have one line, call it directly. If not, write the entrypoint into a script. Parameters ========== lines: the line from the recipe file to parse for CMD ''' lines = [x for x in lines if x not in ['...
def _run(self, lines)
_parse the runscript to be the Docker CMD. If we have one line, call it directly. If not, write the entrypoint into a script. Parameters ========== lines: the line from the recipe file to parse for CMD
11.298234
4.463459
2.531273
'''mapping will take the section name from a Singularity recipe and return a map function to add it to the appropriate place. Any lines that don't cleanly map are assumed to be comments. Parameters ========== section: the name of the Singularity recipe s...
def _get_mapping(self, section)
mapping will take the section name from a Singularity recipe and return a map function to add it to the appropriate place. Any lines that don't cleanly map are assumed to be comments. Parameters ========== section: the name of the Singularity recipe section ...
7.315881
2.440545
2.997642
'''parse is the base function for parsing the recipe, and extracting elements into the correct data structures. Everything is parsed into lists or dictionaries that can be assembled again on demand. Singularity: we parse files/labels first, then install. ...
def _parse(self)
parse is the base function for parsing the recipe, and extracting elements into the correct data structures. Everything is parsed into lists or dictionaries that can be assembled again on demand. Singularity: we parse files/labels first, then install. cd f...
17.562183
3.44835
5.092924
'''load the From section of the recipe for the Dockerfile. ''' # Remove any comments line = line.split('#',1)[0] line = re.sub('(F|f)(R|r)(O|o)(M|m):','', line).strip() bot.info('FROM %s' %line) self.config['from'] = line
def _load_from(self, line)
load the From section of the recipe for the Dockerfile.
9.04002
5.804985
1.557286
'''read in a section to a list, and stop when we hit the next section ''' members = [] while True: if len(lines) == 0: break next_line = lines[0] # The end of a section if next_line.strip().startswith("%")...
def _load_section(self, lines, section)
read in a section to a list, and stop when we hit the next section
5.100369
4.035373
1.263915
'''load will return a loaded in singularity recipe. The idea is that these sections can then be parsed into a Dockerfile, or printed back into their original form. Returns ======= config: a parsed recipe Singularity recipe ''' # Comments b...
def load_recipe(self)
load will return a loaded in singularity recipe. The idea is that these sections can then be parsed into a Dockerfile, or printed back into their original form. Returns ======= config: a parsed recipe Singularity recipe
7.266346
4.454597
1.631202
'''parse a line for a section, and return the parsed section (if not None) Parameters ========== line: the line to parse section: the current (or previous) section Resulting data structure is: config['post'] (in lowercase) '...
def _add_section(self, line, section=None)
parse a line for a section, and return the parsed section (if not None) Parameters ========== line: the line to parse section: the current (or previous) section Resulting data structure is: config['post'] (in lowercase)
7.10908
3.284501
2.164432