code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
part = '/library/sections/%s?%s' % (self.key, urlencode(kwargs))
self._server.query(part, method=self._server._session.put)
# Reload this way since the self.key dont have a full path, but is simply a id.
for s in self._server.library.sections():
if s.key == self.key... | def edit(self, **kwargs) | Edit a library (Note: agent is required). See :class:`~plexapi.library.Library` for example usage.
Parameters:
kwargs (dict): Dict of settings to edit. | 7.876451 | 7.01737 | 1.122422 |
key = '/library/sections/%s/all' % self.key
return self.fetchItem(key, title__iexact=title) | def get(self, title) | Returns the media item with the specified title.
Parameters:
title (str): Title of the item to return. | 14.360346 | 16.215364 | 0.885601 |
sortStr = ''
if sort is not None:
sortStr = '?sort=' + sort
key = '/library/sections/%s/all%s' % (self.key, sortStr)
return self.fetchItems(key, **kwargs) | def all(self, sort=None, **kwargs) | Returns a list of media from this library section.
Parameters:
sort (string): The sort string | 4.798523 | 4.562701 | 1.051685 |
key = '/library/sections/%s/analyze' % self.key
self._server.query(key, method=self._server._session.put) | def analyze(self) | Run an analysis on all of the items in this library section. See
See :func:`~plexapi.base.PlexPartialObject.analyze` for more details. | 15.8709 | 5.925337 | 2.67848 |
key = '/library/sections/%s/emptyTrash' % self.key
self._server.query(key, method=self._server._session.put) | def emptyTrash(self) | If a section has items in the Trash, use this option to empty the Trash. | 12.729152 | 8.318329 | 1.530253 |
key = '/library/sections/%s/refresh' % self.key
self._server.query(key, method=self._server._session.delete) | def cancelUpdate(self) | Cancel update of this Library Section. | 14.284185 | 9.481707 | 1.506499 |
key = '/library/sections/%s/indexes' % self.key
self._server.query(key, method=self._server._session.delete) | def deleteMediaPreviews(self) | Delete the preview thumbnails for items in this library. This cannot
be undone. Recreating media preview files can take hours or even days. | 13.068472 | 11.579129 | 1.128623 |
# TODO: Should this be moved to base?
if category in kwargs:
raise BadRequest('Cannot include kwarg equal to specified category: %s' % category)
args = {}
for subcategory, value in kwargs.items():
args[category] = self._cleanSearchFilter(subcategory, valu... | def listChoices(self, category, libtype=None, **kwargs) | Returns a list of :class:`~plexapi.library.FilterChoice` objects for the
specified category and libtype. kwargs can be any of the same kwargs in
:func:`plexapi.library.LibraySection.search()` to help narrow down the choices
to only those that matter in your current context.
... | 6.255132 | 4.042127 | 1.547485 |
# cleanup the core arguments
args = {}
for category, value in kwargs.items():
args[category] = self._cleanSearchFilter(category, value, libtype)
if title is not None:
args['title'] = title
if sort is not None:
args['sort'] = self._clea... | def search(self, title=None, sort=None, maxresults=999999, libtype=None, **kwargs) | Search the library. If there are many results, they will be fetched from the server
in batches of X_PLEX_CONTAINER_SIZE amounts. If you're only looking for the first <num>
results, it would be wise to set the maxresults option to that amount so this functions
doesn't iterate over all... | 3.141452 | 3.030058 | 1.036763 |
from plexapi.sync import SyncItem
if not self.allowSync:
raise BadRequest('The requested library is not allowed to sync')
args = {}
for category, value in kwargs.items():
args[category] = self._cleanSearchFilter(category, value, libtype)
if sort... | def sync(self, policy, mediaSettings, client=None, clientId=None, title=None, sort=None, libtype=None,
**kwargs) | Add current library section as sync item for specified device.
See description of :func:`~plexapi.library.LibrarySection.search()` for details about filtering / sorting
and :func:`plexapi.myplex.MyPlexAccount.sync()` for possible exceptions.
Parameters:
policy (:clas... | 3.481426 | 3.18014 | 1.09474 |
from plexapi.sync import Policy, MediaSettings
kwargs['mediaSettings'] = MediaSettings.createVideo(videoQuality)
kwargs['policy'] = Policy.create(limit, unwatched)
return super(MovieSection, self).sync(**kwargs) | def sync(self, videoQuality, limit=None, unwatched=False, **kwargs) | Add current Movie library section as sync item for specified device.
See description of :func:`plexapi.library.LibrarySection.search()` for details about filtering / sorting and
:func:`plexapi.library.LibrarySection.sync()` for details on syncing libraries and possible exceptions.
P... | 5.702942 | 5.850381 | 0.974798 |
return self.search(sort='addedAt:desc', libtype=libtype, maxresults=maxresults) | def recentlyAdded(self, libtype='episode', maxresults=50) | Returns a list of recently added episodes from this library section.
Parameters:
maxresults (int): Max number of items to return (default 50). | 5.206177 | 9.913404 | 0.525165 |
from plexapi.sync import Policy, MediaSettings
kwargs['mediaSettings'] = MediaSettings.createMusic(bitrate)
kwargs['policy'] = Policy.create(limit)
return super(MusicSection, self).sync(**kwargs) | def sync(self, bitrate, limit=None, **kwargs) | Add current Music library section as sync item for specified device.
See description of :func:`plexapi.library.LibrarySection.search()` for details about filtering / sorting and
:func:`plexapi.library.LibrarySection.sync()` for details on syncing libraries and possible exceptions.
P... | 6.537036 | 6.9421 | 0.941651 |
return self.search(libtype='photoalbum', title=title, **kwargs) | def searchAlbums(self, title, **kwargs) | Search for an album. See :func:`~plexapi.library.LibrarySection.search()` for usage. | 9.052578 | 6.517747 | 1.388912 |
return self.search(libtype='photo', title=title, **kwargs) | def searchPhotos(self, title, **kwargs) | Search for a photo. See :func:`~plexapi.library.LibrarySection.search()` for usage. | 7.522377 | 4.886683 | 1.539362 |
from plexapi.sync import Policy, MediaSettings
kwargs['mediaSettings'] = MediaSettings.createPhoto(resolution)
kwargs['policy'] = Policy.create(limit)
return super(PhotoSection, self).sync(**kwargs) | def sync(self, resolution, limit=None, **kwargs) | Add current Music library section as sync item for specified device.
See description of :func:`plexapi.library.LibrarySection.search()` for details about filtering / sorting and
:func:`plexapi.library.LibrarySection.sync()` for details on syncing libraries and possible exceptions.
P... | 8.340396 | 7.94963 | 1.049155 |
self._data = data
self.fastKey = data.attrib.get('fastKey')
self.key = data.attrib.get('key')
self.thumb = data.attrib.get('thumb')
self.title = data.attrib.get('title')
self.type = data.attrib.get('type') | def _loadData(self, data) | Load attribute values from Plex XML response. | 2.98471 | 2.285633 | 1.305857 |
starttime = time.time()
try:
device = cls(baseurl=url, token=token, timeout=timeout)
runtime = int(time.time() - starttime)
results[i] = (url, token, device, runtime)
if X_PLEX_ENABLE_FAST_CONNECT and job_is_done_event:
job_is_done_event.set()
except Exceptio... | def _connect(cls, url, token, timeout, results, i, job_is_done_event=None) | Connects to the specified cls with url and token. Stores the connection
information to results[i] in a threadsafe way.
Arguments:
cls: the class which is responsible for establishing connection, basically it's
:class:`~plexapi.client.PlexClient` or :class:`~plexapi.server.P... | 3.042795 | 2.355564 | 1.291748 |
# At this point we have a list of result tuples containing (url, token, PlexServer, runtime)
# or (url, token, None, runtime) in the case a connection could not be established.
for url, token, result, runtime in results:
okerr = 'OK' if result else 'ERR'
log.info('%s connection %s (%ss)... | def _chooseConnection(ctype, name, results) | Chooses the first (best) connection from the given _connect results. | 4.148326 | 4.131224 | 1.00414 |
self._data = data
self._token = logfilter.add_secret(data.attrib.get('authenticationToken'))
self._webhooks = []
self.authenticationToken = self._token
self.certificateVersion = data.attrib.get('certificateVersion')
self.cloudSyncDevice = data.attrib.get('cloudSy... | def _loadData(self, data) | Load attribute values from Plex XML response. | 2.396419 | 2.280022 | 1.051051 |
for device in self.devices():
if device.name.lower() == name.lower():
return device
raise NotFound('Unable to find device %s' % name) | def device(self, name) | Returns the :class:`~plexapi.myplex.MyPlexDevice` that matches the name specified.
Parameters:
name (str): Name to match against. | 3.549256 | 3.943036 | 0.900133 |
data = self.query(MyPlexDevice.key)
return [MyPlexDevice(self, elem) for elem in data] | def devices(self) | Returns a list of all :class:`~plexapi.myplex.MyPlexDevice` objects connected to the server. | 9.195364 | 4.745049 | 1.937886 |
for resource in self.resources():
if resource.name.lower() == name.lower():
return resource
raise NotFound('Unable to find resource %s' % name) | def resource(self, name) | Returns the :class:`~plexapi.myplex.MyPlexResource` that matches the name specified.
Parameters:
name (str): Name to match against. | 3.398226 | 3.968923 | 0.856209 |
data = self.query(MyPlexResource.key)
return [MyPlexResource(self, elem) for elem in data] | def resources(self) | Returns a list of all :class:`~plexapi.myplex.MyPlexResource` objects connected to the server. | 9.776494 | 4.81893 | 2.028769 |
username = user.username if isinstance(user, MyPlexUser) else user
machineId = server.machineIdentifier if isinstance(server, PlexServer) else server
sectionIds = self._getSectionIds(machineId, sections)
params = {
'server_id': machineId,
'shared_server':... | def inviteFriend(self, user, server, sections=None, allowSync=False, allowCameraUpload=False,
allowChannels=False, filterMovies=None, filterTelevision=None, filterMusic=None) | Share library content with the specified user.
Parameters:
user (str): MyPlexUser, username, email of the user to be added.
server (PlexServer): PlexServer object or machineIdentifier containing the library sections to share.
sections ([Section]): Library sec... | 2.69788 | 2.4924 | 1.082442 |
user = self.user(user)
url = self.FRIENDUPDATE if user.friend else self.REMOVEINVITE
url = url.format(userId=user.id)
return self.query(url, self._session.delete) | def removeFriend(self, user) | Remove the specified user from all sharing.
Parameters:
user (str): MyPlexUser, username, email of the user to be added. | 7.379428 | 8.339893 | 0.884835 |
# Update friend servers
response_filters = ''
response_servers = ''
user = user if isinstance(user, MyPlexUser) else self.user(user)
machineId = server.machineIdentifier if isinstance(server, PlexServer) else server
sectionIds = self._getSectionIds(machineId, sec... | def updateFriend(self, user, server, sections=None, removeSections=False, allowSync=None, allowCameraUpload=None,
allowChannels=None, filterMovies=None, filterTelevision=None, filterMusic=None) | Update the specified user's share settings.
Parameters:
user (str): MyPlexUser, username, email of the user to be added.
server (PlexServer): PlexServer object or machineIdentifier containing the library sections to share.
sections: ([Section]): Library secti... | 3.027499 | 2.867797 | 1.055688 |
for user in self.users():
# Home users don't have email, username etc.
if username.lower() == user.title.lower():
return user
elif (user.username and user.email and user.id and username.lower() in
(user.username.lower(), user.email.l... | def user(self, username) | Returns the :class:`~plexapi.myplex.MyPlexUser` that matches the email or username specified.
Parameters:
username (str): Username, email or id of the user to return. | 5.148738 | 4.15355 | 1.2396 |
friends = [MyPlexUser(self, elem) for elem in self.query(MyPlexUser.key)]
requested = [MyPlexUser(self, elem, self.REQUESTED) for elem in self.query(self.REQUESTED)]
return friends + requested | def users(self) | Returns a list of all :class:`~plexapi.myplex.MyPlexUser` objects connected to your account.
This includes both friends and pending invites. You can reference the user.friend to
distinguish between the two. | 7.074222 | 5.343433 | 1.323909 |
if not sections: return []
# Get a list of all section ids for looking up each section.
allSectionIds = {}
machineIdentifier = server.machineIdentifier if isinstance(server, PlexServer) else server
url = self.PLEXSERVERS.replace('{machineId}', machineIdentifier)
... | def _getSectionIds(self, server, sections) | Converts a list of section objects or names to sectionIds needed for library sharing. | 3.512334 | 3.353789 | 1.047273 |
values = []
for key, vals in filterDict.items():
if key not in ('contentRating', 'label'):
raise BadRequest('Unknown filter key: %s', key)
values.append('%s=%s' % (key, '%2C'.join(vals)))
return '|'.join(values) | def _filterDictToStr(self, filterDict) | Converts friend filters to a string representation for transport. | 4.636137 | 4.359494 | 1.063457 |
params = {}
if playback is not None:
params['optOutPlayback'] = int(playback)
if library is not None:
params['optOutLibraryStats'] = int(library)
url = 'https://plex.tv/api/v2/user/privacy'
return self.query(url, method=self._session.put, data=par... | def optOut(self, playback=None, library=None) | Opt in or out of sharing stuff with plex.
See: https://www.plex.tv/about/privacy-legal/ | 3.525741 | 3.087982 | 1.141762 |
if client:
clientId = client.clientIdentifier
elif clientId is None:
clientId = X_PLEX_IDENTIFIER
data = self.query(SyncList.key.format(clientId=clientId))
return SyncList(self, data) | def syncItems(self, client=None, clientId=None) | Returns an instance of :class:`plexapi.sync.SyncList` for specified client.
Parameters:
client (:class:`~plexapi.myplex.MyPlexDevice`): a client to query SyncItems for.
clientId (str): an identifier of a client to query SyncItems for.
If both `client` and `clien... | 8.044926 | 5.617346 | 1.432158 |
if not client and not clientId:
clientId = X_PLEX_IDENTIFIER
if not client:
for device in self.devices():
if device.clientIdentifier == clientId:
client = device
break
if not client:
ra... | def sync(self, sync_item, client=None, clientId=None) | Adds specified sync item for the client. It's always easier to use methods defined directly in the media
objects, e.g. :func:`plexapi.video.Video.sync`, :func:`plexapi.audio.Audio.sync`.
Parameters:
client (:class:`~plexapi.myplex.MyPlexDevice`): a client for which you need to a... | 2.516849 | 2.229516 | 1.128877 |
response = self._session.get('https://plex.tv/api/claim/token.json', headers=self._headers(), timeout=TIMEOUT)
if response.status_code not in (200, 201, 204): # pragma: no cover
codename = codes.get(response.status_code)[0]
errtext = response.text.replace('\n', ' ')
... | def claimToken(self) | Returns a str, a new "claim-token", which you can use to register your new Plex Server instance to your
account.
See: https://hub.docker.com/r/plexinc/pms-docker/, https://www.plex.tv/claim/ | 3.10104 | 2.983124 | 1.039527 |
self._data = data
self.friend = self._initpath == self.key
self.allowCameraUpload = utils.cast(bool, data.attrib.get('allowCameraUpload'))
self.allowChannels = utils.cast(bool, data.attrib.get('allowChannels'))
self.allowSync = utils.cast(bool, data.attrib.get('allowSync... | def _loadData(self, data) | Load attribute values from Plex XML response. | 2.714917 | 2.49869 | 1.086536 |
self._data = data
self.id = utils.cast(int, data.attrib.get('id'))
self.serverId = utils.cast(int, data.attrib.get('serverId'))
self.machineIdentifier = data.attrib.get('machineIdentifier')
self.name = data.attrib.get('name')
self.lastSeenAt = utils.toDatetime(da... | def _loadData(self, data) | Load attribute values from Plex XML response. | 2.329038 | 1.902335 | 1.224305 |
# Sort connections from (https, local) to (http, remote)
# Only check non-local connections unless we own the resource
connections = sorted(self.connections, key=lambda c: c.local, reverse=True)
owned_or_unowned_non_local = lambda x: self.owned or (not self.owned and not x.local... | def connect(self, ssl=None, timeout=None) | Returns a new :class:`~server.PlexServer` or :class:`~client.PlexClient` object.
Often times there is more than one address specified for a server or client.
This function will prioritize local connections before remote and HTTPS before HTTP.
After trying to connect to all available ... | 7.085119 | 6.52917 | 1.085148 |
cls = PlexServer if 'server' in self.provides else PlexClient
listargs = [[cls, url, self.token, timeout] for url in self.connections]
log.info('Testing %s device connections..', len(listargs))
results = utils.threaded(_connect, listargs)
return _chooseConnection('Device... | def connect(self, timeout=None) | Returns a new :class:`~plexapi.client.PlexClient` or :class:`~plexapi.server.PlexServer`
Sometimes there is more than one address specified for a server or client.
After trying to connect to all available addresses for this client and assuming
at least one connection was successful, ... | 13.099417 | 10.157586 | 1.289619 |
key = 'https://plex.tv/devices/%s.xml' % self.id
self._server.query(key, self._server._session.delete) | def delete(self) | Remove this device from your account. | 9.625417 | 7.576221 | 1.270477 |
if 'sync-target' not in self.provides:
raise BadRequest('Requested syncList for device which do not provides sync-target')
return self._server.syncItems(client=self) | def syncItems(self) | Returns an instance of :class:`plexapi.sync.SyncList` for current device.
Raises:
:class:`plexapi.exceptions.BadRequest`: when the device doesn`t provides `sync-target`. | 22.617655 | 10.267769 | 2.202782 |
key = self.firstAttr('thumb', 'parentThumb', 'granparentThumb')
return self._server.url(key, includeToken=True) if key else None | def thumbUrl(self) | Return url to for the thumbnail image. | 18.749662 | 16.620363 | 1.128114 |
args = {}
args['includeChapters'] = includeChapters
args['includeRelated'] = includeRelated
args['repeat'] = repeat
args['shuffle'] = shuffle
if item.type == 'playlist':
args['playlistID'] = item.ratingKey
args['type'] = item.playlistType
... | def create(cls, server, item, shuffle=0, repeat=0, includeChapters=1, includeRelated=1) | Create and returns a new :class:`~plexapi.playqueue.PlayQueue`.
Paramaters:
server (:class:`~plexapi.server.PlexServer`): Server you are connected to.
item (:class:`~plexapi.media.Media` or class:`~plexapi.playlist.Playlist`): A media or Playlist.
shuffle (in... | 4.574521 | 4.238341 | 1.079319 |
deleted = 0
print('%s Cleaning %s to %s episodes.' % (datestr(), show.title, keep))
sort = lambda x:x.originallyAvailableAt or x.addedAt
items = sorted(show.episodes(), key=sort, reverse=True)
for episode in items[keep:]:
delete_episode(episode)
deleted += 1
return deleted | def keep_episodes(show, keep) | Delete all but last count episodes in show. | 4.753673 | 4.369187 | 1.087999 |
deleted = 0
print('%s Cleaning %s to latest season.' % (datestr(), show.title))
for season in show.seasons()[:-1]:
for episode in season.episodes():
delete_episode(episode)
deleted += 1
return deleted | def keep_season(show, keep) | Keep only the latest season. | 5.672973 | 5.146847 | 1.102223 |
try:
os.makedirs(name, mode)
except OSError:
if not os.path.isdir(name) or not exist_ok:
raise | def makedirs(name, mode=0o777, exist_ok=False) | Mimicks os.makedirs() from Python 3. | 2.003907 | 2.108084 | 0.950582 |
if not email_messages:
return
with self._lock:
try:
stream_created = self.open()
for message in email_messages:
self.write_to_stream(message)
self.stream.flush() # flush after each message
... | def echo_to_output_stream(self, email_messages) | Write all messages to the stream in a thread-safe way. | 3.442162 | 3.134326 | 1.098215 |
def set_prop(attachment, prop_name, value):
if SENDGRID_VERSION < '6':
setattr(attachment, prop_name, value)
else:
if prop_name == "filename":
prop_name = "name"
setattr(attachment, 'file_{}'.format(prop_name),... | def _create_sg_attachment(self, django_attch) | Handles the conversion between a django attachment object and a sendgrid attachment object.
Due to differences between sendgrid's API versions, use this method when constructing attachments to ensure
that attachments get properly instantiated. | 2.617781 | 2.493454 | 1.049861 |
result = []
#for elem in path[:-1]:
cur = obj
for elem in path[:-1]:
if ((issubclass(cur.__class__, MutableMapping) and elem in cur)):
result.append([elem, cur[elem].__class__])
cur = cur[elem]
elif (issubclass(cur.__class__, MutableSequence) and int(elem) < ... | def path_types(obj, path) | Given a list of path name elements, return anew list of [name, type] path components, given the reference object. | 2.213232 | 2.095089 | 1.056391 |
validated = []
for elem in path:
key = elem[0]
strkey = str(key)
if (regex and (not regex.findall(strkey))):
raise dpath.exceptions.InvalidKeyName("{} at {} does not match the expression {}"
"".format(strkey,
... | def validate(path, regex=None) | Validate that all the keys in the given list of path components are valid, given that they do not contain the separator, and match any optional regex given. | 6.29466 | 5.741589 | 1.096327 |
if isinstance(obj, MutableMapping):
# Python 3 support
if PY3:
iteritems = obj.items()
string_class = str
else: # Default to PY2
iteritems = obj.iteritems()
string_class = basestring
for (k, v) in iteritems:
if issubcl... | def paths(obj, dirs=True, leaves=True, path=[], skip=False) | Yield all paths of the object.
Arguments:
obj -- An object to get paths from.
Keyword Arguments:
dirs -- Yield intermediate paths.
leaves -- Yield the paths with leaf objects.
path -- A list of keys representing the path.
skip -- Skip special keys beginning with '+'. | 3.148318 | 3.154193 | 0.998137 |
path_len = len(path)
glob_len = len(glob)
ss = -1
ss_glob = glob
if '**' in glob:
ss = glob.index('**')
if '**' in glob[ss + 1:]:
raise dpath.exceptions.InvalidGlob("Invalid glob. Only one '**' is permitted per glob.")
if path_len >= glob_len:
#... | def match(path, glob) | Match the path with the glob.
Arguments:
path -- A list of keys representing the path.
glob -- A list of globs to match against the path. | 3.347693 | 3.428583 | 0.976407 |
cur = obj
traversed = []
def _presence_test_dict(obj, elem):
return (elem[0] in obj)
def _create_missing_dict(obj, elem):
obj[elem[0]] = elem[1]()
def _presence_test_list(obj, elem):
return (int(str(elem[0])) < len(obj))
def _create_missing_list(obj, elem):
... | def set(obj, path, value, create_missing=True, afilter=None) | Set the value of the given path in the object. Path
must be a list of specific path elements, not a glob.
You can use dpath.util.set for globs, but the paths must
slready exist.
If create_missing is True (the default behavior), then any
missing path components in the dictionary are made silently.
... | 2.431985 | 2.540226 | 0.957389 |
index = 0
path_count = len(path) - 1
target = obj
head = type(target)()
tail = head
up = None
for pair in path:
key = pair[0]
target = target[key]
if view:
if isinstance(tail, MutableMapping):
if issubclass(pair[1], (MutableSequence, ... | def get(obj, path, view=False, afilter=None) | Get the value of the given path.
Arguments:
obj -- Object to look in.
path -- A list of keys representing the path.
Keyword Arguments:
view -- Return a view of the object. | 2.854551 | 3.057146 | 0.933731 |
pathlist = __safe_path__(path, separator)
pathobj = dpath.path.path_types(obj, pathlist)
return dpath.path.set(obj, pathobj, value, create_missing=True) | def new(obj, path, value, separator="/") | Set the element at the terminus of path to value, and create
it if it does not exist (as opposed to 'set' that can only
change existing keys).
path will NOT be treated like a glob. If it has globbing
characters in it, they will become part of the resulting
keys | 7.177568 | 7.714063 | 0.930452 |
deleted = 0
paths = []
globlist = __safe_path__(glob, separator)
for path in _inner_search(obj, globlist, separator):
# These are yielded back, don't mess up the dict.
paths.append(path)
for path in paths:
cur = obj
prev = None
for item in path:
... | def delete(obj, glob, separator="/", afilter=None) | Given a path glob, delete all elements that match the glob.
Returns the number of deleted objects. Raises PathNotFound if no paths are
found to delete. | 5.540024 | 5.641544 | 0.982005 |
changed = 0
globlist = __safe_path__(glob, separator)
for path in _inner_search(obj, globlist, separator):
changed += 1
dpath.path.set(obj, path, value, create_missing=False, afilter=afilter)
return changed | def set(obj, glob, value, separator="/", afilter=None) | Given a path glob, set all existing elements in the document
to the given value. Returns the number of elements changed. | 6.380233 | 5.948278 | 1.072619 |
ret = None
found = False
for item in search(obj, glob, yielded=True, separator=separator):
if ret is not None:
raise ValueError("dpath.util.get() globs must match only one leaf : %s" % glob)
ret = item[1]
found = True
if found is False:
raise KeyError(glo... | def get(obj, glob, separator="/") | Given an object which contains only one possible match for the given glob,
return the value for the leaf matching the given glob.
If more than one leaf matches the glob, ValueError is raised. If the glob is
not found, KeyError is raised. | 4.843939 | 4.87417 | 0.993798 |
return [x[1] for x in dpath.util.search(obj, glob, yielded=True, separator=separator, afilter=afilter, dirs=dirs)] | def values(obj, glob, separator="/", afilter=None, dirs=True) | Given an object and a path glob, return an array of all values which match
the glob. The arguments to this function are identical to those of search(),
and it is primarily a shorthand for a list comprehension over a yielded
search call. | 4.697939 | 3.354512 | 1.400483 |
def _search_view(obj, glob, separator, afilter, dirs):
view = {}
globlist = __safe_path__(glob, separator)
for path in _inner_search(obj, globlist, separator, dirs=dirs):
try:
val = dpath.path.get(obj, path, afilter=afilter, view=True)
merge(... | def search(obj, glob, yielded=False, separator="/", afilter=None, dirs = True) | Given a path glob, return a dictionary containing all keys
that matched the given glob.
If 'yielded' is true, then a dictionary will not be returned.
Instead tuples will be yielded in the form of (path, value) for
every element in the document that matched the glob. | 2.601866 | 2.651923 | 0.981124 |
for path in dpath.path.paths(obj, dirs, leaves, skip=True):
if dpath.path.match(path, glob):
yield path | def _inner_search(obj, glob, separator, dirs=True, leaves=False) | Search the object paths that match the glob. | 6.403387 | 5.095206 | 1.256747 |
if afilter:
# Having merge do its own afiltering is dumb, let search do the
# heavy lifting for us.
src = search(src, '**', afilter=afilter)
return merge(dst, src)
def _check_typesafe(obj1, obj2, key, path):
if not key in obj1:
return
elif ( (fl... | def merge(dst, src, separator="/", afilter=None, flags=MERGE_ADDITIVE, _path="") | Merge source into destination. Like dict.update() but performs
deep merging.
flags is an OR'ed combination of MERGE_ADDITIVE, MERGE_REPLACE, or
MERGE_TYPESAFE.
* MERGE_ADDITIVE : List objects are combined onto one long
list (NOT a set). This is the default flag.
* MERGE_REPLACE : ... | 2.340805 | 2.209358 | 1.059495 |
reversed_morsetab = {symbol: character for character,
symbol in list(getattr(encoding, 'morsetab').items())}
encoding_type = encoding_type.lower()
allowed_encoding_type = ['default', 'binary']
if encoding_type == 'default':
# For spacing the words
letters... | def decode(code, encoding_type='default') | Converts a string of morse code into English message
The encoded message can also be decoded using the same morse chart
backwards.
>>> code = '... --- ...'
>>> decode(code)
'SOS' | 3.994851 | 4.024278 | 0.992688 |
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(fillvalue=fillvalue, *args) | def grouper(n, iterable, fillvalue=None) | grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx | 2.146338 | 2.617927 | 0.819862 |
'''
create a generator which computes the samples.
essentially it creates a sequence of the sum of each function in the channel
at each sample in the file for each channel.
'''
return islice(izip(*(imap(sum, izip(*channel)) for channel in channels)), nsamples) | def compute_samples(channels, nsamples=None) | create a generator which computes the samples.
essentially it creates a sequence of the sum of each function in the channel
at each sample in the file for each channel. | 13.131832 | 3.06629 | 4.282645 |
"Write samples to a wavefile."
if nframes is None:
nframes = 0
w = wave.open(f, 'wb')
w.setparams((nchannels, sampwidth, framerate, nframes, 'NONE', 'not compressed'))
max_amplitude = float(int((2 ** (sampwidth * 8)) / 2) - 1)
# split the samples into chunks (to reduce memory consumpt... | def write_wavefile(f, samples, nframes=None, nchannels=2, sampwidth=2, framerate=44100, bufsize=2048) | Write samples to a wavefile. | 3.016433 | 2.94927 | 1.022773 |
omega = 2.0 * pi * float(frequency)
sine = sin(omega * (float(i) / float(framerate)))
return float(amplitude) * sine | def sine_wave(i, frequency=FREQUENCY, framerate=FRAMERATE, amplitude=AMPLITUDE) | Returns value of a sine wave at a given frequency and framerate
for a given sample i | 3.297199 | 3.168473 | 1.040627 |
lst_bin = _encode_binary(message)
if amplitude > 1.0:
amplitude = 1.0
if amplitude < 0.0:
amplitude = 0.0
seconds_per_dot = _seconds_per_dot(word_ref) # =1.2
for i in count(skip_frame):
bit = morse_bin(i=i, lst_bin=lst_bin, wpm=wpm, framerate=framerate, default_value=0.... | def generate_wave(message, wpm=WPM, framerate=FRAMERATE, skip_frame=0, amplitude=AMPLITUDE, frequency=FREQUENCY, word_ref=WORD) | Generate binary Morse code of message at a given code speed wpm and framerate
Parameters
----------
word : string
wpm : int or float - word per minute
framerate : nb of samples / seconds
word_spaced : bool - calculate with spaces between 2 words (default is False)
skip_frame : int - nb of f... | 4.14147 | 4.602896 | 0.899753 |
try:
return lst_bin[int(float(wpm) * float(i) / (seconds_per_dot * float(framerate)))]
except IndexError:
return default_value | def morse_bin(i, lst_bin, wpm=WPM, framerate=FRAMERATE, default_value=0.0, seconds_per_dot=1.2) | Returns value of a morse bin list at a given framerate and code speed (wpm)
for a given sample i | 3.510655 | 3.218861 | 1.090651 |
bit = morse_bin(i=i, lst_bin=lst_bin, wpm=wpm, framerate=framerate,
default_value=0.0, seconds_per_dot=seconds_per_dot)
sine = sine_wave(i=i, frequency=frequency, framerate=framerate, amplitude=amplitude)
return bit * sine | def calculate_wave(i, lst_bin, wpm=WPM, frequency=FREQUENCY, framerate=FRAMERATE, amplitude=AMPLITUDE, seconds_per_dot=SECONDS_PER_DOT) | Returns product of a sin wave and morse code (dit, dah, silent) | 3.303522 | 3.06038 | 1.079448 |
samp_nb = samples_nb(message=message, wpm=wpm, framerate=framerate, word_spaced=False)
import sounddevice as sd
lst_bin = _encode_binary(message)
amplitude = _limit_value(amplitude)
seconds_per_dot = _seconds_per_dot(word_ref) # 1.2
a = [calculate_wave(i, lst_bin, wpm, frequency, framerate... | def preview_wave(message, wpm=WPM, frequency=FREQUENCY, framerate=FRAMERATE, amplitude=AMPLITUDE, word_ref=WORD) | Listen (preview) wave
sounddevice is required http://python-sounddevice.readthedocs.org/
$ pip install sounddevice | 5.619273 | 5.905925 | 0.951464 |
def to_string(i, s):
if i == 0 and s == ' ':
return ' '
return s
return letter_sep.join([to_string(i, s) for i, s in enumerate(_encode_morse(message))]) | def _encode_to_morse_string(message, letter_sep) | >>> message = "SOS"
>>> _encode_to_morse_string(message, letter_sep=' '*3)
'... --- ...'
>>> message = " SOS"
>>> _encode_to_morse_string(message, letter_sep=' '*3)
' ... --- ...' | 4.149083 | 4.478416 | 0.926462 |
l = _encode_morse(message)
s = ' '.join(l)
l = list(s)
bin_conv = {'.': [on], '-': [on] * 3, ' ': [off]}
l = map(lambda symb: [off] + bin_conv[symb], l)
lst = [item for sublist in l for item in sublist] # flatten list
return lst[1:] | def _encode_binary(message, on=1, off=0) | >>> message = "SOS"
>>> _encode_binary(message)
[1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1]
>>> _encode_binary(message, on='1', off='0')
['1', '0', '1', '0', '1', '0', '0', '0', '1', '1', '1', '0', '1', '1', '1', '0', '1', '1', '1', '0', '0', '0', '1', '0', '1', '0... | 5.30239 | 5.584228 | 0.94953 |
def to_string(i, s):
if i == 0 and s == off:
return off * 4
return s
return ''.join(to_string(i, s) for i, s in enumerate(_encode_binary(message, on=on, off=off))) | def _encode_to_binary_string(message, on, off) | >>> message = "SOS"
>>> _encode_to_binary_string(message, on='1', off='0')
'101010001110111011100010101'
>>> message = " SOS"
>>> _encode_to_binary_string(message, on='1', off='0')
'0000000101010001110111011100010101' | 5.20392 | 5.254568 | 0.990361 |
if strip:
message = message.strip() # No trailing or leading spaces
encoding_type = encoding_type.lower()
allowed_encoding_type = ['default', 'binary']
if encoding_type == 'default':
return _encode_to_morse_string(message, letter_sep)
elif encoding_type == 'binary':
r... | def encode(message, encoding_type='default', letter_sep=' ' * 3, strip=True) | Converts a string of message into morse
Two types of marks are there. One is short mark, dot(.) or "dit" and
other is long mark, dash(-) or "dah". After every dit or dah, there is
a one dot duration or one unit log gap.
Between every letter, there is a short gap (three units long).
Between every w... | 3.235435 | 3.332961 | 0.970739 |
l = [0] + l + [0]
y = []
x = []
for i, bit in enumerate(l):
y.append(bit)
y.append(bit)
x.append((i - 1) * duration)
x.append(i * duration)
return x, y | def _create_x_y(l, duration=1) | Create 2 lists
x: time (as unit of dot (dit)
y: bits
from a list of bit
>>> l = [1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1]
>>> x, y = _create_x_y(l)
>>> x
[-1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, ... | 2.687015 | 2.89794 | 0.927215 |
lst_bin = _encode_binary(message)
x, y = _create_x_y(lst_bin, duration)
ax = _create_ax(ax)
ax.plot(x, y, linewidth=2.0)
delta_y = 0.1
ax.set_ylim(-delta_y, 1 + delta_y)
ax.set_yticks([0, 1])
delta_x = 0.5 * duration
ax.set_xlim(-delta_x, len(lst_bin) * duration + delta_x)
r... | def plot(message, duration=1, ax=None) | Plot a message
Returns: ax a Matplotlib Axe | 3.110419 | 3.285979 | 0.946573 |
message = (word_space + word) * N
message = message[len(word_space):]
return message | def _repeat_word(word, N, word_space=" ") | Return a repeated string
>>> word = "PARIS"
>>> _repeat_word(word, 5)
'PARIS PARIS PARIS PARIS PARIS'
>>> _repeat_word(word, 5, word_space="")
'PARISPARISPARISPARISPARIS' | 4.573348 | 9.531692 | 0.479804 |
message = _repeat_word(message, N)
if word_spaced:
message = message + " E"
lst_bin = _encode_binary(message)
N = len(lst_bin)
if word_spaced:
N -= 1 # E is one "dit" so we remove it
return N | def mlength(message, N=1, word_spaced=True) | Returns Morse length
>>> message = "PARIS"
>>> mlength(message)
50
>>> mlength(message, 5)
250 | 7.875262 | 10.601647 | 0.742834 |
N = mlength(word_ref) * wpm
output = output.lower()
allowed_output = ['decimal', 'float', 'timedelta']
if output == 'decimal':
import decimal
duration = 60 * 1000 / decimal.Decimal(N)
elif output == 'float':
duration = 60 * 1000 / float(N)
elif output == 'timedelta':... | def wpm_to_duration(wpm, output='timedelta', word_ref=WORD) | Convert from WPM (word per minutes) to
element duration
Parameters
----------
wpm : int or float - word per minute
output : String - type of output
'timedelta'
'float'
'decimal'
word_ref : string - reference word (PARIS by default)
Returns
-------
duration :... | 2.897107 | 3.279554 | 0.883384 |
elt_duration = wpm_to_duration(wpm, output=output, word_ref=word_ref)
word_length = mlength(message, word_spaced=word_spaced)
return word_length * elt_duration | def duration(message, wpm, output='timedelta', word_ref=WORD, word_spaced=False) | Calculate duration to send a message at a given code speed
(calculated using reference word PARIS)
Parameters
----------
word : string
wpm : int or float - word per minute
output : String - type of output
'timedelta'
'float'
'decimal'
word : string - reference word (... | 4.431416 | 7.224977 | 0.613347 |
return int(duration(message, wpm, output='float', word_spaced=word_spaced) / 1000.0 * framerate) | def samples_nb(message, wpm, framerate=FRAMERATE, word_spaced=False) | Calculate the number of samples for a given word at a given framerate (samples / seconds)
>>> samples_nb('SOS', 15)
23814 | 5.379374 | 7.62218 | 0.705753 |
seconds_per_dot = _seconds_per_dot(word_ref)
if element_duration is None and wpm is None:
# element_duration = 1
# wpm = seconds_per_dot / element_duration
wpm = WPM
element_duration = wpm_to_duration(wpm, output='float', word_ref=WORD) / 1000.0
return element_durati... | def _get_speed(element_duration, wpm, word_ref=WORD) | Returns
element duration when element_duration and/or code speed is given
wpm
>>> _get_speed(0.2, None)
(0.2, 5.999999999999999)
>>> _get_speed(None, 15)
(0.08, 15)
>>> _get_speed(None, None)
(0.08, 15) | 2.289218 | 2.375079 | 0.963849 |
lst = range(1, N + 1)
return "".join(list(map(lambda i: str(i % 10), lst))) | def _numbers_units(N) | >>> _numbers_units(45)
'123456789012345678901234567890123456789012345' | 5.089118 | 4.53611 | 1.121912 |
N = N // 10
lst = range(1, N + 1)
return "".join(map(lambda i: "%10s" % i, lst)) | def _numbers_decades(N) | >>> _numbers_decades(45)
' 1 2 3 4' | 5.028756 | 4.661253 | 1.078842 |
s_bin = mtalk.encode(c, encoding_type='binary', letter_sep=' ')
N = len(s_bin)
if align == ALIGN.LEFT:
s_align = "<"
elif align == ALIGN.RIGHT:
s_align = ">"
elif align == ALIGN.CENTER:
s_align = "^"
else:
raise NotImplementedError("align '%s' not allowed" % ... | def _char_to_string_binary(c, align=ALIGN.LEFT, padding='-') | >>> _char_to_string_binary('O', align=ALIGN.LEFT)
'O----------'
>>> _char_to_string_binary('O', align=ALIGN.RIGHT)
'----------O'
>>> _char_to_string_binary('O', align=ALIGN.CENTER)
'-----O-----' | 4.240354 | 4.817955 | 0.880115 |
s = _encode_to_binary_string(message, on="=", off=".")
N = len(s)
s += '\n' + _numbers_decades(N)
s += '\n' + _numbers_units(N)
s += '\n'
s += '\n' + _timing_char(message)
return s | def _timing_representation(message) | Returns timing representation of a message like
1 2 3 4 5 6 7 8
12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
M------ O---------- R------ S---- E C---------- O---------- D------ ... | 6.415025 | 7.522196 | 0.852813 |
s = ''
inter_symb = ' '
inter_char = ' ' * 3
inter_word = inter_symb * 7
for i, word in enumerate(_split_message(message)):
if i >= 1:
s += inter_word
for j, c in enumerate(word):
if j != 0:
s += inter_char
s += _char_to_string... | def _timing_char(message) | >>> message = 'MORSE CODE'
>>> _timing_char(message)
'M------ O---------- R------ S---- E C---------- O---------- D------ E' | 4.780751 | 4.797036 | 0.996605 |
s = ''
inter_char = ' '
inter_word = inter_char * 9
for i, word in enumerate(lst_lst_char):
if i >= 1:
s += inter_word
for j, c in enumerate(word):
if j != 0:
s += inter_char
s += _char_to_string_morse(c)
return s | def _spoken_representation_L1(lst_lst_char) | >>> lst = [['M', 'O', 'R', 'S', 'E'], ['C', 'O', 'D', 'E']]
>>> _spoken_representation_L1(lst)
'M O R S E C O D E'
>>> lst = [[], ['M', 'O', 'R', 'S', 'E'], ['C', 'O', 'D', 'E']]
>>> _spoken_representation_L1(lst)
' M O R S E C O D E' | 3.416668 | 3.754213 | 0.910089 |
s = ''
inter_char = ' '
inter_word = ' (space) '
for i, word in enumerate(lst_lst_char):
if i >= 1:
s += inter_word
for j, c in enumerate(word):
if j != 0:
s += inter_char
s += mtalk.encoding.morsetab[c]
return s | def _spoken_representation_L2(lst_lst_char) | >>> lst = [['M', 'O', 'R', 'S', 'E'], ['C', 'O', 'D', 'E']]
>>> _spoken_representation_L2(lst)
'-- --- .-. ... . (space) -.-. --- -.. .' | 5.091529 | 4.909507 | 1.037075 |
lst_lst_char = _split_message(message)
s = _spoken_representation_L1(lst_lst_char)
s += '\n' + _spoken_representation_L2(lst_lst_char)
return s | def _spoken_representation(message) | Returns 2 lines of spoken representation of a message
like:
M O R S E C O D E
(space) -- --- .-. ... . (space) -.-. --- -.. . | 4.290999 | 4.525802 | 0.948119 |
fmt = "{0:>8s}: '{1}'"
key = "text"
if strip:
print(fmt.format(key, message.strip()))
else:
print(fmt.format(key, message.strip()))
print(fmt.format("morse", mtalk.encode(message, strip=strip)))
print(fmt.format("bin", mtalk.encode(message, encoding_type='binary', strip=stri... | def display(message, wpm, element_duration, word_ref, strip=False) | Display
text message
morse code
binary morse code | 3.699764 | 3.55893 | 1.039572 |
if value > upper:
return(upper)
if value < lower:
return(lower)
return value | def _limit_value(value, upper=1.0, lower=0.0) | Returs value (such as amplitude) to upper and lower value
>>> _limit_value(0.5)
0.5
>>> _limit_value(1.5)
1.0
>>> _limit_value(-1.5)
0.0 | 3.4168 | 5.549575 | 0.615687 |
''' take a field_name_label and return the id'''
if self.is_child:
try:
return self._children[label]
except KeyError:
self._children[label] = ChildFieldPicklist(self.parent,
label,
... | def lookup(self, label) | take a field_name_label and return the id | 5.590404 | 4.265857 | 1.310499 |
''' take a field_name_id and return the label '''
label = get_value_label(value, self._picklist, condition=condition)
return label | def reverse_lookup(self, value, condition=is_active) | take a field_name_id and return the label | 13.500394 | 6.772853 | 1.99331 |
'type: wrapper :atws.Wrapper'
fields = wrapper.new('GetFieldInfo')
fields.psObjectType = entity_type
return wrapper.GetFieldInfo(fields) | def get_field_info(wrapper,entity_type) | type: wrapper :atws.Wrapper | 30.970671 | 10.273293 | 3.014678 |
item = {
"info": {"key": key or title, "synonyms": synonyms or []},
"title": title,
"description": description,
"image": {
"imageUri": img_url or "",
"accessibilityText": alt_text or "{} img".format(title),
},
}
return item | def build_item(
title, key=None, synonyms=None, description=None, img_url=None, alt_text=None
) | Builds an item that may be added to List or Carousel | 3.152592 | 3.099729 | 1.017054 |
chips = []
for r in replies:
chips.append({"title": r})
# NOTE: both of these formats work in the dialogflow console,
# but only the first (suggestions) appears in actual Google Assistant
# native chips for GA
self._messages.append(
{"pl... | def suggest(self, *replies) | Use suggestion chips to hint at responses to continue or pivot the conversation | 5.80833 | 5.165233 | 1.124505 |
self._messages.append(
{
"platform": "ACTIONS_ON_GOOGLE",
"linkOutSuggestion": {"destinationName": name, "uri": url},
}
)
return self | def link_out(self, name, url) | Presents a chip similar to suggestion, but instead links to a url | 5.285056 | 5.497053 | 0.961435 |
list_card = _ListSelector(
self._speech, display_text=self._display_text, title=title, items=items
)
return list_card | def build_list(self, title=None, items=None) | Presents the user with a vertical list of multiple items.
Allows the user to select a single item.
Selection generates a user query containing the title of the list item
*Note* Returns a completely new object,
and does not modify the existing response object
Therefore, to add i... | 9.044607 | 6.546038 | 1.381692 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.