_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q262300
BaseAXUIElement._performAction
validation
def _performAction(self, action): """Perform the specified action.""" try: _a11y.AXUIElement._performAction(self, 'AX%s' %
python
{ "resource": "" }
q262301
BaseAXUIElement._generateChildren
validation
def _generateChildren(self): """Generator which yields all AXChildren of the object.""" try:
python
{ "resource": "" }
q262302
BaseAXUIElement._generateChildrenR
validation
def _generateChildrenR(self, target=None): """Generator which recursively yields all AXChildren of the object.""" if target is None: target = self
python
{ "resource": "" }
q262303
BaseAXUIElement._match
validation
def _match(self, **kwargs): """Method which indicates if the object matches specified criteria. Match accepts criteria as kwargs and looks them up on attributes. Actual matching is performed with fnmatch, so shell-like wildcards work within match strings. Examples: obj._match(AXTitle='Terminal*') obj._match(AXRole='TextField', AXRoleDescription='search text field') """ for k in kwargs.keys(): try: val = getattr(self, k) except _a11y.Error: return False # Not all values may be strings (e.g. size, position) if sys.version_info[:2] <= (2, 6): if isinstance(val, basestring): if not fnmatch.fnmatch(unicode(val), kwargs[k]): return False else: if val != kwargs[k]:
python
{ "resource": "" }
q262304
BaseAXUIElement._matchOther
validation
def _matchOther(self, obj, **kwargs): """Perform _match but on another object, not self.""" if obj is not None: # Need to check that the returned UI element wasn't destroyed first:
python
{ "resource": "" }
q262305
BaseAXUIElement._generateFind
validation
def _generateFind(self, **kwargs): """Generator which yields matches on AXChildren."""
python
{ "resource": "" }
q262306
BaseAXUIElement._generateFindR
validation
def _generateFindR(self, **kwargs): """Generator which yields matches on AXChildren and their children."""
python
{ "resource": "" }
q262307
BaseAXUIElement._findAll
validation
def _findAll(self, **kwargs): """Return a list of all children that match the specified criteria.""" result = []
python
{ "resource": "" }
q262308
BaseAXUIElement._getApplication
validation
def _getApplication(self): """Get the base application UIElement. If the UIElement is a child of the application, it will try to get the AXParent until it reaches the top application level element. """ app = self
python
{ "resource": "" }
q262309
BaseAXUIElement._getBundleId
validation
def _getBundleId(self): """Return the bundle ID of the application.""" ra = AppKit.NSRunningApplication app
python
{ "resource": "" }
q262310
NativeUIElement.popUpItem
validation
def popUpItem(self, *args): """Return the specified item in a pop up menu.""" self.Press()
python
{ "resource": "" }
q262311
NativeUIElement.dragMouseButtonLeft
validation
def dragMouseButtonLeft(self, coord, dest_coord, interval=0.5): """Drag the left mouse button without modifiers pressed. Parameters: coordinates to click on screen (tuple (x, y)) dest coordinates to drag to (tuple (x, y)) interval to send event of btn down, drag and up Returns: None """ modFlags = 0
python
{ "resource": "" }
q262312
NativeUIElement.doubleClickDragMouseButtonLeft
validation
def doubleClickDragMouseButtonLeft(self, coord, dest_coord, interval=0.5): """Double-click and drag the left mouse button without modifiers pressed. Parameters: coordinates to double-click on screen (tuple (x, y)) dest coordinates to drag to (tuple (x, y)) interval to send event of btn down, drag and up Returns: None """ modFlags = 0 self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags,
python
{ "resource": "" }
q262313
NativeUIElement.clickMouseButtonLeft
validation
def clickMouseButtonLeft(self, coord, interval=None): """Click the left mouse button without modifiers pressed. Parameters: coordinates to click on screen (tuple (x, y)) Returns: None """ modFlags = 0
python
{ "resource": "" }
q262314
NativeUIElement.clickMouseButtonRight
validation
def clickMouseButtonRight(self, coord): """Click the right mouse button without modifiers pressed. Parameters: coordinates to click on scren (tuple (x, y)) Returns: None """ modFlags =
python
{ "resource": "" }
q262315
NativeUIElement.clickMouseButtonRightWithMods
validation
def clickMouseButtonRightWithMods(self, coord, modifiers): """Click the right mouse button with modifiers pressed. Parameters: coordinates to click; modifiers (list) Returns: None """ modFlags = self._pressModifiers(modifiers)
python
{ "resource": "" }
q262316
NativeUIElement.leftMouseDragged
validation
def leftMouseDragged(self, stopCoord, strCoord=(0, 0), speed=1): """Click the left mouse button and drag object. Parameters: stopCoord, the position of dragging stopped
python
{ "resource": "" }
q262317
NativeUIElement.doubleClickMouse
validation
def doubleClickMouse(self, coord): """Double-click primary mouse button. Parameters: coordinates to click (assume primary is left button) Returns: None """ modFlags = 0 self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags) # This is a kludge:
python
{ "resource": "" }
q262318
NativeUIElement.tripleClickMouse
validation
def tripleClickMouse(self, coord): """Triple-click primary mouse button. Parameters: coordinates to click (assume primary is left button) Returns: None """ # Note above re: double-clicks applies to triple-clicks modFlags = 0 for i in range(2):
python
{ "resource": "" }
q262319
NativeUIElement.waitFor
validation
def waitFor(self, timeout, notification, **kwargs): """Generic wait for a UI event that matches the specified criteria to occur. For customization of the callback, use keyword args labeled 'callback', 'args', and 'kwargs' for the callback fn, callback args, and callback kwargs, respectively. Also note that on return, the observer-returned UI element will be included
python
{ "resource": "" }
q262320
NativeUIElement.waitForCreation
validation
def waitForCreation(self, timeout=10, notification='AXCreated'): """Convenience method to wait for creation of some UI element. Returns: The element created """ callback = AXCallbacks.returnElemCallback retelem = None
python
{ "resource": "" }
q262321
NativeUIElement.waitForWindowToDisappear
validation
def waitForWindowToDisappear(self, winName, timeout=10): """Convenience method to wait for a window with the given name to disappear. Returns: Boolean """ callback = AXCallbacks.elemDisappearedCallback retelem = None args = (retelem, self) # For some reason for the AXUIElementDestroyed notification to fire,
python
{ "resource": "" }
q262322
NativeUIElement.waitForValueToChange
validation
def waitForValueToChange(self, timeout=10): """Convenience method to wait for value attribute of given element to change. Some types of elements (e.g. menu items) have their titles change, so this will not work for those. This seems to work best if you set the notification at the application level. Returns: Element or None """ # Want to identify that the element whose value changes matches this # object's. Unique identifiers considered include role and position # This seems to
python
{ "resource": "" }
q262323
NativeUIElement.waitForFocusedWindowToChange
validation
def waitForFocusedWindowToChange(self, nextWinName, timeout=10): """Convenience method to wait for focused window to change Returns: Boolean """ callback = AXCallbacks.returnElemCallback retelem = None
python
{ "resource": "" }
q262324
removecallback
validation
def removecallback(window_name): """ Remove registered callback on window create @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @return: 1 if registration was successful, 0 if not. @rtype: integer """
python
{ "resource": "" }
q262325
stopEventLoop
validation
def stopEventLoop(): """ Stop the current event loop if possible returns True if it expects that it was successful, False otherwise """ stopper = PyObjCAppHelperRunLoopStopper_wrap.currentRunLoopStopper() if stopper is None: if NSApp() is not None: NSApp().terminate_(None)
python
{ "resource": "" }
q262326
main
validation
def main(port=4118, parentpid=None): """Main entry point. Parse command line options and start up a server.""" if "LDTP_DEBUG" in os.environ: _ldtp_debug = True else: _ldtp_debug = False _ldtp_debug_file = os.environ.get('LDTP_DEBUG_FILE', None) if _ldtp_debug: print("Parent PID: {}".format(int(parentpid))) if _ldtp_debug_file: with open(unicode(_ldtp_debug_file), "a") as fp: fp.write("Parent PID: {}".format(int(parentpid)))
python
{ "resource": "" }
q262327
LDTPServer.server_bind
validation
def server_bind(self, *args, **kwargs): '''Server Bind. Forces reuse of port.''' self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
python
{ "resource": "" }
q262328
ooldtp.log
validation
def log(self, message, level=logging.DEBUG): """ Logs the message in the root logger with the log level @param message: Message to be logged @type message: string @param level: Log level, defaul DEBUG @type level: integer
python
{ "resource": "" }
q262329
ooldtp.stoplog
validation
def stoplog(self): """ Stop logging. @return: 1 on success and 0 on error @rtype: integer
python
{ "resource": "" }
q262330
ooldtp.imagecapture
validation
def imagecapture(self, window_name=None, out_file=None, x=0, y=0, width=None, height=None): """ Captures screenshot of the whole desktop or given window @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param x: x co-ordinate value @type x: integer @param y: y co-ordinate value @type y: integer @param width: width co-ordinate value @type width: integer
python
{ "resource": "" }
q262331
ooldtp.onwindowcreate
validation
def onwindowcreate(self, window_name, fn_name, *args): """ On window create, call the function with given arguments @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string
python
{ "resource": "" }
q262332
ooldtp.registerevent
validation
def registerevent(self, event_name, fn_name, *args): """ Register at-spi event @param event_name: Event name in at-spi format. @type event_name: string @param fn_name: Callback function @type fn_name: function @param *args: arguments to be passed
python
{ "resource": "" }
q262333
ooldtp.registerkbevent
validation
def registerkbevent(self, keys, modifiers, fn_name, *args): """ Register keystroke events @param keys: key to listen @type keys: string @param modifiers: control / alt combination using gtk MODIFIERS @type modifiers: int @param fn_name: Callback function
python
{ "resource": "" }
q262334
ooldtp.windowuptime
validation
def windowuptime(self, window_name): """ Get window uptime @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @return: "starttime, endtime" as datetime python object """ tmp_time = self._remote_windowuptime(window_name) if tmp_time: tmp_time = tmp_time.split('-')
python
{ "resource": "" }
q262335
Value.verifyscrollbarvertical
validation
def verifyscrollbarvertical(self, window_name, object_name): """ Verify scrollbar is vertical @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success. @rtype: integer """
python
{ "resource": "" }
q262336
Value.verifyscrollbarhorizontal
validation
def verifyscrollbarhorizontal(self, window_name, object_name): """ Verify scrollbar is horizontal @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success. @rtype: integer """
python
{ "resource": "" }
q262337
Value.setmax
validation
def setmax(self, window_name, object_name): """ Set max value @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob.
python
{ "resource": "" }
q262338
Value.setmin
validation
def setmin(self, window_name, object_name): """ Set min value @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob.
python
{ "resource": "" }
q262339
Value.onedown
validation
def onedown(self, window_name, object_name, iterations): """ Press scrollbar down with number of iterations @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param interations: iterations to perform on slider increase @type iterations: integer @return: 1 on success. @rtype: integer """ if not self.verifyscrollbarvertical(window_name, object_name): raise LdtpServerException('Object not vertical scrollbar')
python
{ "resource": "" }
q262340
Value.oneup
validation
def oneup(self, window_name, object_name, iterations): """ Press scrollbar up with number of iterations @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param interations: iterations to perform on slider increase @type iterations: integer @return: 1 on success. @rtype: integer """ if not self.verifyscrollbarvertical(window_name, object_name): raise LdtpServerException('Object not vertical scrollbar') object_handle =
python
{ "resource": "" }
q262341
Value.oneright
validation
def oneright(self, window_name, object_name, iterations): """ Press scrollbar right with number of iterations @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param interations: iterations to perform on slider increase @type iterations: integer @return: 1 on success. @rtype: integer """ if not self.verifyscrollbarhorizontal(window_name, object_name): raise LdtpServerException('Object not horizontal scrollbar') object_handle
python
{ "resource": "" }
q262342
Value.oneleft
validation
def oneleft(self, window_name, object_name, iterations): """ Press scrollbar left with number of iterations @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param interations: iterations to perform on slider increase @type iterations: integer @return: 1 on success. @rtype: integer """ if not self.verifyscrollbarhorizontal(window_name, object_name): raise LdtpServerException('Object not horizontal scrollbar') object_handle =
python
{ "resource": "" }
q262343
ComboBox.getallitem
validation
def getallitem(self, window_name, object_name): """ Get all combo box item @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: list of string on success. @rtype: list """ object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) object_handle.Press() # Required for menuitem to appear in accessibility list self.wait(1) child = None try: if not object_handle.AXChildren: raise LdtpServerException(u"Unable to find menu") # Get AXMenu children = object_handle.AXChildren[0] if not children:
python
{ "resource": "" }
q262344
MobileClientWrapper.login
validation
def login(self, username=None, password=None, android_id=None): """Authenticate the gmusicapi Mobileclient instance. Parameters: username (Optional[str]): Your Google Music username. Will be prompted if not given. password (Optional[str]): Your Google Music password. Will be prompted if not given. android_id (Optional[str]): The 16 hex digits from an Android device ID. Default: Use gmusicapi.Mobileclient.FROM_MAC_ADDRESS to create ID from computer's MAC address. Returns: ``True`` on successful login or ``False`` on unsuccessful login. """ cls_name = type(self).__name__ if username is None: username = input("Enter your Google username or email address: ") if password is None: password = getpass.getpass("Enter your Google Music password: ") if android_id is None:
python
{ "resource": "" }
q262345
MobileClientWrapper.get_google_playlist
validation
def get_google_playlist(self, playlist): """Get playlist information of a user-generated Google Music playlist. Parameters: playlist (str): Name or ID of Google Music playlist. Names are case-sensitive. Google allows multiple playlists with the same name. If multiple playlists have the same name, the first one encountered is used. Returns: dict: The playlist dict as returned by Mobileclient.get_all_user_playlist_contents. """ logger.info("Loading playlist {0}".format(playlist)) for google_playlist in
python
{ "resource": "" }
q262346
MobileClientWrapper.get_google_playlist_songs
validation
def get_google_playlist_songs(self, playlist, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False): """Create song list from a user-generated Google Music playlist. Parameters: playlist (str): Name or ID of Google Music playlist. Names are case-sensitive. Google allows multiple playlists with the same name. If multiple playlists have the same name, the first one encountered is used. include_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid Google Music metadata field available to the Musicmanager client. Patterns are Python regex patterns. Google Music songs are filtered out if the given metadata field values don't match any of the given patterns. exclude_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid Google Music metadata field available to the Musicmanager client. Patterns are Python regex patterns. Google Music songs are filtered out if the given metadata field values match any of the given patterns. all_includes (bool): If ``True``, all include_filters criteria must match to include a song. all_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song.
python
{ "resource": "" }
q262347
cast_to_list
validation
def cast_to_list(position): """Cast the positional argument at given position into a list if not already a list.""" @wrapt.decorator def wrapper(function, instance, args, kwargs): if not isinstance(args[position], list): args = list(args)
python
{ "resource": "" }
q262348
_pybossa_req
validation
def _pybossa_req(method, domain, id=None, payload=None, params={}, headers={'content-type': 'application/json'}, files=None): """ Send a JSON request. Returns True if everything went well, otherwise it returns the status code of the response. """ url = _opts['endpoint'] + '/api/' + domain if id is not None: url += '/' + str(id) if 'api_key' in _opts: params['api_key'] = _opts['api_key'] if method == 'get': r = requests.get(url, params=params) elif method == 'post': if files is None and headers['content-type'] == 'application/json': r = requests.post(url, params=params, headers=headers, data=json.dumps(payload))
python
{ "resource": "" }
q262349
get_projects
validation
def get_projects(limit=100, offset=0, last_id=None): """Return a list of registered projects. :param limit: Number of returned items, default 100 :type limit: integer :param offset: Offset for the query, default 0 :type offset: integer :param last_id: id of the last project, used for pagination. If provided, offset is ignored :type last_id: integer :rtype: list :returns: A list of PYBOSSA Projects """ if last_id is not None: params = dict(limit=limit, last_id=last_id) else: print(OFFSET_WARNING) params = dict(limit=limit, offset=offset)
python
{ "resource": "" }
q262350
get_project
validation
def get_project(project_id): """Return a PYBOSSA Project for the project_id. :param project_id: PYBOSSA Project ID :type project_id: integer :rtype: PYBOSSA Project :returns: A PYBOSSA Project object """ try: res = _pybossa_req('get', 'project', project_id)
python
{ "resource": "" }
q262351
find_project
validation
def find_project(**kwargs): """Return a list with matching project arguments. :param kwargs: PYBOSSA Project members :rtype: list :returns: A list of projects that match the kwargs """ try: res = _pybossa_req('get', 'project', params=kwargs) if type(res).__name__
python
{ "resource": "" }
q262352
create_project
validation
def create_project(name, short_name, description): """Create a project. :param name: PYBOSSA Project Name :type name: string :param short_name: PYBOSSA Project short name or slug :type short_name: string :param description: PYBOSSA Project description
python
{ "resource": "" }
q262353
update_project
validation
def update_project(project): """Update a project instance. :param project: PYBOSSA project :type project: PYBOSSA Project :returns: True -- the response status code """ try:
python
{ "resource": "" }
q262354
delete_project
validation
def delete_project(project_id): """Delete a Project with id = project_id. :param project_id: PYBOSSA Project ID :type project_id: integer :returns: True -- the response status code """ try: res = _pybossa_req('delete', 'project', project_id)
python
{ "resource": "" }
q262355
get_categories
validation
def get_categories(limit=20, offset=0, last_id=None): """Return a list of registered categories. :param limit: Number of returned items, default 20 :type limit: integer :param offset: Offset for the query, default 0 :type offset: integer :param last_id: id of the last category, used for pagination. If provided, offset is ignored :type last_id: integer :rtype: list :returns: A list of PYBOSSA Categories """ if last_id is not None: params = dict(limit=limit, last_id=last_id) else: params = dict(limit=limit, offset=offset)
python
{ "resource": "" }
q262356
get_category
validation
def get_category(category_id): """Return a PYBOSSA Category for the category_id. :param category_id: PYBOSSA Category ID :type category_id: integer :rtype: PYBOSSA Category :returns: A PYBOSSA Category object """ try: res = _pybossa_req('get', 'category', category_id)
python
{ "resource": "" }
q262357
find_category
validation
def find_category(**kwargs): """Return a list with matching Category arguments. :param kwargs: PYBOSSA Category members :rtype: list :returns: A list of project that match the kwargs """ try: res = _pybossa_req('get', 'category', params=kwargs) if type(res).__name__
python
{ "resource": "" }
q262358
create_category
validation
def create_category(name, description): """Create a Category. :param name: PYBOSSA Category Name :type name: string :param description: PYBOSSA Category description :type decription: string :returns: True -- the response status code """ try: category = dict(name=name, short_name=name.lower().replace(" ", ""),
python
{ "resource": "" }
q262359
update_category
validation
def update_category(category): """Update a Category instance. :param category: PYBOSSA Category :type category: PYBOSSA Category :returns: True -- the response status code """ try: res = _pybossa_req('put', 'category',
python
{ "resource": "" }
q262360
delete_category
validation
def delete_category(category_id): """Delete a Category with id = category_id. :param category_id: PYBOSSA Category ID :type category_id: integer :returns: True -- the response status code """ try: res = _pybossa_req('delete', 'category', category_id)
python
{ "resource": "" }
q262361
get_tasks
validation
def get_tasks(project_id, limit=100, offset=0, last_id=None): """Return a list of tasks for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param limit: Number of returned items, default 100 :type limit: integer :param offset: Offset for the query, default 0 :param last_id: id of the last task, used for pagination. If provided, offset is ignored :type last_id: integer :type offset: integer :returns: True -- the response status code """ if last_id is not None: params = dict(limit=limit, last_id=last_id) else: params = dict(limit=limit, offset=offset)
python
{ "resource": "" }
q262362
find_tasks
validation
def find_tasks(project_id, **kwargs): """Return a list of matched tasks for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param kwargs: PYBOSSA Task members :type info: dict :rtype: list :returns: A list of tasks that match the kwargs """ try: kwargs['project_id']
python
{ "resource": "" }
q262363
create_task
validation
def create_task(project_id, info, n_answers=30, priority_0=0, quorum=0): """Create a task for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param info: PYBOSSA Project info JSON field :type info: dict :param n_answers: Number of answers or TaskRuns per task, default 30 :type n_answers: integer :param priority_0: Value between 0 and 1 indicating priority of task within Project (higher = more important), default 0.0 :type priority_0: float :param quorum: Number of times this task should be done by different users, default 0 :type quorum: integer :returns: True -- the response status code """ try:
python
{ "resource": "" }
q262364
update_task
validation
def update_task(task): """Update a task for a given task ID. :param task: PYBOSSA task """ try: task_id = task.id task = _forbidden_attributes(task) res = _pybossa_req('put', 'task', task_id, payload=task.data)
python
{ "resource": "" }
q262365
delete_task
validation
def delete_task(task_id): """Delete a task for a given task ID. :param task: PYBOSSA task """ #: :arg task: A task try: res = _pybossa_req('delete', 'task', task_id)
python
{ "resource": "" }
q262366
get_taskruns
validation
def get_taskruns(project_id, limit=100, offset=0, last_id=None): """Return a list of task runs for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param limit: Number of returned items, default 100 :type limit: integer :param offset: Offset for the query, default 0 :type offset: integer :param last_id: id of the last taskrun, used for pagination. If provided, offset is ignored :type last_id: integer :rtype: list :returns: A list of task runs for the given project ID """ if last_id is not None: params = dict(limit=limit, last_id=last_id) else:
python
{ "resource": "" }
q262367
find_taskruns
validation
def find_taskruns(project_id, **kwargs): """Return a list of matched task runs for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param kwargs: PYBOSSA Task Run members :rtype: list :returns: A List of task runs that match the query members """ try: kwargs['project_id'] = project_id
python
{ "resource": "" }
q262368
delete_taskrun
validation
def delete_taskrun(taskrun_id): """Delete the given taskrun. :param task: PYBOSSA task """ try: res = _pybossa_req('delete', 'taskrun', taskrun_id) if type(res).__name__ == 'bool':
python
{ "resource": "" }
q262369
get_results
validation
def get_results(project_id, limit=100, offset=0, last_id=None): """Return a list of results for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param limit: Number of returned items, default 100 :type limit: integer :param offset: Offset for the query, default 0 :param last_id: id of the last result, used for pagination. If provided, offset is ignored :type last_id: integer :type offset: integer :returns: True -- the response status code """ if last_id is not None: params = dict(limit=limit, last_id=last_id) else: params = dict(limit=limit, offset=offset)
python
{ "resource": "" }
q262370
find_results
validation
def find_results(project_id, **kwargs): """Return a list of matched results for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param kwargs: PYBOSSA Results members :type info: dict :rtype: list :returns: A list of results that match the kwargs """ try: kwargs['project_id']
python
{ "resource": "" }
q262371
update_result
validation
def update_result(result): """Update a result for a given result ID. :param result: PYBOSSA result """ try: result_id = result.id result = _forbidden_attributes(result) res = _pybossa_req('put', 'result', result_id, payload=result.data)
python
{ "resource": "" }
q262372
_forbidden_attributes
validation
def _forbidden_attributes(obj): """Return the object without the forbidden attributes.""" for key in list(obj.data.keys()): if key
python
{ "resource": "" }
q262373
create_helpingmaterial
validation
def create_helpingmaterial(project_id, info, media_url=None, file_path=None): """Create a helping material for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param info: PYBOSSA Helping Material info JSON field :type info: dict :param media_url: URL for a media file (image, video or audio) :type media_url: string :param file_path: File path to the local image, video or sound to upload. :type file_path: string
python
{ "resource": "" }
q262374
get_helping_materials
validation
def get_helping_materials(project_id, limit=100, offset=0, last_id=None): """Return a list of helping materials for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param limit: Number of returned items, default 100 :type limit: integer :param offset: Offset for the query, default 0 :param last_id: id of the last helping material, used for pagination. If provided, offset is ignored :type last_id: integer :type offset: integer :returns: True -- the response status code """ if last_id is not None: params = dict(limit=limit, last_id=last_id) else: params = dict(limit=limit, offset=offset)
python
{ "resource": "" }
q262375
find_helping_materials
validation
def find_helping_materials(project_id, **kwargs): """Return a list of matched helping materials for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param kwargs: PYBOSSA HelpingMaterial members :type info: dict :rtype: list :returns: A list of helping materials that match the kwargs """ try:
python
{ "resource": "" }
q262376
update_helping_material
validation
def update_helping_material(helpingmaterial): """Update a helping material for a given helping material ID. :param helpingmaterial: PYBOSSA helping material """ try: helpingmaterial_id = helpingmaterial.id helpingmaterial = _forbidden_attributes(helpingmaterial) res = _pybossa_req('put', 'helpingmaterial',
python
{ "resource": "" }
q262377
MusicManagerWrapper.login
validation
def login(self, oauth_filename="oauth", uploader_id=None): """Authenticate the gmusicapi Musicmanager instance. Parameters: oauth_filename (str): The filename of the oauth credentials file to use/create for login. Default: ``oauth`` uploader_id (str): A unique id as a MAC address (e.g. ``'00:11:22:33:AA:BB'``). This should only be provided in cases where the default (host MAC address incremented by 1) won't work. Returns: ``True`` on successful login, ``False`` on unsuccessful login. """ cls_name = type(self).__name__ oauth_cred = os.path.join(os.path.dirname(OAUTH_FILEPATH), oauth_filename + '.cred') try: if not self.api.login(oauth_credentials=oauth_cred, uploader_id=uploader_id): try:
python
{ "resource": "" }
q262378
MusicManagerWrapper.download
validation
def download(self, songs, template=None): """Download Google Music songs. Parameters: songs (list or dict): Google Music song dict(s). template (str): A filepath which can include template patterns. Returns: A list of result dictionaries. :: [ {'result': 'downloaded', 'id': song_id, 'filepath': downloaded[song_id]}, # downloaded {'result': 'error', 'id': song_id, 'message': error[song_id]} # error ] """ if not template: template = os.getcwd() songnum = 0 total = len(songs) results = [] errors = {} pad = len(str(total)) for result in self._download(songs, template): song_id = songs[songnum]['id'] songnum += 1 downloaded, error = result if downloaded: logger.info( "({num:>{pad}}/{total}) Successfully downloaded -- {file} ({song_id})".format( num=songnum, pad=pad, total=total, file=downloaded[song_id], song_id=song_id ) ) results.append({'result': 'downloaded', 'id': song_id, 'filepath': downloaded[song_id]}) elif error: title = songs[songnum].get('title', "<empty>")
python
{ "resource": "" }
q262379
convert_cygwin_path
validation
def convert_cygwin_path(path): """Convert Unix path from Cygwin to Windows path.""" try: win_path = subprocess.check_output(["cygpath", "-aw", path], universal_newlines=True).strip()
python
{ "resource": "" }
q262380
_get_mutagen_metadata
validation
def _get_mutagen_metadata(filepath): """Get mutagen metadata dict from a file.""" try: metadata = mutagen.File(filepath, easy=True) except mutagen.MutagenError:
python
{ "resource": "" }
q262381
_mutagen_fields_to_single_value
validation
def _mutagen_fields_to_single_value(metadata): """Replace mutagen metadata field list values in mutagen tags with the first list
python
{ "resource": "" }
q262382
_normalize_metadata
validation
def _normalize_metadata(metadata): """Normalize metadata to improve match accuracy.""" metadata = str(metadata) metadata = metadata.lower() metadata = re.sub(r'\/\s*\d+', '', metadata) # Remove "/<totaltracks>" from track number. metadata = re.sub(r'^0+([0-9]+)', r'\1', metadata) # Remove leading zero(s) from track number. metadata = re.sub(r'^\d+\.+', '', metadata) # Remove dots from track number. metadata = re.sub(r'[^\w\s]', '', metadata) # Remove any non-words. metadata = re.sub(r'\s+', ' ', metadata) # Reduce
python
{ "resource": "" }
q262383
compare_song_collections
validation
def compare_song_collections(src_songs, dst_songs): """Compare two song collections to find missing songs. Parameters: src_songs (list): Google Music song dicts or filepaths of local songs. dest_songs (list): Google Music song dicts or filepaths of local songs. Returns: A list of Google Music song dicts or local song filepaths from source missing in destination. """ def
python
{ "resource": "" }
q262384
get_supported_filepaths
validation
def get_supported_filepaths(filepaths, supported_extensions, max_depth=float('inf')): """Get filepaths with supported extensions from given filepaths. Parameters: filepaths (list or str): Filepath(s) to check. supported_extensions (tuple or str): Supported file extensions or a single file extension. max_depth (int): The depth in the directory tree to walk. A depth of '0' limits the walk to the top directory. Default: No limit. Returns: A list of supported filepaths. """ supported_filepaths = [] for path in filepaths:
python
{ "resource": "" }
q262385
exclude_filepaths
validation
def exclude_filepaths(filepaths, exclude_patterns=None): """Exclude file paths based on regex patterns. Parameters: filepaths (list or str): Filepath(s) to check. exclude_patterns (list): Python regex patterns to check filepaths against. Returns: A list of filepaths to include and
python
{ "resource": "" }
q262386
_check_field_value
validation
def _check_field_value(field_value, pattern): """Check a song metadata field value for a pattern.""" if isinstance(field_value,
python
{ "resource": "" }
q262387
_check_filters
validation
def _check_filters(song, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False): """Check a song metadata dict against a set of metadata filters.""" include = True if include_filters: if all_includes: if not all(field in song and _check_field_value(song[field], pattern) for field, pattern in include_filters): include = False else: if not any(field in song and _check_field_value(song[field], pattern) for field, pattern in include_filters): include = False if
python
{ "resource": "" }
q262388
filter_google_songs
validation
def filter_google_songs(songs, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False): """Match a Google Music song dict against a set of metadata filters. Parameters: songs (list): Google Music song dicts to filter. include_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid Google Music metadata field available to the Musicmanager client. Patterns are Python regex patterns. Google Music songs are filtered out if the given metadata field values don't match any of the given patterns. exclude_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid Google Music metadata field available to the Musicmanager client. Patterns are Python regex patterns. Google Music songs are filtered out if the given metadata field values match any of the given patterns. all_includes (bool): If ``True``, all include_filters criteria must match to include a song. all_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song. Returns:
python
{ "resource": "" }
q262389
filter_local_songs
validation
def filter_local_songs(filepaths, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False): """Match a local file against a set of metadata filters. Parameters: filepaths (list): Filepaths to filter. include_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid mutagen metadata fields. Patterns are Python regex patterns. Local songs are filtered out if the given metadata field values don't match any of the given patterns. exclude_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid mutagen metadata fields. Patterns are Python regex patterns. Local songs are filtered out if the given metadata field values match any of the given patterns. all_includes (bool): If ``True``, all include_filters criteria must match to include a song. all_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song. Returns: A list of local song filepaths matching criteria and a list of local song filepaths filtered out using filter criteria. Invalid music files
python
{ "resource": "" }
q262390
get_suggested_filename
validation
def get_suggested_filename(metadata): """Generate a filename for a song based on metadata. Parameters: metadata (dict): A metadata dict. Returns: A filename. """ if metadata.get('title') and metadata.get('track_number'): suggested_filename = '{track_number:0>2} {title}'.format(**metadata)
python
{ "resource": "" }
q262391
template_to_filepath
validation
def template_to_filepath(template, metadata, template_patterns=None): """Create directory structure and file name based on metadata template. Parameters: template (str): A filepath which can include template patterns as defined by :param template_patterns:. metadata (dict): A metadata dict. template_patterns (dict): A dict of ``pattern: field`` pairs used to replace patterns with metadata field values. Default: :const TEMPLATE_PATTERNS: Returns: A filepath. """ if template_patterns is None: template_patterns = TEMPLATE_PATTERNS metadata = metadata if isinstance(metadata, dict) else
python
{ "resource": "" }
q262392
walk_depth
validation
def walk_depth(path, max_depth=float('inf')): """Walk a directory tree with configurable depth. Parameters: path (str): A directory path to walk. max_depth (int): The depth in the directory tree to walk. A depth of '0' limits the walk to the top directory. Default:
python
{ "resource": "" }
q262393
_BaseWrapper.get_local_songs
validation
def get_local_songs( filepaths, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False, exclude_patterns=None, max_depth=float('inf')): """Load songs from local filepaths. Parameters: filepaths (list or str): Filepath(s) to search for music files. include_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid mutagen metadata fields. Patterns are Python regex patterns. Local songs are filtered out if the given metadata field values don't match any of the given patterns. exclude_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid mutagen metadata fields. Patterns are Python regex patterns. Local songs are filtered out if the given metadata field values match any of the given patterns. all_includes (bool): If ``True``, all include_filters criteria must match to include a song. all_excludes (bool): If ``True``,
python
{ "resource": "" }
q262394
_BaseWrapper.get_local_playlists
validation
def get_local_playlists(filepaths, exclude_patterns=None, max_depth=float('inf')): """Load playlists from local filepaths. Parameters: filepaths (list or str): Filepath(s) to search for music files. exclude_patterns (list or str): Pattern(s) to exclude. Patterns are Python regex patterns. Filepaths are excluded if they match any of the exclude patterns. max_depth (int): The depth in the directory tree to walk. A depth of '0' limits the walk to the top directory.
python
{ "resource": "" }
q262395
_BaseWrapper.get_local_playlist_songs
validation
def get_local_playlist_songs( playlist, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False, exclude_patterns=None): """Load songs from local playlist. Parameters: playlist (str): An M3U(8) playlist filepath. include_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid mutagen metadata fields. Patterns are Python regex patterns. Local songs are filtered out if the given metadata field values don't match any of the given patterns. exclude_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid mutagen metadata fields. Patterns are Python regex patterns. Local songs are filtered out if the given metadata field values match any of the given patterns. all_includes (bool): If ``True``, all include_filters criteria must match to include a song. all_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song. exclude_patterns (list or str): Pattern(s) to exclude. Patterns are Python regex patterns. Filepaths are excluded if they match any of the exclude patterns. Returns: A list of local playlist song filepaths matching criteria, a list of local playlist song filepaths filtered out using filter criteria, and a list of local playlist song filepaths excluded using exclusion criteria. """ logger.info("Loading local playlist songs...") if os.name == 'nt' and CYGPATH_RE.match(playlist): playlist = convert_cygwin_path(playlist) filepaths = [] base_filepath = os.path.dirname(os.path.abspath(playlist)) with open(playlist) as local_playlist: for line in local_playlist.readlines(): line = line.strip() if line.lower().endswith(SUPPORTED_SONG_FORMATS): path = line if not os.path.isabs(path):
python
{ "resource": "" }
q262396
Material._create_element_list_
validation
def _create_element_list_(self): """ Extract an alphabetically sorted list of elements from the compounds of
python
{ "resource": "" }
q262397
MaterialPackage.get_assay
validation
def get_assay(self): """ Determine the assay of self. :returns: [mass fractions] An array containing the assay of self. """
python
{ "resource": "" }
q262398
MaterialPackage.get_element_masses
validation
def get_element_masses(self): """ Get the masses of elements in the package. :returns: [kg] An array of element masses. The sequence of the elements in the result corresponds with the sequence of elements in the
python
{ "resource": "" }
q262399
MaterialPackage.add_to
validation
def add_to(self, other): """ Add another chem material package to this material package. :param other: The other material package. """ # Add another package. if type(other) is MaterialPackage: # Packages of the same material. if self.material == other.material: self.compound_masses += other.compound_masses # Packages of different materials. else: for compound in other.material.compounds: if compound not in self.material.compounds: raise Exception("Packages of '" + other.material.name +
python
{ "resource": "" }