Search is not available for this dataset
text
stringlengths 75
104k
|
|---|
def unregister_hook(self, func):
""" Unregisters a hook. For further explanation, please have a look at ``register_hook``. """
if func in self.hooks:
self.hooks.remove(func)
|
async def dispatch_event(self, event):
""" Dispatches an event to all registered hooks. """
log.debug('Dispatching event of type {} to {} hooks'.format(event.__class__.__name__, len(self.hooks)))
for hook in self.hooks:
try:
if asyncio.iscoroutinefunction(hook):
await hook(event)
else:
hook(event)
except Exception as e: # pylint: disable=broad-except
# Catch generic exception thrown by user hooks
log.warning(
'Encountered exception while dispatching an event to hook `{}` ({})'.format(hook.__name__, str(e)))
if isinstance(event, (TrackEndEvent, TrackExceptionEvent, TrackStuckEvent)) and event.player:
await event.player.handle_event(event)
|
async def update_state(self, data):
""" Updates a player's state when a payload with opcode ``playerUpdate`` is received. """
guild_id = int(data['guildId'])
if guild_id in self.players:
player = self.players.get(guild_id)
player.position = data['state'].get('position', 0)
player.position_timestamp = data['state']['time']
|
async def get_tracks(self, query):
""" Returns a Dictionary containing search results for a given query. """
log.debug('Requesting tracks for query {}'.format(query))
async with self.http.get(self.rest_uri + quote(query), headers={'Authorization': self.password}) as res:
return await res.json(content_type=None)
|
async def on_socket_response(self, data):
"""
This coroutine will be called every time an event from Discord is received.
It is used to update a player's voice state through forwarding a payload via the WebSocket connection to Lavalink.
-------------
:param data:
The payload received from Discord.
"""
# INTERCEPT VOICE UPDATES
if not data or data.get('t', '') not in ['VOICE_STATE_UPDATE', 'VOICE_SERVER_UPDATE']:
return
if data['t'] == 'VOICE_SERVER_UPDATE':
self.voice_state.update({
'op': 'voiceUpdate',
'guildId': data['d']['guild_id'],
'event': data['d']
})
else:
if int(data['d']['user_id']) != self.bot.user.id:
return
self.voice_state.update({'sessionId': data['d']['session_id']})
guild_id = int(data['d']['guild_id'])
if self.players[guild_id]:
self.players[guild_id].channel_id = data['d']['channel_id']
if {'op', 'guildId', 'sessionId', 'event'} == self.voice_state.keys():
await self.ws.send(**self.voice_state)
self.voice_state.clear()
|
def destroy(self):
""" Destroys the Lavalink client. """
self.ws.destroy()
self.bot.remove_listener(self.on_socket_response)
self.hooks.clear()
|
def format_time(time):
""" Formats the given time into HH:MM:SS. """
hours, remainder = divmod(time / 1000, 3600)
minutes, seconds = divmod(remainder, 60)
return '%02d:%02d:%02d' % (hours, minutes, seconds)
|
def build(self, track, requester):
""" Returns an optional AudioTrack. """
try:
self.track = track['track']
self.identifier = track['info']['identifier']
self.can_seek = track['info']['isSeekable']
self.author = track['info']['author']
self.duration = track['info']['length']
self.stream = track['info']['isStream']
self.title = track['info']['title']
self.uri = track['info']['uri']
self.requester = requester
return self
except KeyError:
raise InvalidTrack('An invalid track was passed.')
|
async def _previous(self, ctx):
""" Plays the previous song. """
player = self.bot.lavalink.players.get(ctx.guild.id)
try:
await player.play_previous()
except lavalink.NoPreviousTrack:
await ctx.send('There is no previous song to play.')
|
async def _playnow(self, ctx, *, query: str):
""" Plays immediately a song. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.queue and not player.is_playing:
return await ctx.invoke(self._play, query=query)
query = query.strip('<>')
if not url_rx.match(query):
query = f'ytsearch:{query}'
results = await self.bot.lavalink.get_tracks(query)
if not results or not results['tracks']:
return await ctx.send('Nothing found!')
tracks = results['tracks']
track = tracks.pop(0)
if results['loadType'] == 'PLAYLIST_LOADED':
for _track in tracks:
player.add(requester=ctx.author.id, track=_track)
await player.play_now(requester=ctx.author.id, track=track)
|
async def _playat(self, ctx, index: int):
""" Plays the queue from a specific point. Disregards tracks before the index. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if index < 1:
return await ctx.send('Invalid specified index.')
if len(player.queue) < index:
return await ctx.send('This index exceeds the queue\'s length.')
await player.play_at(index-1)
|
async def _find(self, ctx, *, query):
""" Lists the first 10 search results from a given query. """
if not query.startswith('ytsearch:') and not query.startswith('scsearch:'):
query = 'ytsearch:' + query
results = await self.bot.lavalink.get_tracks(query)
if not results or not results['tracks']:
return await ctx.send('Nothing found')
tracks = results['tracks'][:10] # First 10 results
o = ''
for index, track in enumerate(tracks, start=1):
track_title = track["info"]["title"]
track_uri = track["info"]["uri"]
o += f'`{index}.` [{track_title}]({track_uri})\n'
embed = discord.Embed(color=discord.Color.blurple(), description=o)
await ctx.send(embed=embed)
|
def add_suggestions(self, *suggestions, **kwargs):
"""
Add suggestion terms to the AutoCompleter engine. Each suggestion has a score and string.
If kwargs['increment'] is true and the terms are already in the server's dictionary, we increment their scores
"""
pipe = self.redis.pipeline()
for sug in suggestions:
args = [AutoCompleter.SUGADD_COMMAND, self.key, sug.string, sug.score]
if kwargs.get('increment'):
args.append(AutoCompleter.INCR)
if sug.payload:
args.append('PAYLOAD')
args.append(sug.payload)
pipe.execute_command(*args)
return pipe.execute()[-1]
|
def delete(self, string):
"""
Delete a string from the AutoCompleter index.
Returns 1 if the string was found and deleted, 0 otherwise
"""
return self.redis.execute_command(AutoCompleter.SUGDEL_COMMAND, self.key, string)
|
def get_suggestions(self, prefix, fuzzy = False, num = 10, with_scores = False, with_payloads=False):
"""
Get a list of suggestions from the AutoCompleter, for a given prefix
### Parameters:
- **prefix**: the prefix we are searching. **Must be valid ascii or utf-8**
- **fuzzy**: If set to true, the prefix search is done in fuzzy mode.
**NOTE**: Running fuzzy searches on short (<3 letters) prefixes can be very slow, and even scan the entire index.
- **with_scores**: if set to true, we also return the (refactored) score of each suggestion.
This is normally not needed, and is NOT the original score inserted into the index
- **with_payloads**: Return suggestion payloads
- **num**: The maximum number of results we return. Note that we might return less. The algorithm trims irrelevant suggestions.
Returns a list of Suggestion objects. If with_scores was False, the score of all suggestions is 1.
"""
args = [AutoCompleter.SUGGET_COMMAND, self.key, prefix, 'MAX', num]
if fuzzy:
args.append(AutoCompleter.FUZZY)
if with_scores:
args.append(AutoCompleter.WITHSCORES)
if with_payloads:
args.append(AutoCompleter.WITHPAYLOADS)
ret = self.redis.execute_command(*args)
results = []
if not ret:
return results
parser = SuggestionParser(with_scores, with_payloads, ret)
return [s for s in parser]
|
def create_index(self, fields, no_term_offsets=False,
no_field_flags=False, stopwords = None):
"""
Create the search index. The index must not already exist.
### Parameters:
- **fields**: a list of TextField or NumericField objects
- **no_term_offsets**: If true, we will not save term offsets in the index
- **no_field_flags**: If true, we will not save field flags that allow searching in specific fields
- **stopwords**: If not None, we create the index with this custom stopword list. The list can be empty
"""
args = [self.CREATE_CMD, self.index_name]
if no_term_offsets:
args.append(self.NOOFFSETS)
if no_field_flags:
args.append(self.NOFIELDS)
if stopwords is not None and isinstance(stopwords, (list, tuple, set)):
args += [self.STOPWORDS, len(stopwords)]
if len(stopwords) > 0:
args += list(stopwords)
args.append('SCHEMA')
args += list(itertools.chain(*(f.redis_args() for f in fields)))
return self.redis.execute_command(*args)
|
def _add_document(self, doc_id, conn=None, nosave=False, score=1.0, payload=None,
replace=False, partial=False, language=None, **fields):
"""
Internal add_document used for both batch and single doc indexing
"""
if conn is None:
conn = self.redis
if partial:
replace = True
args = [self.ADD_CMD, self.index_name, doc_id, score]
if nosave:
args.append('NOSAVE')
if payload is not None:
args.append('PAYLOAD')
args.append(payload)
if replace:
args.append('REPLACE')
if partial:
args.append('PARTIAL')
if language:
args += ['LANGUAGE', language]
args.append('FIELDS')
args += list(itertools.chain(*fields.items()))
return conn.execute_command(*args)
|
def add_document(self, doc_id, nosave=False, score=1.0, payload=None,
replace=False, partial=False, language=None, **fields):
"""
Add a single document to the index.
### Parameters
- **doc_id**: the id of the saved document.
- **nosave**: if set to true, we just index the document, and don't save a copy of it. This means that searches will just return ids.
- **score**: the document ranking, between 0.0 and 1.0
- **payload**: optional inner-index payload we can save for fast access in scoring functions
- **replace**: if True, and the document already is in the index, we perform an update and reindex the document
- **partial**: if True, the fields specified will be added to the existing document.
This has the added benefit that any fields specified with `no_index`
will not be reindexed again. Implies `replace`
- **language**: Specify the language used for document tokenization.
- **fields** kwargs dictionary of the document fields to be saved and/or indexed.
NOTE: Geo points shoule be encoded as strings of "lon,lat"
"""
return self._add_document(doc_id, conn=None, nosave=nosave, score=score,
payload=payload, replace=replace,
partial=partial, language=language, **fields)
|
def delete_document(self, doc_id, conn=None):
"""
Delete a document from index
Returns 1 if the document was deleted, 0 if not
"""
if conn is None:
conn = self.redis
return conn.execute_command(self.DEL_CMD, self.index_name, doc_id)
|
def load_document(self, id):
"""
Load a single document by id
"""
fields = self.redis.hgetall(id)
if six.PY3:
f2 = {to_string(k): to_string(v) for k, v in fields.items()}
fields = f2
try:
del fields['id']
except KeyError:
pass
return Document(id=id, **fields)
|
def info(self):
"""
Get info an stats about the the current index, including the number of documents, memory consumption, etc
"""
res = self.redis.execute_command('FT.INFO', self.index_name)
it = six.moves.map(to_string, res)
return dict(six.moves.zip(it, it))
|
def search(self, query):
"""
Search the index for a given query, and return a result of documents
### Parameters
- **query**: the search query. Either a text for simple queries with default parameters, or a Query object for complex queries.
See RediSearch's documentation on query format
- **snippet_sizes**: A dictionary of {field: snippet_size} used to trim and format the result. e.g.e {'body': 500}
"""
args, query = self._mk_query_args(query)
st = time.time()
res = self.redis.execute_command(self.SEARCH_CMD, *args)
return Result(res,
not query._no_content,
duration=(time.time() - st) * 1000.0,
has_payload=query._with_payloads)
|
def aggregate(self, query):
"""
Issue an aggregation query
### Parameters
**query**: This can be either an `AggeregateRequest`, or a `Cursor`
An `AggregateResult` object is returned. You can access the rows from its
`rows` property, which will always yield the rows of the result
"""
if isinstance(query, AggregateRequest):
has_schema = query._with_schema
has_cursor = bool(query._cursor)
cmd = [self.AGGREGATE_CMD, self.index_name] + query.build_args()
elif isinstance(query, Cursor):
has_schema = False
has_cursor = True
cmd = [self.CURSOR_CMD, 'READ', self.index_name] + query.build_args()
else:
raise ValueError('Bad query', query)
raw = self.redis.execute_command(*cmd)
if has_cursor:
if isinstance(query, Cursor):
query.cid = raw[1]
cursor = query
else:
cursor = Cursor(raw[1])
raw = raw[0]
else:
cursor = None
if query._with_schema:
schema = raw[0]
rows = raw[2:]
else:
schema = None
rows = raw[1:]
res = AggregateResult(rows, cursor, schema)
return res
|
def alias(self, alias):
"""
Set the alias for this reducer.
### Parameters
- **alias**: The value of the alias for this reducer. If this is the
special value `aggregation.FIELDNAME` then this reducer will be
aliased using the same name as the field upon which it operates.
Note that using `FIELDNAME` is only possible on reducers which
operate on a single field value.
This method returns the `Reducer` object making it suitable for
chaining.
"""
if alias is FIELDNAME:
if not self._field:
raise ValueError("Cannot use FIELDNAME alias with no field")
# Chop off initial '@'
alias = self._field[1:]
self._alias = alias
return self
|
def group_by(self, fields, *reducers):
"""
Specify by which fields to group the aggregation.
### Parameters
- **fields**: Fields to group by. This can either be a single string,
or a list of strings. both cases, the field should be specified as
`@field`.
- **reducers**: One or more reducers. Reducers may be found in the
`aggregation` module.
"""
group = Group(fields, reducers)
self._groups.append(group)
return self
|
def apply(self, **kwexpr):
"""
Specify one or more projection expressions to add to each result
### Parameters
- **kwexpr**: One or more key-value pairs for a projection. The key is
the alias for the projection, and the value is the projection
expression itself, for example `apply(square_root="sqrt(@foo)")`
"""
for alias, expr in kwexpr.items():
self._projections.append([alias, expr])
return self
|
def limit(self, offset, num):
"""
Sets the limit for the most recent group or query.
If no group has been defined yet (via `group_by()`) then this sets
the limit for the initial pool of results from the query. Otherwise,
this limits the number of items operated on from the previous group.
Setting a limit on the initial search results may be useful when
attempting to execute an aggregation on a sample of a large data set.
### Parameters
- **offset**: Result offset from which to begin paging
- **num**: Number of results to return
Example of sorting the initial results:
```
AggregateRequest('@sale_amount:[10000, inf]')\
.limit(0, 10)\
.group_by('@state', r.count())
```
Will only group by the states found in the first 10 results of the
query `@sale_amount:[10000, inf]`. On the other hand,
```
AggregateRequest('@sale_amount:[10000, inf]')\
.limit(0, 1000)\
.group_by('@state', r.count()\
.limit(0, 10)
```
Will group all the results matching the query, but only return the
first 10 groups.
If you only wish to return a *top-N* style query, consider using
`sort_by()` instead.
"""
limit = Limit(offset, num)
if self._groups:
self._groups[-1].limit = limit
else:
self._limit = limit
return self
|
def sort_by(self, *fields, **kwargs):
"""
Indicate how the results should be sorted. This can also be used for
*top-N* style queries
### Parameters
- **fields**: The fields by which to sort. This can be either a single
field or a list of fields. If you wish to specify order, you can
use the `Asc` or `Desc` wrapper classes.
- **max**: Maximum number of results to return. This can be used instead
of `LIMIT` and is also faster.
Example of sorting by `foo` ascending and `bar` descending:
```
sort_by(Asc('@foo'), Desc('@bar'))
```
Return the top 10 customers:
```
AggregateRequest()\
.group_by('@customer', r.sum('@paid').alias(FIELDNAME))\
.sort_by(Desc('@paid'), max=10)
```
"""
self._max = kwargs.get('max', 0)
if isinstance(fields, (string_types, SortDirection)):
fields = [fields]
for f in fields:
if isinstance(f, SortDirection):
self._sortby += [f.field, f.DIRSTRING]
else:
self._sortby.append(f)
return self
|
def summarize(self, fields=None, context_len=None, num_frags=None, sep=None):
"""
Return an abridged format of the field, containing only the segments of
the field which contain the matching term(s).
If `fields` is specified, then only the mentioned fields are
summarized; otherwise all results are summarized.
Server side defaults are used for each option (except `fields`) if not specified
- **fields** List of fields to summarize. All fields are summarized if not specified
- **context_len** Amount of context to include with each fragment
- **num_frags** Number of fragments per document
- **sep** Separator string to separate fragments
"""
args = ['SUMMARIZE']
fields = self._mk_field_list(fields)
if fields:
args += ['FIELDS', str(len(fields))] + fields
if context_len is not None:
args += ['LEN', str(context_len)]
if num_frags is not None:
args += ['FRAGS', str(num_frags)]
if sep is not None:
args += ['SEPARATOR', sep]
self._summarize_fields = args
return self
|
def highlight(self, fields=None, tags=None):
"""
Apply specified markup to matched term(s) within the returned field(s)
- **fields** If specified then only those mentioned fields are highlighted, otherwise all fields are highlighted
- **tags** A list of two strings to surround the match.
"""
args = ['HIGHLIGHT']
fields = self._mk_field_list(fields)
if fields:
args += ['FIELDS', str(len(fields))] + fields
if tags:
args += ['TAGS'] + list(tags)
self._highlight_fields = args
return self
|
def get_args(self):
"""
Format the redis arguments for this query and return them
"""
args = [self._query_string]
if self._no_content:
args.append('NOCONTENT')
if self._fields:
args.append('INFIELDS')
args.append(len(self._fields))
args += self._fields
if self._verbatim:
args.append('VERBATIM')
if self._no_stopwords:
args.append('NOSTOPWORDS')
if self._filters:
for flt in self._filters:
assert isinstance(flt, Filter)
args += flt.args
if self._with_payloads:
args.append('WITHPAYLOADS')
if self._ids:
args.append('INKEYS')
args.append(len(self._ids))
args += self._ids
if self._slop >= 0:
args += ['SLOP', self._slop]
if self._in_order:
args.append('INORDER')
if self._return_fields:
args.append('RETURN')
args.append(len(self._return_fields))
args += self._return_fields
if self._sortby:
assert isinstance(self._sortby, SortbyField)
args.append('SORTBY')
args += self._sortby.args
if self._language:
args += ['LANGUAGE', self._language]
args += self._summarize_fields + self._highlight_fields
args += ["LIMIT", self._offset, self._num]
return args
|
def paging(self, offset, num):
"""
Set the paging for the query (defaults to 0..10).
- **offset**: Paging offset for the results. Defaults to 0
- **num**: How many results do we want
"""
self._offset = offset
self._num = num
return self
|
def sort_by(self, field, asc=True):
"""
Add a sortby field to the query
- **field** - the name of the field to sort by
- **asc** - when `True`, sorting will be done in asceding order
"""
self._sortby = SortbyField(field, asc)
return self
|
def between(a, b, inclusive_min=True, inclusive_max=True):
"""
Indicate that value is a numeric range
"""
return RangeValue(a, b,
inclusive_min=inclusive_min, inclusive_max=inclusive_max)
|
def geo(lat, lon, radius, unit='km'):
"""
Indicate that value is a geo region
"""
return GeoValue(lat, lon, radius, unit)
|
def transform(self, jam):
'''Bypass transformations.
Parameters
----------
jam : pyjams.JAMS
A muda-enabled JAMS object
Yields
------
jam_out : pyjams.JAMS iterator
The first result is `jam` (unmodified), by reference
All subsequent results are generated by `transformer`
'''
# Step 1: yield the unmodified jam
yield jam
# Step 2: yield from the transformer
for jam_out in self.transformer.transform(jam):
yield jam_out
|
def __sox(y, sr, *args):
'''Execute sox
Parameters
----------
y : np.ndarray
Audio time series
sr : int > 0
Sampling rate of `y`
*args
Additional arguments to sox
Returns
-------
y_out : np.ndarray
`y` after sox transformation
'''
assert sr > 0
fdesc, infile = tempfile.mkstemp(suffix='.wav')
os.close(fdesc)
fdesc, outfile = tempfile.mkstemp(suffix='.wav')
os.close(fdesc)
# Dump the audio
librosa.output.write_wav(infile, y, sr)
try:
arguments = ['sox', infile, outfile, '-q']
arguments.extend(args)
subprocess.check_call(arguments)
y_out, sr = psf.read(outfile)
y_out = y_out.T
if y.ndim == 1:
y_out = librosa.to_mono(y_out)
finally:
os.unlink(infile)
os.unlink(outfile)
return y_out
|
def transpose(label, n_semitones):
'''Transpose a chord label by some number of semitones
Parameters
----------
label : str
A chord string
n_semitones : float
The number of semitones to move `label`
Returns
-------
label_transpose : str
The transposed chord label
'''
# Otherwise, split off the note from the modifier
match = re.match(six.text_type('(?P<note>[A-G][b#]*)(?P<mod>.*)'),
six.text_type(label))
if not match:
return label
note = match.group('note')
new_note = librosa.midi_to_note(librosa.note_to_midi(note) + n_semitones,
octave=False)
return new_note + match.group('mod')
|
def jam_pack(jam, **kwargs):
'''Pack data into a jams sandbox.
If not already present, this creates a `muda` field within `jam.sandbox`,
along with `history`, `state`, and version arrays which are populated by
deformation objects.
Any additional fields can be added to the `muda` sandbox by supplying
keyword arguments.
Parameters
----------
jam : jams.JAMS
A JAMS object
Returns
-------
jam : jams.JAMS
The updated JAMS object
Examples
--------
>>> jam = jams.JAMS()
>>> muda.jam_pack(jam, my_data=dict(foo=5, bar=None))
>>> jam.sandbox
<Sandbox: muda>
>>> jam.sandbox.muda
<Sandbox: state, version, my_data, history>
>>> jam.sandbox.muda.my_data
{'foo': 5, 'bar': None}
'''
if not hasattr(jam.sandbox, 'muda'):
# If there's no mudabox, create one
jam.sandbox.muda = jams.Sandbox(history=[],
state=[],
version=dict(muda=version,
librosa=librosa.__version__,
jams=jams.__version__,
pysoundfile=psf.__version__))
elif not isinstance(jam.sandbox.muda, jams.Sandbox):
# If there is a muda entry, but it's not a sandbox, coerce it
jam.sandbox.muda = jams.Sandbox(**jam.sandbox.muda)
jam.sandbox.muda.update(**kwargs)
return jam
|
def load_jam_audio(jam_in, audio_file,
validate=True,
strict=True,
fmt='auto',
**kwargs):
'''Load a jam and pack it with audio.
Parameters
----------
jam_in : str, file descriptor, or jams.JAMS
JAMS filename, open file-descriptor, or object to load.
See ``jams.load`` for acceptable formats.
audio_file : str
Audio filename to load
validate : bool
strict : bool
fmt : str
Parameters to `jams.load`
kwargs : additional keyword arguments
See `librosa.load`
Returns
-------
jam : jams.JAMS
A jams object with audio data in the top-level sandbox
Notes
-----
This operation can modify the `file_metadata.duration` field of `jam_in`:
If it is not currently set, it will be populated with the duration of the
audio file.
See Also
--------
jams.load
librosa.core.load
'''
if isinstance(jam_in, jams.JAMS):
jam = jam_in
else:
jam = jams.load(jam_in, validate=validate, strict=strict, fmt=fmt)
y, sr = librosa.load(audio_file, **kwargs)
if jam.file_metadata.duration is None:
jam.file_metadata.duration = librosa.get_duration(y=y, sr=sr)
return jam_pack(jam, _audio=dict(y=y, sr=sr))
|
def save(filename_audio, filename_jam, jam, strict=True, fmt='auto', **kwargs):
'''Save a muda jam to disk
Parameters
----------
filename_audio: str
The path to store the audio file
filename_jam: str
The path to store the jams object
strict: bool
Strict safety checking for jams output
fmt : str
Output format parameter for `jams.JAMS.save`
kwargs
Additional parameters to `soundfile.write`
'''
y = jam.sandbox.muda._audio['y']
sr = jam.sandbox.muda._audio['sr']
# First, dump the audio file
psf.write(filename_audio, y, sr, **kwargs)
# Then dump the jam
jam.save(filename_jam, strict=strict, fmt=fmt)
|
def __reconstruct(params):
'''Reconstruct a transformation or pipeline given a parameter dump.'''
if isinstance(params, dict):
if '__class__' in params:
cls = params['__class__']
data = __reconstruct(params['params'])
return cls(**data)
else:
data = dict()
for key, value in six.iteritems(params):
data[key] = __reconstruct(value)
return data
elif isinstance(params, (list, tuple)):
return [__reconstruct(v) for v in params]
else:
return params
|
def serialize(transform, **kwargs):
'''Serialize a transformation object or pipeline.
Parameters
----------
transform : BaseTransform or Pipeline
The transformation object to be serialized
kwargs
Additional keyword arguments to `jsonpickle.encode()`
Returns
-------
json_str : str
A JSON encoding of the transformation
See Also
--------
deserialize
Examples
--------
>>> D = muda.deformers.TimeStretch(rate=1.5)
>>> muda.serialize(D)
'{"params": {"rate": 1.5},
"__class__": {"py/type": "muda.deformers.time.TimeStretch"}}'
'''
params = transform.get_params()
return jsonpickle.encode(params, **kwargs)
|
def deserialize(encoded, **kwargs):
'''Construct a muda transformation from a JSON encoded string.
Parameters
----------
encoded : str
JSON encoding of the transformation or pipeline
kwargs
Additional keyword arguments to `jsonpickle.decode()`
Returns
-------
obj
The transformation
See Also
--------
serialize
Examples
--------
>>> D = muda.deformers.TimeStretch(rate=1.5)
>>> D_serial = muda.serialize(D)
>>> D2 = muda.deserialize(D_serial)
>>> D2
TimeStretch(rate=1.5)
'''
params = jsonpickle.decode(encoded, **kwargs)
return __reconstruct(params)
|
def _pprint(params, offset=0, printer=repr):
"""Pretty print the dictionary 'params'
Parameters
----------
params: dict
The dictionary to pretty print
offset: int
The offset in characters to add at the begin of each line.
printer:
The function to convert entries to strings, typically
the builtin str or repr
"""
# Do a multi-line justified repr:
options = np.get_printoptions()
np.set_printoptions(precision=5, threshold=64, edgeitems=2)
params_list = list()
this_line_length = offset
line_sep = ',\n' + (1 + offset // 2) * ' '
for i, (k, v) in enumerate(sorted(six.iteritems(params))):
if type(v) is float:
# use str for representing floating point numbers
# this way we get consistent representation across
# architectures and versions.
this_repr = '%s=%s' % (k, str(v))
else:
# use repr of the rest
this_repr = '%s=%s' % (k, printer(v))
if len(this_repr) > 500:
this_repr = this_repr[:300] + '...' + this_repr[-100:]
if i > 0:
if (this_line_length + len(this_repr) >= 75 or '\n' in this_repr):
params_list.append(line_sep)
this_line_length = len(line_sep)
else:
params_list.append(', ')
this_line_length += 2
params_list.append(this_repr)
this_line_length += len(this_repr)
np.set_printoptions(**options)
lines = ''.join(params_list)
# Strip trailing space to avoid nightmare in doctests
lines = '\n'.join(l.rstrip(' ') for l in lines.split('\n'))
return lines
|
def _get_param_names(cls):
'''Get the list of parameter names for the object'''
init = cls.__init__
args, varargs = inspect.getargspec(init)[:2]
if varargs is not None:
raise RuntimeError('BaseTransformer objects cannot have varargs')
args.pop(0)
args.sort()
return args
|
def get_params(self, deep=True):
'''Get the parameters for this object. Returns as a dict.
Parameters
----------
deep : bool
Recurse on nested objects
Returns
-------
params : dict
A dictionary containing all parameters for this object
'''
out = dict(__class__=self.__class__,
params=dict())
for key in self._get_param_names():
value = getattr(self, key, None)
if deep and hasattr(value, 'get_params'):
deep_items = value.get_params().items()
out['params'][key] = dict(__class__=value.__class__)
out['params'][key].update((k, val) for k, val in deep_items)
else:
out['params'][key] = value
return out
|
def _transform(self, jam, state):
'''Apply the transformation to audio and annotations.
The input jam is copied and modified, and returned
contained in a list.
Parameters
----------
jam : jams.JAMS
A single jam object to modify
Returns
-------
jam_list : list
A length-1 list containing `jam` after transformation
See also
--------
core.load_jam_audio
'''
if not hasattr(jam.sandbox, 'muda'):
raise RuntimeError('No muda state found in jams sandbox.')
# We'll need a working copy of this object for modification purposes
jam_w = copy.deepcopy(jam)
# Push our reconstructor onto the history stack
jam_w.sandbox.muda['history'].append({'transformer': self.__serialize__,
'state': state})
if hasattr(self, 'audio'):
self.audio(jam_w.sandbox.muda, state)
if hasattr(self, 'metadata'):
self.metadata(jam_w.file_metadata, state)
# Walk over the list of deformers
for query, function_name in six.iteritems(self.dispatch):
function = getattr(self, function_name)
for matched_annotation in jam_w.search(namespace=query):
function(matched_annotation, state)
return jam_w
|
def transform(self, jam):
'''Iterative transformation generator
Applies the deformation to an input jams object.
This generates a sequence of deformed output JAMS.
Parameters
----------
jam : jams.JAMS
The jam to transform
Examples
--------
>>> for jam_out in deformer.transform(jam_in):
... process(jam_out)
'''
for state in self.states(jam):
yield self._transform(jam, state)
|
def get_params(self):
'''Get the parameters for this object. Returns as a dict.'''
out = {}
out['__class__'] = self.__class__
out['params'] = dict(steps=[])
for name, step in self.steps:
out['params']['steps'].append([name, step.get_params(deep=True)])
return out
|
def __recursive_transform(self, jam, steps):
'''A recursive transformation pipeline'''
if len(steps) > 0:
head_transformer = steps[0][1]
for t_jam in head_transformer.transform(jam):
for q in self.__recursive_transform(t_jam, steps[1:]):
yield q
else:
yield jam
|
def transform(self, jam):
'''Apply the sequence of transformations to a single jam object.
Parameters
----------
jam : jams.JAMS
The jam object to transform
Yields
------
jam_out : jams.JAMS
The jam objects produced by the transformation sequence
'''
for output in self.__recursive_transform(jam, self.steps):
yield output
|
def __serial_transform(self, jam, steps):
'''A serial transformation union'''
# This uses the round-robin itertools recipe
if six.PY2:
attr = 'next'
else:
attr = '__next__'
pending = len(steps)
nexts = itertools.cycle(getattr(iter(D.transform(jam)), attr)
for (name, D) in steps)
while pending:
try:
for next_jam in nexts:
yield next_jam()
except StopIteration:
pending -= 1
nexts = itertools.cycle(itertools.islice(nexts, pending))
|
def transform(self, jam):
'''Apply the sequence of transformations to a single jam object.
Parameters
----------
jam : jams.JAMS
The jam object to transform
Yields
------
jam_out : jams.JAMS
The jam objects produced by each member of the union
'''
for output in self.__serial_transform(jam, self.steps):
yield output
|
def sample_clip_indices(filename, n_samples, sr):
'''Calculate the indices at which to sample a fragment of audio from a file.
Parameters
----------
filename : str
Path to the input file
n_samples : int > 0
The number of samples to load
sr : int > 0
The target sampling rate
Returns
-------
start : int
The sample index from `filename` at which the audio fragment starts
stop : int
The sample index from `filename` at which the audio fragment stops (e.g. y = audio[start:stop])
'''
with psf.SoundFile(str(filename), mode='r') as soundf:
# Measure required length of fragment
n_target = int(np.ceil(n_samples * soundf.samplerate / float(sr)))
# Raise exception if source is too short
if len(soundf) < n_target:
raise RuntimeError('Source {} (length={})'.format(filename, len(soundf)) +
' must be at least the length of the input ({})'.format(n_target))
# Draw a starting point at random in the background waveform
start = np.random.randint(0, 1 + len(soundf) - n_target)
stop = start + n_target
return start, stop
|
def slice_clip(filename, start, stop, n_samples, sr, mono=True):
'''Slice a fragment of audio from a file.
This uses pysoundfile to efficiently seek without
loading the entire stream.
Parameters
----------
filename : str
Path to the input file
start : int
The sample index of `filename` at which the audio fragment should start
stop : int
The sample index of `filename` at which the audio fragment should stop (e.g. y = audio[start:stop])
n_samples : int > 0
The number of samples to load
sr : int > 0
The target sampling rate
mono : bool
Ensure monophonic audio
Returns
-------
y : np.ndarray [shape=(n_samples,)]
A fragment of audio sampled from `filename`
Raises
------
ValueError
If the source file is shorter than the requested length
'''
with psf.SoundFile(str(filename), mode='r') as soundf:
n_target = stop - start
soundf.seek(start)
y = soundf.read(n_target).T
if mono:
y = librosa.to_mono(y)
# Resample to initial sr
y = librosa.resample(y, soundf.samplerate, sr)
# Clip to the target length exactly
y = librosa.util.fix_length(y, n_samples)
return y
|
def norm_remote_path(path):
"""Normalize `path`.
All remote paths are absolute.
"""
path = os.path.normpath(path)
if path.startswith(os.path.sep):
return path[1:]
else:
return path
|
def split_storage(path, default='osfstorage'):
"""Extract storage name from file path.
If a path begins with a known storage provider the name is removed
from the path. Otherwise the `default` storage provider is returned
and the path is not modified.
"""
path = norm_remote_path(path)
for provider in KNOWN_PROVIDERS:
if path.startswith(provider + '/'):
if six.PY3:
return path.split('/', maxsplit=1)
else:
return path.split('/', 1)
return (default, path)
|
def file_empty(fp):
"""Determine if a file is empty or not."""
# for python 2 we need to use a homemade peek()
if six.PY2:
contents = fp.read()
fp.seek(0)
return not bool(contents)
else:
return not fp.peek()
|
def checksum(file_path, hash_type='md5', block_size=65536):
"""Returns either the md5 or sha256 hash of a file at `file_path`.
md5 is the default hash_type as it is faster than sha256
The default block size is 64 kb, which appears to be one of a few command
choices according to https://stackoverflow.com/a/44873382/2680. The code
below is an extension of the example presented in that post.
"""
if hash_type == 'md5':
hash_ = hashlib.md5()
elif hash_type == 'sha256':
hash_ = hashlib.sha256()
else:
raise ValueError(
"{} is an invalid hash_type. Expected 'md5' or 'sha256'."
.format(hash_type)
)
with open(file_path, 'rb') as f:
for block in iter(lambda: f.read(block_size), b''):
hash_.update(block)
return hash_.hexdigest()
|
def storage(self, provider='osfstorage'):
"""Return storage `provider`."""
stores = self._json(self._get(self._storages_url), 200)
stores = stores['data']
for store in stores:
provides = self._get_attribute(store, 'attributes', 'provider')
if provides == provider:
return Storage(store, self.session)
raise RuntimeError("Project has no storage "
"provider '{}'".format(provider))
|
def storages(self):
"""Iterate over all storages for this projects."""
stores = self._json(self._get(self._storages_url), 200)
stores = stores['data']
for store in stores:
yield Storage(store, self.session)
|
def create_file(self, path, fp, force=False, update=False):
"""Store a new file at `path` in this storage.
The contents of the file descriptor `fp` (opened in 'rb' mode)
will be uploaded to `path` which is the full path at
which to store the file.
To force overwrite of an existing file, set `force=True`.
To overwrite an existing file only if the files differ, set `update=True`
"""
if 'b' not in fp.mode:
raise ValueError("File has to be opened in binary mode.")
# all paths are assumed to be absolute
path = norm_remote_path(path)
directory, fname = os.path.split(path)
directories = directory.split(os.path.sep)
# navigate to the right parent object for our file
parent = self
for directory in directories:
# skip empty directory names
if directory:
parent = parent.create_folder(directory, exist_ok=True)
url = parent._new_file_url
# When uploading a large file (>a few MB) that already exists
# we sometimes get a ConnectionError instead of a status == 409.
connection_error = False
# peek at the file to check if it is an empty file which needs special
# handling in requests. If we pass a file like object to data that
# turns out to be of length zero then no file is created on the OSF.
# See: https://github.com/osfclient/osfclient/pull/135
if file_empty(fp):
response = self._put(url, params={'name': fname}, data=b'')
else:
try:
response = self._put(url, params={'name': fname}, data=fp)
except ConnectionError:
connection_error = True
if connection_error or response.status_code == 409:
if not force and not update:
# one-liner to get file size from file pointer from
# https://stackoverflow.com/a/283719/2680824
file_size_bytes = get_local_file_size(fp)
large_file_cutoff = 2**20 # 1 MB in bytes
if connection_error and file_size_bytes < large_file_cutoff:
msg = (
"There was a connection error which might mean {} " +
"already exists. Try again with the `--force` flag " +
"specified."
).format(path)
raise RuntimeError(msg)
else:
# note in case of connection error, we are making an inference here
raise FileExistsError(path)
else:
# find the upload URL for the file we are trying to update
for file_ in self.files:
if norm_remote_path(file_.path) == path:
if not force:
if checksum(path) == file_.hashes.get('md5'):
# If the hashes are equal and force is False,
# we're done here
break
# in the process of attempting to upload the file we
# moved through it -> reset read position to beginning
# of the file
fp.seek(0)
file_.update(fp)
break
else:
raise RuntimeError("Could not create a new file at "
"({}) nor update it.".format(path))
|
def copyfileobj(fsrc, fdst, total, length=16*1024):
"""Copy data from file-like object fsrc to file-like object fdst
This is like shutil.copyfileobj but with a progressbar.
"""
with tqdm(unit='bytes', total=total, unit_scale=True) as pbar:
while 1:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf)
pbar.update(len(buf))
|
def write_to(self, fp):
"""Write contents of this file to a local file.
Pass in a filepointer `fp` that has been opened for writing in
binary mode.
"""
if 'b' not in fp.mode:
raise ValueError("File has to be opened in binary mode.")
response = self._get(self._download_url, stream=True)
if response.status_code == 200:
response.raw.decode_content = True
copyfileobj(response.raw, fp,
int(response.headers['Content-Length']))
else:
raise RuntimeError("Response has status "
"code {}.".format(response.status_code))
|
def remove(self):
"""Remove this file from the remote storage."""
response = self._delete(self._delete_url)
if response.status_code != 204:
raise RuntimeError('Could not delete {}.'.format(self.path))
|
def update(self, fp):
"""Update the remote file from a local file.
Pass in a filepointer `fp` that has been opened for writing in
binary mode.
"""
if 'b' not in fp.mode:
raise ValueError("File has to be opened in binary mode.")
url = self._upload_url
# peek at the file to check if it is an ampty file which needs special
# handling in requests. If we pass a file like object to data that
# turns out to be of length zero then no file is created on the OSF
if fp.peek(1):
response = self._put(url, data=fp)
else:
response = self._put(url, data=b'')
if response.status_code != 200:
msg = ('Could not update {} (status '
'code: {}).'.format(self.path, response.status_code))
raise RuntimeError(msg)
|
def _iter_children(self, url, kind, klass, recurse=None):
"""Iterate over all children of `kind`
Yield an instance of `klass` when a child is of type `kind`. Uses
`recurse` as the path of attributes in the JSON returned from `url`
to find more children.
"""
children = self._follow_next(url)
while children:
child = children.pop()
kind_ = child['attributes']['kind']
if kind_ == kind:
yield klass(child, self.session)
elif recurse is not None:
# recurse into a child and add entries to `children`
url = self._get_attribute(child, *recurse)
children.extend(self._follow_next(url))
|
def might_need_auth(f):
"""Decorate a CLI function that might require authentication.
Catches any UnauthorizedException raised, prints a helpful message and
then exits.
"""
@wraps(f)
def wrapper(cli_args):
try:
return_value = f(cli_args)
except UnauthorizedException as e:
config = config_from_env(config_from_file())
username = _get_username(cli_args, config)
if username is None:
sys.exit("Please set a username (run `osf -h` for details).")
else:
sys.exit("You are not authorized to access this project.")
return return_value
return wrapper
|
def init(args):
"""Initialize or edit an existing .osfcli.config file."""
# reading existing config file, convert to configparser object
config = config_from_file()
config_ = configparser.ConfigParser()
config_.add_section('osf')
if 'username' not in config.keys():
config_.set('osf', 'username', '')
else:
config_.set('osf', 'username', config['username'])
if 'project' not in config.keys():
config_.set('osf', 'project', '')
else:
config_.set('osf', 'project', config['project'])
# now we can start asking for new values
print('Provide a username for the config file [current username: {}]:'.format(
config_.get('osf', 'username')))
username = input()
if username:
config_.set('osf', 'username', username)
print('Provide a project for the config file [current project: {}]:'.format(
config_.get('osf', 'project')))
project = input()
if project:
config_.set('osf', 'project', project)
cfgfile = open(".osfcli.config", "w")
config_.write(cfgfile)
cfgfile.close()
|
def clone(args):
"""Copy all files from all storages of a project.
The output directory defaults to the current directory.
If the project is private you need to specify a username.
If args.update is True, overwrite any existing local files only if local and
remote files differ.
"""
osf = _setup_osf(args)
project = osf.project(args.project)
output_dir = args.project
if args.output is not None:
output_dir = args.output
with tqdm(unit='files') as pbar:
for store in project.storages:
prefix = os.path.join(output_dir, store.name)
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
path = os.path.join(prefix, path)
if os.path.exists(path) and args.update:
if checksum(path) == file_.hashes.get('md5'):
continue
directory, _ = os.path.split(path)
makedirs(directory, exist_ok=True)
with open(path, "wb") as f:
file_.write_to(f)
pbar.update()
|
def fetch(args):
"""Fetch an individual file from a project.
The first part of the remote path is interpreted as the name of the
storage provider. If there is no match the default (osfstorage) is
used.
The local path defaults to the name of the remote file.
If the project is private you need to specify a username.
If args.force is True, write local file even if that file already exists.
If args.force is False but args.update is True, overwrite an existing local
file only if local and remote files differ.
"""
storage, remote_path = split_storage(args.remote)
local_path = args.local
if local_path is None:
_, local_path = os.path.split(remote_path)
local_path_exists = os.path.exists(local_path)
if local_path_exists and not args.force and not args.update:
sys.exit("Local file %s already exists, not overwriting." % local_path)
directory, _ = os.path.split(local_path)
if directory:
makedirs(directory, exist_ok=True)
osf = _setup_osf(args)
project = osf.project(args.project)
store = project.storage(storage)
for file_ in store.files:
if norm_remote_path(file_.path) == remote_path:
if local_path_exists and not args.force and args.update:
if file_.hashes.get('md5') == checksum(local_path):
print("Local file %s already matches remote." % local_path)
break
with open(local_path, 'wb') as fp:
file_.write_to(fp)
# only fetching one file so we are done
break
|
def list_(args):
"""List all files from all storages for project.
If the project is private you need to specify a username.
"""
osf = _setup_osf(args)
project = osf.project(args.project)
for store in project.storages:
prefix = store.name
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
print(os.path.join(prefix, path))
|
def upload(args):
"""Upload a new file to an existing project.
The first part of the remote path is interpreted as the name of the
storage provider. If there is no match the default (osfstorage) is
used.
If the project is private you need to specify a username.
To upload a whole directory (and all its sub-directories) use the `-r`
command-line option. If your source directory name ends in a / then
files will be created directly in the remote directory. If it does not
end in a slash an extra sub-directory with the name of the local directory
will be created.
To place contents of local directory `foo` in remote directory `bar/foo`:
$ osf upload -r foo bar
To place contents of local directory `foo` in remote directory `bar`:
$ osf upload -r foo/ bar
"""
osf = _setup_osf(args)
if osf.username is None or osf.password is None:
sys.exit('To upload a file you need to provide a username and'
' password.')
project = osf.project(args.project)
storage, remote_path = split_storage(args.destination)
store = project.storage(storage)
if args.recursive:
if not os.path.isdir(args.source):
raise RuntimeError("Expected source ({}) to be a directory when "
"using recursive mode.".format(args.source))
# local name of the directory that is being uploaded
_, dir_name = os.path.split(args.source)
for root, _, files in os.walk(args.source):
subdir_path = os.path.relpath(root, args.source)
for fname in files:
local_path = os.path.join(root, fname)
with open(local_path, 'rb') as fp:
# build the remote path + fname
name = os.path.join(remote_path, dir_name, subdir_path,
fname)
store.create_file(name, fp, force=args.force,
update=args.update)
else:
with open(args.source, 'rb') as fp:
store.create_file(remote_path, fp, force=args.force,
update=args.update)
|
def remove(args):
"""Remove a file from the project's storage.
The first part of the remote path is interpreted as the name of the
storage provider. If there is no match the default (osfstorage) is
used.
"""
osf = _setup_osf(args)
if osf.username is None or osf.password is None:
sys.exit('To remove a file you need to provide a username and'
' password.')
project = osf.project(args.project)
storage, remote_path = split_storage(args.target)
store = project.storage(storage)
for f in store.files:
if norm_remote_path(f.path) == remote_path:
f.remove()
|
def login(self, username, password=None, token=None):
"""Login user for protected API calls."""
self.session.basic_auth(username, password)
|
def project(self, project_id):
"""Fetch project `project_id`."""
type_ = self.guid(project_id)
url = self._build_url(type_, project_id)
if type_ in Project._types:
return Project(self._json(self._get(url), 200), self.session)
raise OSFException('{} is unrecognized type {}. Clone supports projects and registrations'.format(project_id, type_))
|
def guid(self, guid):
"""Determines JSONAPI type for provided GUID"""
return self._json(self._get(self._build_url('guids', guid)), 200)['data']['type']
|
def _json(self, response, status_code):
"""Extract JSON from response if `status_code` matches."""
if isinstance(status_code, numbers.Integral):
status_code = (status_code,)
if response.status_code in status_code:
return response.json()
else:
raise RuntimeError("Response has status "
"code {} not {}".format(response.status_code,
status_code))
|
def _follow_next(self, url):
"""Follow the 'next' link on paginated results."""
response = self._json(self._get(url), 200)
data = response['data']
next_url = self._get_attribute(response, 'links', 'next')
while next_url is not None:
response = self._json(self._get(next_url), 200)
data.extend(response['data'])
next_url = self._get_attribute(response, 'links', 'next')
return data
|
def project(*descs, root_file=None):
"""
Make a new project, using recursion and alias resolution.
Use this function in preference to calling Project() directly.
"""
load.ROOT_FILE = root_file
desc = merge.merge(merge.DEFAULT_PROJECT, *descs)
path = desc.get('path', '')
if root_file:
project_path = os.path.dirname(root_file)
if path:
path += ':' + project_path
else:
path = project_path
with load.extender(path):
desc = recurse.recurse(desc)
project = construct.construct(**desc)
project.desc = desc
return project
|
def clear(self):
"""Clear description to default values"""
self._desc = {}
for key, value in merge.DEFAULT_PROJECT.items():
if key not in self._HIDDEN:
self._desc[key] = type(value)()
|
def update(self, desc=None, **kwds):
"""This method updates the description much like dict.update(), *except*:
1. for description which have dictionary values, it uses update
to alter the existing value and does not replace them.
2. `None` is a special value that means "clear section to default" or
"delete field".
"""
sections.update(self._desc, desc, **kwds)
|
def SPI(ledtype=None, num=0, **kwargs):
"""Wrapper function for using SPI device drivers on systems like the
Raspberry Pi and BeagleBone. This allows using any of the SPI drivers
from a single entry point instead importing the driver for a specific
LED type.
Provides the same parameters of
:py:class:`bibliopixel.drivers.SPI.SPIBase` as
well as those below:
:param ledtype: One of: LPD8806, WS2801, WS281X, or APA102
"""
from ...project.types.ledtype import make
if ledtype is None:
raise ValueError('Must provide ledtype value!')
ledtype = make(ledtype)
if num == 0:
raise ValueError('Must provide num value >0!')
if ledtype not in SPI_DRIVERS.keys():
raise ValueError('{} is not a valid LED type.'.format(ledtype))
return SPI_DRIVERS[ledtype](num, **kwargs)
|
def put_edit(self, f, *args, **kwds):
"""
Defer an edit to run on the EditQueue.
:param callable f: The function to be called
:param tuple args: Positional arguments to the function
:param tuple kwds: Keyword arguments to the function
:throws queue.Full: if the queue is full
"""
self.put_nowait(functools.partial(f, *args, **kwds))
|
def get_and_run_edits(self):
"""
Get all the edits in the queue, then execute them.
The algorithm gets all edits, and then executes all of them. It does
*not* pull off one edit, execute, repeat until the queue is empty, and
that means that the queue might not be empty at the end of
``run_edits``, because new edits might have entered the queue
while the previous edits are being executed.
This has the advantage that if edits enter the queue faster than they
can be processed, ``get_and_run_edits`` won't go into an infinite loop,
but rather the queue will grow unboundedly, which that can be
detected, and mitigated and reported on - or if Queue.maxsize is
set, ``bp`` will report a fairly clear error and just dump the edits
on the ground.
"""
if self.empty():
return
edits = []
while True:
try:
edits.append(self.get_nowait())
except queue.Empty:
break
for e in edits:
try:
e()
except:
log.error('Error on edit %s', e)
traceback.print_exc()
|
def error(self, text):
"""SHOULD BE PRIVATE"""
msg = 'Error with dev: {}, spi_speed: {} - {}'.format(
self._dev, self._spi_speed, text)
log.error(msg)
raise IOError(msg)
|
def send_packet(self, data):
"""SHOULD BE PRIVATE"""
package_size = 4032 # bit smaller than 4096 because of headers
for i in range(int(math.ceil(len(data) / package_size))):
start = i * package_size
end = (i + 1) * package_size
self._spi.write(data[start:end])
self._spi.flush()
|
def find_serial_devices(self):
"""Scan and report all compatible serial devices on system.
:returns: List of discovered devices
"""
if self.devices is not None:
return self.devices
self.devices = {}
hardware_id = "(?i)" + self.hardware_id # forces case insensitive
for ports in serial.tools.list_ports.grep(hardware_id):
port = ports[0]
try:
id = self.get_device_id(port)
ver = self._get_device_version(port)
except:
log.debug('Error getting device_id for %s, %s',
port, self.baudrate)
if True:
raise
continue
if getattr(ports, '__len__', lambda: 0)():
log.debug('Multi-port device %s:%s:%s with %s ports found',
self.hardware_id, id, ver, len(ports))
if id < 0:
log.debug('Serial device %s:%s:%s with id %s < 0',
self.hardware_id, id, ver)
else:
self.devices[id] = port, ver
return self.devices
|
def get_device(self, id=None):
"""Returns details of either the first or specified device
:param int id: Identifier of desired device. If not given, first device
found will be returned
:returns tuple: Device ID, Device Address, Firmware Version
"""
if id is None:
if not self.devices:
raise ValueError('No default device for %s' % self.hardware_id)
id, (device, version) = sorted(self.devices.items())[0]
elif id in self.devices:
device, version = self.devices[id]
else:
error = 'Unable to find device with ID %s' % id
log.error(error)
raise ValueError(error)
log.info("Using COM Port: %s, Device ID: %s, Device Ver: %s",
device, id, version)
return id, device, version
|
def error(self, fail=True, action=''):
"""
SHOULD BE PRIVATE METHOD
"""
e = 'There was an unknown error communicating with the device.'
if action:
e = 'While %s: %s' % (action, e)
log.error(e)
if fail:
raise IOError(e)
|
def set_device_id(self, dev, id):
"""Set device ID to new value.
:param str dev: Serial device address/path
:param id: Device ID to set
"""
if id < 0 or id > 255:
raise ValueError("ID must be an unsigned byte!")
com, code, ok = io.send_packet(
CMDTYPE.SETID, 1, dev, self.baudrate, 5, id)
if not ok:
raise_error(code)
|
def get_device_id(self, dev):
"""Get device ID at given address/path.
:param str dev: Serial device address/path
:param baudrate: Baudrate to use when connecting (optional)
"""
com, code, ok = io.send_packet(CMDTYPE.GETID, 0, dev, self.baudrate, 5)
if code is None:
self.error(action='get_device_id')
return code
|
def get(name=None):
"""
Return a named Palette, or None if no such name exists.
If ``name`` is omitted, the default value is used.
"""
if name is None or name == 'default':
return _DEFAULT_PALETTE
if isinstance(name, str):
return PROJECT_PALETTES.get(name) or BUILT_IN_PALETTES.get(name)
|
def crop(image, top_offset=0, left_offset=0, bottom_offset=0, right_offset=0):
"""Return an image cropped on top, bottom, left or right."""
if bottom_offset or top_offset or left_offset or right_offset:
width, height = image.size
box = (left_offset, top_offset,
width - right_offset, height - bottom_offset)
image = image.crop(box=box)
return image
|
def resize(image, x, y, stretch=False, top=None, left=None, mode='RGB',
resample=None):
"""Return an image resized."""
if x <= 0:
raise ValueError('x must be greater than zero')
if y <= 0:
raise ValueError('y must be greater than zero')
from PIL import Image
resample = Image.ANTIALIAS if resample is None else resample
if not isinstance(resample, numbers.Number):
try:
resample = getattr(Image, resample.upper())
except:
raise ValueError("(1) Didn't understand resample=%s" % resample)
if not isinstance(resample, numbers.Number):
raise ValueError("(2) Didn't understand resample=%s" % resample)
size = x, y
if stretch:
return image.resize(size, resample=resample)
result = Image.new(mode, size)
ratios = [d1 / d2 for d1, d2 in zip(size, image.size)]
if ratios[0] < ratios[1]:
new_size = (size[0], int(image.size[1] * ratios[0]))
else:
new_size = (int(image.size[0] * ratios[1]), size[1])
image = image.resize(new_size, resample=resample)
if left is None:
box_x = int((x - new_size[0]) / 2)
elif left:
box_x = 0
else:
box_x = x - new_size[0]
if top is None:
box_y = int((y - new_size[1]) / 2)
elif top:
box_y = 0
else:
box_y = y - new_size[1]
result.paste(image, box=(box_x, box_y))
return result
|
def extract(self, msg):
"""Yield an ordered dictionary if msg['type'] is in keys_by_type."""
def normal(key):
v = msg.get(key)
if v is None:
return v
normalizer = self.normalizers.get(key, lambda x: x)
return normalizer(v)
def odict(keys):
return collections.OrderedDict((k, normal(k)) for k in keys)
def match(m):
return (msg.get(k) in v for k, v in m.items()) if m else ()
accept = all(match(self.accept))
reject = any(match(self.reject))
if reject or not accept:
keys = ()
elif self.keys_by_type is None:
keys = [k for k in msg.keys() if k not in self.omit]
else:
keys = self.keys_by_type.get(msg.get('type'))
return odict(keys)
|
def get(self, x, y):
"""
Return the pixel color at position (x, y), or Colors.black if that
position is out-of-bounds.
"""
try:
pixel = self.coord_map[y][x]
return self._get_base(pixel)
except IndexError:
return colors.COLORS.Black
|
def drawCircle(self, x0, y0, r, color=None):
"""
Draw a circle in an RGB color, with center x0, y0 and radius r.
"""
md.draw_circle(self.set, x0, y0, r, color)
|
def fillCircle(self, x0, y0, r, color=None):
"""
Draw a filled circle in an RGB color, with center x0, y0 and radius r.
"""
md.fill_circle(self.set, x0, y0, r, color)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.