idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
21,700 | def split ( self ) : key = '%s/split' % self . key return self . _server . query ( key , method = self . _server . _session . put ) | Split a duplicate . |
21,701 | def unmatch ( self ) : key = '%s/unmatch' % self . key return self . _server . query ( key , method = self . _server . _session . put ) | Unmatch a media file . |
21,702 | def download ( self , savepath = None , keep_original_name = False , ** kwargs ) : filepaths = [ ] locations = [ i for i in self . iterParts ( ) if i ] for location in locations : filename = location . file if keep_original_name is False : filename = '%s.%s' % ( self . _prettyfilename ( ) , location . container ) if kwargs : download_url = self . getStreamURL ( ** kwargs ) else : download_url = self . _server . url ( '%s?download=1' % location . key ) filepath = utils . download ( download_url , self . _server . _token , filename = filename , savepath = savepath , session = self . _server . _session ) if filepath : filepaths . append ( filepath ) return filepaths | Downloads this items media to the specified location . Returns a list of filepaths that have been saved to disk . |
21,703 | def stop ( self , reason = '' ) : key = '/status/sessions/terminate?sessionId=%s&reason=%s' % ( self . session [ 0 ] . id , quote_plus ( reason ) ) return self . _server . query ( key ) | Stop playback for a media item . |
21,704 | def updateProgress ( self , time , state = 'stopped' ) : key = '/:/progress?key=%s&identifier=com.plexapp.plugins.library&time=%d&state=%s' % ( self . ratingKey , time , state ) self . _server . query ( key ) self . reload ( ) | Set the watched progress for this video . |
21,705 | def updateTimeline ( self , time , state = 'stopped' , duration = None ) : durationStr = '&duration=' if duration is not None : durationStr = durationStr + str ( duration ) else : durationStr = durationStr + str ( self . duration ) key = '/:/timeline?ratingKey=%s&key=%s&identifier=com.plexapp.plugins.library&time=%d&state=%s%s' key %= ( self . ratingKey , self . key , time , state , durationStr ) self . _server . query ( key ) self . reload ( ) | Set the timeline progress for this video . |
21,706 | def all ( self , ** kwargs ) : items = [ ] for section in self . sections ( ) : for item in section . all ( ** kwargs ) : items . append ( item ) return items | Returns a list of all media from all library sections . This may be a very large dataset to retrieve . |
21,707 | def search ( self , title = None , libtype = None , ** kwargs ) : args = { } if title : args [ 'title' ] = title if libtype : args [ 'type' ] = utils . searchType ( libtype ) for attr , value in kwargs . items ( ) : args [ attr ] = value key = '/library/all%s' % utils . joinArgs ( args ) return self . fetchItems ( key ) | Searching within a library section is much more powerful . It seems certain attributes on the media objects can be targeted to filter this search down a bit but I havent found the documentation for it . |
21,708 | def add ( self , name = '' , type = '' , agent = '' , scanner = '' , location = '' , language = 'en' , * args , ** kwargs ) : part = '/library/sections?name=%s&type=%s&agent=%s&scanner=%s&language=%s&location=%s' % ( quote_plus ( name ) , type , agent , quote_plus ( scanner ) , language , quote_plus ( location ) ) if kwargs : part += urlencode ( kwargs ) return self . _server . query ( part , method = self . _server . _session . post ) | Simplified add for the most common options . |
21,709 | def delete ( self ) : try : return self . _server . query ( '/library/sections/%s' % self . key , method = self . _server . _session . delete ) except BadRequest : msg = 'Failed to delete library %s' % self . key msg += 'You may need to allow this permission in your Plex settings.' log . error ( msg ) raise | Delete a library section . |
21,710 | def get ( self , title ) : key = '/library/sections/%s/all' % self . key return self . fetchItem ( key , title__iexact = title ) | Returns the media item with the specified title . |
21,711 | def all ( self , sort = None , ** kwargs ) : sortStr = '' if sort is not None : sortStr = '?sort=' + sort key = '/library/sections/%s/all%s' % ( self . key , sortStr ) return self . fetchItems ( key , ** kwargs ) | Returns a list of media from this library section . |
21,712 | def emptyTrash ( self ) : key = '/library/sections/%s/emptyTrash' % self . key self . _server . query ( key , method = self . _server . _session . put ) | If a section has items in the Trash use this option to empty the Trash . |
21,713 | def cancelUpdate ( self ) : key = '/library/sections/%s/refresh' % self . key self . _server . query ( key , method = self . _server . _session . delete ) | Cancel update of this Library Section . |
21,714 | def deleteMediaPreviews ( self ) : key = '/library/sections/%s/indexes' % self . key self . _server . query ( key , method = self . _server . _session . delete ) | Delete the preview thumbnails for items in this library . This cannot be undone . Recreating media preview files can take hours or even days . |
21,715 | def recentlyAdded ( self , libtype = 'episode' , maxresults = 50 ) : return self . search ( sort = 'addedAt:desc' , libtype = libtype , maxresults = maxresults ) | Returns a list of recently added episodes from this library section . |
21,716 | def inviteFriend ( self , user , server , sections = None , allowSync = False , allowCameraUpload = False , allowChannels = False , filterMovies = None , filterTelevision = None , filterMusic = None ) : 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' : { 'library_section_ids' : sectionIds , 'invited_email' : username } , 'sharing_settings' : { 'allowSync' : ( '1' if allowSync else '0' ) , 'allowCameraUpload' : ( '1' if allowCameraUpload else '0' ) , 'allowChannels' : ( '1' if allowChannels else '0' ) , 'filterMovies' : self . _filterDictToStr ( filterMovies or { } ) , 'filterTelevision' : self . _filterDictToStr ( filterTelevision or { } ) , 'filterMusic' : self . _filterDictToStr ( filterMusic or { } ) , } , } headers = { 'Content-Type' : 'application/json' } url = self . FRIENDINVITE . format ( machineId = machineId ) return self . query ( url , self . _session . post , json = params , headers = headers ) | Share library content with the specified user . |
21,717 | def removeFriend ( self , user ) : 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 ) | Remove the specified user from all sharing . |
21,718 | def updateFriend ( self , user , server , sections = None , removeSections = False , allowSync = None , allowCameraUpload = None , allowChannels = None , filterMovies = None , filterTelevision = None , filterMusic = None ) : 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 , sections ) headers = { 'Content-Type' : 'application/json' } user_servers = [ s for s in user . servers if s . machineIdentifier == machineId ] if user_servers and sectionIds : serverId = user_servers [ 0 ] . id params = { 'server_id' : machineId , 'shared_server' : { 'library_section_ids' : sectionIds } } url = self . FRIENDSERVERS . format ( machineId = machineId , serverId = serverId ) else : params = { 'server_id' : machineId , 'shared_server' : { 'library_section_ids' : sectionIds , "invited_id" : user . id } } url = self . FRIENDINVITE . format ( machineId = machineId ) if not user_servers or sectionIds : if removeSections is True : response_servers = self . query ( url , self . _session . delete , json = params , headers = headers ) elif 'invited_id' in params . get ( 'shared_server' , '' ) : response_servers = self . query ( url , self . _session . post , json = params , headers = headers ) else : response_servers = self . query ( url , self . _session . put , json = params , headers = headers ) else : log . warning ( 'Section name, number of section object is required changing library sections' ) url = self . FRIENDUPDATE . format ( userId = user . id ) params = { } if isinstance ( allowSync , bool ) : params [ 'allowSync' ] = '1' if allowSync else '0' if isinstance ( allowCameraUpload , bool ) : params [ 'allowCameraUpload' ] = '1' if allowCameraUpload else '0' if isinstance ( allowChannels , bool ) : params [ 'allowChannels' ] = '1' if allowChannels else '0' if isinstance ( filterMovies , dict ) : params [ 'filterMovies' ] = self . _filterDictToStr ( filterMovies or { } ) if isinstance ( filterTelevision , dict ) : params [ 'filterTelevision' ] = self . _filterDictToStr ( filterTelevision or { } ) if isinstance ( allowChannels , dict ) : params [ 'filterMusic' ] = self . _filterDictToStr ( filterMusic or { } ) if params : url += joinArgs ( params ) response_filters = self . query ( url , self . _session . put ) return response_servers , response_filters | Update the specified user s share settings . |
21,719 | def _getSectionIds ( self , server , sections ) : if not sections : return [ ] allSectionIds = { } machineIdentifier = server . machineIdentifier if isinstance ( server , PlexServer ) else server url = self . PLEXSERVERS . replace ( '{machineId}' , machineIdentifier ) data = self . query ( url , self . _session . get ) for elem in data [ 0 ] : allSectionIds [ elem . attrib . get ( 'id' , '' ) . lower ( ) ] = elem . attrib . get ( 'id' ) allSectionIds [ elem . attrib . get ( 'title' , '' ) . lower ( ) ] = elem . attrib . get ( 'id' ) allSectionIds [ elem . attrib . get ( 'key' , '' ) . lower ( ) ] = elem . attrib . get ( 'id' ) log . debug ( allSectionIds ) sectionIds = [ ] for section in sections : sectionKey = section . key if isinstance ( section , LibrarySection ) else section sectionIds . append ( allSectionIds [ sectionKey . lower ( ) ] ) return sectionIds | Converts a list of section objects or names to sectionIds needed for library sharing . |
21,720 | def _filterDictToStr ( self , filterDict ) : 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 ) | Converts friend filters to a string representation for transport . |
21,721 | def delete ( self ) : key = 'https://plex.tv/devices/%s.xml' % self . id self . _server . query ( key , self . _server . _session . delete ) | Remove this device from your account . |
21,722 | def thumbUrl ( self ) : key = self . firstAttr ( 'thumb' , 'parentThumb' , 'granparentThumb' ) return self . _server . url ( key , includeToken = True ) if key else None | Return url to for the thumbnail image . |
21,723 | def keep_episodes ( show , keep ) : 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 | Delete all but last count episodes in show . |
21,724 | def keep_season ( show , keep ) : 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 | Keep only the latest season . |
21,725 | def _create_sg_attachment ( self , django_attch ) : 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 ) , value ) sg_attch = Attachment ( ) if isinstance ( django_attch , MIMEBase ) : filename = django_attch . get_filename ( ) if not filename : ext = mimetypes . guess_extension ( django_attch . get_content_type ( ) ) filename = "part-{0}{1}" . format ( uuid . uuid4 ( ) . hex , ext ) set_prop ( sg_attch , "filename" , filename ) set_prop ( sg_attch , "content" , django_attch . get_payload ( ) . replace ( "\n" , "" ) ) set_prop ( sg_attch , "type" , django_attch . get_content_type ( ) ) content_id = django_attch . get ( "Content-ID" ) if content_id : if content_id . startswith ( "<" ) and content_id . endswith ( ">" ) : content_id = content_id [ 1 : - 1 ] sg_attch . content_id = content_id sg_attch . disposition = "inline" else : filename , content , mimetype = django_attch set_prop ( sg_attch , "filename" , filename ) if isinstance ( content , str ) : content = content . encode ( 'utf-8' ) set_prop ( sg_attch , "content" , base64 . b64encode ( content ) . decode ( ) ) set_prop ( sg_attch , "type" , mimetype ) return sg_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 . |
21,726 | def validate ( path , regex = None ) : 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 , validated , regex . pattern ) ) validated . append ( strkey ) | 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 . |
21,727 | def paths ( obj , dirs = True , leaves = True , path = [ ] , skip = False ) : if isinstance ( obj , MutableMapping ) : if PY3 : iteritems = obj . items ( ) string_class = str else : iteritems = obj . iteritems ( ) string_class = basestring for ( k , v ) in iteritems : if issubclass ( k . __class__ , ( string_class ) ) : if ( not k ) and ( not dpath . options . ALLOW_EMPTY_STRING_KEYS ) : raise dpath . exceptions . InvalidKeyName ( "Empty string keys not allowed without " "dpath.options.ALLOW_EMPTY_STRING_KEYS=True" ) elif ( skip and k [ 0 ] == '+' ) : continue newpath = path + [ [ k , v . __class__ ] ] validate ( newpath ) if dirs : yield newpath for child in paths ( v , dirs , leaves , newpath , skip ) : yield child elif isinstance ( obj , MutableSequence ) : for ( i , v ) in enumerate ( obj ) : newpath = path + [ [ i , v . __class__ ] ] if dirs : yield newpath for child in paths ( obj [ i ] , dirs , leaves , newpath , skip ) : yield child elif leaves : yield path + [ [ obj , obj . __class__ ] ] elif not dirs : yield path | Yield all paths of the object . |
21,728 | def match ( path , glob ) : 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 : more_stars = [ '*' ] * ( path_len - glob_len + 1 ) ss_glob = glob [ : ss ] + more_stars + glob [ ss + 1 : ] elif path_len == glob_len - 1 : ss_glob = glob [ : ss ] + glob [ ss + 1 : ] if path_len == len ( ss_glob ) : if PY3 : return all ( map ( fnmatch . fnmatch , list ( map ( str , paths_only ( path ) ) ) , list ( map ( str , ss_glob ) ) ) ) else : return all ( map ( fnmatch . fnmatch , map ( str , paths_only ( path ) ) , map ( str , ss_glob ) ) ) return False | Match the path with the glob . |
21,729 | def set ( obj , path , value , create_missing = True , afilter = None ) : 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 ) : idx = int ( str ( elem [ 0 ] ) ) while ( len ( obj ) - 1 ) < idx : obj . append ( None ) def _accessor_dict ( obj , elem ) : return obj [ elem [ 0 ] ] def _accessor_list ( obj , elem ) : return obj [ int ( str ( elem [ 0 ] ) ) ] def _assigner_dict ( obj , elem , value ) : obj [ elem [ 0 ] ] = value def _assigner_list ( obj , elem , value ) : obj [ int ( str ( elem [ 0 ] ) ) ] = value elem = None for elem in path : elem_value = elem [ 0 ] elem_type = elem [ 1 ] tester = None creator = None accessor = None assigner = None if issubclass ( obj . __class__ , ( MutableMapping ) ) : tester = _presence_test_dict creator = _create_missing_dict accessor = _accessor_dict assigner = _assigner_dict elif issubclass ( obj . __class__ , MutableSequence ) : if not str ( elem_value ) . isdigit ( ) : raise TypeError ( "Can only create integer indexes in lists, " "not {}, in {}" . format ( type ( obj ) , traversed ) ) tester = _presence_test_list creator = _create_missing_list accessor = _accessor_list assigner = _assigner_list else : raise TypeError ( "Unable to path into elements of type {} " "at {}" . format ( obj , traversed ) ) if ( not tester ( obj , elem ) ) and ( create_missing ) : creator ( obj , elem ) elif ( not tester ( obj , elem ) ) : raise dpath . exceptions . PathNotFound ( "{} does not exist in {}" . format ( elem , traversed ) ) traversed . append ( elem_value ) if len ( traversed ) < len ( path ) : obj = accessor ( obj , elem ) if elem is None : return if ( afilter and afilter ( accessor ( obj , elem ) ) ) or ( not afilter ) : assigner ( obj , elem , value ) | 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 . |
21,730 | def get ( obj , path , view = False , afilter = None ) : 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 , MutableMapping ) ) and index != path_count : tail [ key ] = pair [ 1 ] ( ) else : tail [ key ] = target up = tail tail = tail [ key ] elif issubclass ( tail . __class__ , MutableSequence ) : if issubclass ( pair [ 1 ] , ( MutableSequence , MutableMapping ) ) and index != path_count : tail . append ( pair [ 1 ] ( ) ) else : tail . append ( target ) up = tail tail = tail [ - 1 ] if not issubclass ( target . __class__ , ( MutableSequence , MutableMapping ) ) : if ( afilter and ( not afilter ( target ) ) ) : raise dpath . exceptions . FilteredValue index += 1 if view : return head else : return target | Get the value of the given path . |
21,731 | def delete ( obj , glob , separator = "/" , afilter = None ) : deleted = 0 paths = [ ] globlist = __safe_path__ ( glob , separator ) for path in _inner_search ( obj , globlist , separator ) : paths . append ( path ) for path in paths : cur = obj prev = None for item in path : prev = cur try : cur = cur [ item [ 0 ] ] except AttributeError as e : pass if ( not afilter ) or ( afilter and afilter ( prev [ item [ 0 ] ] ) ) : prev . pop ( item [ 0 ] ) deleted += 1 if not deleted : raise dpath . exceptions . PathNotFound ( "Could not find {0} to delete it" . format ( glob ) ) return deleted | Given a path glob delete all elements that match the glob . |
21,732 | def set ( obj , glob , value , separator = "/" , afilter = None ) : 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 | Given a path glob set all existing elements in the document to the given value . Returns the number of elements changed . |
21,733 | def get ( obj , glob , separator = "/" ) : 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 ( glob ) return ret | Given an object which contains only one possible match for the given glob return the value for the leaf matching the given glob . |
21,734 | def search ( obj , glob , yielded = False , separator = "/" , afilter = None , dirs = True ) : 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 ( view , val ) except dpath . exceptions . FilteredValue : pass return view def _search_yielded ( obj , glob , separator , afilter , dirs ) : globlist = __safe_path__ ( glob , separator ) for path in _inner_search ( obj , globlist , separator , dirs = dirs ) : try : val = dpath . path . get ( obj , path , view = False , afilter = afilter ) yield ( separator . join ( map ( str , dpath . path . paths_only ( path ) ) ) , val ) except dpath . exceptions . FilteredValue : pass if afilter is not None : dirs = False if yielded : return _search_yielded ( obj , glob , separator , afilter , dirs ) return _search_view ( obj , glob , separator , afilter , dirs ) | Given a path glob return a dictionary containing all keys that matched the given glob . |
21,735 | def _inner_search ( obj , glob , separator , dirs = True , leaves = False ) : for path in dpath . path . paths ( obj , dirs , leaves , skip = True ) : if dpath . path . match ( path , glob ) : yield path | Search the object paths that match the glob . |
21,736 | def decode ( code , encoding_type = 'default' ) : 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' : letters = 0 words = 0 index = { } for i in range ( len ( code ) ) : if code [ i : i + 3 ] == ' ' * 3 : if code [ i : i + 7 ] == ' ' * 7 : words += 1 letters += 1 index [ words ] = letters elif code [ i + 4 ] and code [ i - 1 ] != ' ' : letters += 1 message = [ reversed_morsetab [ i ] for i in code . split ( ) ] for i , ( word , letter ) in enumerate ( list ( index . items ( ) ) ) : message . insert ( letter + i , ' ' ) return '' . join ( message ) elif encoding_type == 'binary' : lst = list ( map ( lambda word : word . split ( '0' * 3 ) , code . split ( '0' * 7 ) ) ) for i , word in enumerate ( lst ) : for j , bin_letter in enumerate ( word ) : lst [ i ] [ j ] = binary_lookup [ bin_letter ] lst [ i ] = "" . join ( lst [ i ] ) s = " " . join ( lst ) return s else : raise NotImplementedError ( "encoding_type must be in %s" % allowed_encoding_type ) | Converts a string of morse code into English message |
21,737 | def compute_samples ( channels , nsamples = None ) : return islice ( izip ( * ( imap ( sum , izip ( * channel ) ) for channel in channels ) ) , nsamples ) | 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 . |
21,738 | def write_wavefile ( f , samples , nframes = None , nchannels = 2 , sampwidth = 2 , framerate = 44100 , bufsize = 2048 ) : "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 ) for chunk in grouper ( bufsize , samples ) : frames = b'' . join ( b'' . join ( struct . pack ( 'h' , int ( max_amplitude * sample ) ) for sample in channels ) for channels in chunk if channels is not None ) w . writeframesraw ( frames ) w . close ( ) | Write samples to a wavefile . |
21,739 | def sine_wave ( i , frequency = FREQUENCY , framerate = FRAMERATE , amplitude = AMPLITUDE ) : omega = 2.0 * pi * float ( frequency ) sine = sin ( omega * ( float ( i ) / float ( framerate ) ) ) return float ( amplitude ) * sine | Returns value of a sine wave at a given frequency and framerate for a given sample i |
21,740 | def generate_wave ( message , wpm = WPM , framerate = FRAMERATE , skip_frame = 0 , amplitude = AMPLITUDE , frequency = FREQUENCY , word_ref = WORD ) : 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 ) for i in count ( skip_frame ) : 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 ) yield sine * bit | Generate binary Morse code of message at a given code speed wpm and framerate |
21,741 | def encode ( message , encoding_type = 'default' , letter_sep = ' ' * 3 , strip = True ) : if strip : message = message . strip ( ) 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' : return _encode_to_binary_string ( message , on = '1' , off = '0' ) else : raise NotImplementedError ( "encoding_type must be in %s" % allowed_encoding_type ) | Converts a string of message into morse |
21,742 | def plot ( message , duration = 1 , ax = None ) : 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 ) return ax | Plot a message |
21,743 | def _repeat_word ( word , N , word_space = " " ) : message = ( word_space + word ) * N message = message [ len ( word_space ) : ] return message | Return a repeated string |
21,744 | def mlength ( message , N = 1 , word_spaced = True ) : 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 return N | Returns Morse length |
21,745 | def _timing_representation ( message ) : 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 | Returns timing representation of a message like |
21,746 | def display ( message , wpm , element_duration , word_ref , strip = False ) : 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 = strip ) ) ) print ( "" ) print ( "{0:>8s}:" . format ( "timing" ) ) print ( _timing_representation ( message ) ) print ( "" ) print ( "{0:>8s}:" . format ( "spoken reprentation" ) ) print ( _spoken_representation ( message ) ) print ( "" ) print ( "code speed : %s wpm" % wpm ) print ( "element_duration : %s s" % element_duration ) print ( "reference word : %r" % word_ref ) print ( "" ) | Display text message morse code binary morse code |
21,747 | def lookup ( self , label ) : if self . is_child : try : return self . _children [ label ] except KeyError : self . _children [ label ] = ChildFieldPicklist ( self . parent , label , self . field_name ) return self . _children [ label ] else : return get_label_value ( label , self . _picklist ) | take a field_name_label and return the id |
21,748 | def reverse_lookup ( self , value , condition = is_active ) : label = get_value_label ( value , self . _picklist , condition = condition ) return label | take a field_name_id and return the label |
21,749 | def build_item ( title , key = None , synonyms = None , description = None , img_url = None , alt_text = None ) : 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 | Builds an item that may be added to List or Carousel |
21,750 | def suggest ( self , * replies ) : chips = [ ] for r in replies : chips . append ( { "title" : r } ) self . _messages . append ( { "platform" : "ACTIONS_ON_GOOGLE" , "suggestions" : { "suggestions" : chips } } ) return self | Use suggestion chips to hint at responses to continue or pivot the conversation |
21,751 | def link_out ( self , name , url ) : self . _messages . append ( { "platform" : "ACTIONS_ON_GOOGLE" , "linkOutSuggestion" : { "destinationName" : name , "uri" : url } , } ) return self | Presents a chip similar to suggestion but instead links to a url |
21,752 | def build_list ( self , title = None , items = None ) : list_card = _ListSelector ( self . _speech , display_text = self . _display_text , title = title , items = items ) return list_card | Presents the user with a vertical list of multiple items . |
21,753 | def add_item ( self , title , key , synonyms = None , description = None , img_url = None ) : item = build_item ( title , key , synonyms , description , img_url ) self . _items . append ( item ) return self | Adds item to a list or carousel card . |
21,754 | def get_intent ( self , intent_id ) : endpoint = self . _intent_uri ( intent_id = intent_id ) return self . _get ( endpoint ) | Returns the intent object with the given intent_id |
21,755 | def post_intent ( self , intent_json ) : endpoint = self . _intent_uri ( ) return self . _post ( endpoint , data = intent_json ) | Sends post request to create a new intent |
21,756 | def put_intent ( self , intent_id , intent_json ) : endpoint = self . _intent_uri ( intent_id ) return self . _put ( endpoint , intent_json ) | Send a put request to update the intent with intent_id |
21,757 | def find_assistant ( ) : if hasattr ( current_app , "assist" ) : return getattr ( current_app , "assist" ) else : if hasattr ( current_app , "blueprints" ) : blueprints = getattr ( current_app , "blueprints" ) for blueprint_name in blueprints : if hasattr ( blueprints [ blueprint_name ] , "assist" ) : return getattr ( blueprints [ blueprint_name ] , "assist" ) | Find our instance of Assistant navigating Local s and possible blueprints . |
21,758 | def action ( self , intent_name , is_fallback = False , mapping = { } , convert = { } , default = { } , with_context = [ ] , events = [ ] , * args , ** kw ) : def decorator ( f ) : action_funcs = self . _intent_action_funcs . get ( intent_name , [ ] ) action_funcs . append ( f ) self . _intent_action_funcs [ intent_name ] = action_funcs self . _intent_mappings [ intent_name ] = mapping self . _intent_converts [ intent_name ] = convert self . _intent_defaults [ intent_name ] = default self . _intent_fallbacks [ intent_name ] = is_fallback self . _intent_events [ intent_name ] = events self . _register_context_to_func ( intent_name , with_context ) @ wraps ( f ) def wrapper ( * args , ** kw ) : self . _flask_assitant_view_func ( * args , ** kw ) return f return decorator | Decorates an intent_name s Action view function . |
21,759 | def prompt_for ( self , next_param , intent_name ) : def decorator ( f ) : prompts = self . _intent_prompts . get ( intent_name ) if prompts : prompts [ next_param ] = f else : self . _intent_prompts [ intent_name ] = { } self . _intent_prompts [ intent_name ] [ next_param ] = f @ wraps ( f ) def wrapper ( * args , ** kw ) : self . _flask_assitant_view_func ( * args , ** kw ) return f return decorator | Decorates a function to prompt for an action s required parameter . |
21,760 | def _context_views ( self ) : possible_views = [ ] for func in self . _func_contexts : if self . _context_satified ( func ) : logger . debug ( "{} context conditions satisified" . format ( func . __name__ ) ) possible_views . append ( func ) return possible_views | Returns view functions for which the context requirements are met |
21,761 | def get_assistant ( filename ) : agent_name = os . path . splitext ( filename ) [ 0 ] try : agent_module = import_with_3 ( agent_name , os . path . join ( os . getcwd ( ) , filename ) ) except ImportError : agent_module = import_with_2 ( agent_name , os . path . join ( os . getcwd ( ) , filename ) ) for name , obj in agent_module . __dict__ . items ( ) : if isinstance ( obj , Assistant ) : return obj | Imports a module from filename as a string returns the contained Assistant object |
21,762 | def _annotate_params ( self , word ) : annotation = { } annotation [ 'text' ] = word annotation [ 'meta' ] = '@' + self . entity_map [ word ] annotation [ 'alias' ] = self . entity_map [ word ] . replace ( 'sys.' , '' ) annotation [ 'userDefined' ] = True self . data . append ( annotation ) | Annotates a given word for the UserSays data field of an Intent object . |
21,763 | def app_intents ( self ) : from_app = [ ] for intent_name in self . assist . _intent_action_funcs : intent = self . build_intent ( intent_name ) from_app . append ( intent ) return from_app | Returns a list of Intent objects created from the assistant s acion functions |
21,764 | def build_intent ( self , intent_name ) : is_fallback = self . assist . _intent_fallbacks [ intent_name ] contexts = self . assist . _required_contexts [ intent_name ] events = self . assist . _intent_events [ intent_name ] new_intent = Intent ( intent_name , fallback_intent = is_fallback , contexts = contexts , events = events ) self . build_action ( new_intent ) self . build_user_says ( new_intent ) return new_intent | Builds an Intent object of the given name |
21,765 | def parse_params ( self , intent_name ) : params = [ ] action_func = self . assist . _intent_action_funcs [ intent_name ] [ 0 ] argspec = inspect . getargspec ( action_func ) param_entity_map = self . assist . _intent_mappings . get ( intent_name ) args , defaults = argspec . args , argspec . defaults default_map = { } if defaults : default_map = dict ( zip ( args [ - len ( defaults ) : ] , defaults ) ) for arg in args : param_info = { } param_entity = param_entity_map . get ( arg , arg ) param_name = param_entity . replace ( 'sys.' , '' ) param_info [ 'name' ] = param_name param_info [ 'value' ] = '$' + param_name param_info [ 'dataType' ] = '@' + param_entity param_info [ 'prompts' ] = [ ] param_info [ 'required' ] = arg not in default_map param_info [ 'isList' ] = isinstance ( default_map . get ( arg ) , list ) if param_info [ 'isList' ] : param_info [ 'defaultValue' ] = '' else : param_info [ 'defaultValue' ] = default_map . get ( arg , '' ) params . append ( param_info ) return params | Parses params from an intent s action decorator and view function . |
21,766 | def push_intent ( self , intent ) : if intent . id : print ( 'Updating {} intent' . format ( intent . name ) ) self . update ( intent ) else : print ( 'Registering {} intent' . format ( intent . name ) ) intent = self . register ( intent ) return intent | Registers or updates an intent and returns the intent_json with an ID |
21,767 | def register ( self , intent ) : response = self . api . post_intent ( intent . serialize ) print ( response ) print ( ) if response [ 'status' ] [ 'code' ] == 200 : intent . id = response [ 'id' ] elif response [ 'status' ] [ 'code' ] == 409 : intent . id = next ( i . id for i in self . api . agent_intents if i . name == intent . name ) self . update ( intent ) return intent | Registers a new intent and returns the Intent object with an ID |
21,768 | def register ( self , entity ) : response = self . api . post_entity ( entity . serialize ) print ( response ) print ( ) if response [ 'status' ] [ 'code' ] == 200 : entity . id = response [ 'id' ] if response [ 'status' ] [ 'code' ] == 409 : entity . id = next ( i . id for i in self . api . agent_entities if i . name == entity . name ) self . update ( entity ) return entity | Registers a new entity and returns the entity object with an ID |
21,769 | def push_entity ( self , entity ) : if entity . id : print ( 'Updating {} entity' . format ( entity . name ) ) self . update ( entity ) else : print ( 'Registering {} entity' . format ( entity . name ) ) entity = self . register ( entity ) return entity | Registers or updates an entity and returns the entity_json with an ID |
21,770 | def set_state ( self , entity_id , new_state , ** kwargs ) : "Updates or creates the current state of an entity." return remote . set_state ( self . api , new_state , ** kwargs ) | Updates or creates the current state of an entity . |
21,771 | def is_state ( self , entity_id , state ) : return remote . is_state ( self . api , entity_id , state ) | Checks if the entity has the given state |
21,772 | def etag ( self , etag ) : if not isinstance ( etag , bytes ) : etag = bytes ( etag , "utf-8" ) self . _etag . append ( etag ) | Set the ETag of the resource . |
21,773 | def payload ( self , p ) : if isinstance ( p , tuple ) : k = p [ 0 ] v = p [ 1 ] self . actual_content_type = k self . _payload [ k ] = v else : self . _payload = { defines . Content_types [ "text/plain" ] : p } | Set the payload of the resource . |
21,774 | def content_type ( self ) : value = "" lst = self . _attributes . get ( "ct" ) if lst is not None and len ( lst ) > 0 : value = "ct=" for v in lst : value += str ( v ) + " " if len ( value ) > 0 : value = value [ : - 1 ] return value | Get the CoRE Link Format ct attribute of the resource . |
21,775 | def content_type ( self , lst ) : value = [ ] if isinstance ( lst , str ) : ct = defines . Content_types [ lst ] self . add_content_type ( ct ) elif isinstance ( lst , list ) : for ct in lst : self . add_content_type ( ct ) | Set the CoRE Link Format ct attribute of the resource . |
21,776 | def add_content_type ( self , ct ) : lst = self . _attributes . get ( "ct" ) if lst is None : lst = [ ] if isinstance ( ct , str ) : ct = defines . Content_types [ ct ] lst . append ( ct ) self . _attributes [ "ct" ] = lst | Add a CoRE Link Format ct attribute to the resource . |
21,777 | def resource_type ( self ) : value = "rt=" lst = self . _attributes . get ( "rt" ) if lst is None : value = "" else : value += "\"" + str ( lst ) + "\"" return value | Get the CoRE Link Format rt attribute of the resource . |
21,778 | def resource_type ( self , rt ) : if not isinstance ( rt , str ) : rt = str ( rt ) self . _attributes [ "rt" ] = rt | Set the CoRE Link Format rt attribute of the resource . |
21,779 | def interface_type ( self ) : value = "if=" lst = self . _attributes . get ( "if" ) if lst is None : value = "" else : value += "\"" + str ( lst ) + "\"" return value | Get the CoRE Link Format if attribute of the resource . |
21,780 | def interface_type ( self , ift ) : if not isinstance ( ift , str ) : ift = str ( ift ) self . _attributes [ "if" ] = ift | Set the CoRE Link Format if attribute of the resource . |
21,781 | def maximum_size_estimated ( self ) : value = "sz=" lst = self . _attributes . get ( "sz" ) if lst is None : value = "" else : value += "\"" + str ( lst ) + "\"" return value | Get the CoRE Link Format sz attribute of the resource . |
21,782 | def maximum_size_estimated ( self , sz ) : if not isinstance ( sz , str ) : sz = str ( sz ) self . _attributes [ "sz" ] = sz | Set the CoRE Link Format sz attribute of the resource . |
21,783 | def init_resource ( self , request , res ) : res . location_query = request . uri_query res . payload = ( request . content_type , request . payload ) return res | Helper function to initialize a new resource . |
21,784 | def edit_resource ( self , request ) : self . location_query = request . uri_query self . payload = ( request . content_type , request . payload ) | Helper function to edit a resource |
21,785 | def receive_request ( self , transaction ) : if transaction . request . block2 is not None : host , port = transaction . request . source key_token = hash ( str ( host ) + str ( port ) + str ( transaction . request . token ) ) num , m , size = transaction . request . block2 if key_token in self . _block2_receive : self . _block2_receive [ key_token ] . num = num self . _block2_receive [ key_token ] . size = size self . _block2_receive [ key_token ] . m = m del transaction . request . block2 else : byte = 0 self . _block2_receive [ key_token ] = BlockItem ( byte , num , m , size ) del transaction . request . block2 elif transaction . request . block1 is not None : host , port = transaction . request . source key_token = hash ( str ( host ) + str ( port ) + str ( transaction . request . token ) ) num , m , size = transaction . request . block1 if key_token in self . _block1_receive : content_type = transaction . request . content_type if num != self . _block1_receive [ key_token ] . num or content_type != self . _block1_receive [ key_token ] . content_type : return self . incomplete ( transaction ) self . _block1_receive [ key_token ] . payload += transaction . request . payload else : if num != 0 : return self . incomplete ( transaction ) content_type = transaction . request . content_type self . _block1_receive [ key_token ] = BlockItem ( size , num , m , size , transaction . request . payload , content_type ) if m == 0 : transaction . request . payload = self . _block1_receive [ key_token ] . payload del transaction . request . block1 transaction . block_transfer = False del self . _block1_receive [ key_token ] return transaction else : transaction . block_transfer = True transaction . response = Response ( ) transaction . response . destination = transaction . request . source transaction . response . token = transaction . request . token transaction . response . code = defines . Codes . CONTINUE . number transaction . response . block1 = ( num , m , size ) num += 1 byte = size self . _block1_receive [ key_token ] . byte = byte self . _block1_receive [ key_token ] . num = num self . _block1_receive [ key_token ] . size = size self . _block1_receive [ key_token ] . m = m return transaction | Handles the Blocks option in a incoming request . |
21,786 | def send_response ( self , transaction ) : host , port = transaction . request . source key_token = hash ( str ( host ) + str ( port ) + str ( transaction . request . token ) ) if ( key_token in self . _block2_receive and transaction . response . payload is not None ) or ( transaction . response . payload is not None and len ( transaction . response . payload ) > defines . MAX_PAYLOAD ) : if key_token in self . _block2_receive : byte = self . _block2_receive [ key_token ] . byte size = self . _block2_receive [ key_token ] . size num = self . _block2_receive [ key_token ] . num else : byte = 0 num = 0 size = defines . MAX_PAYLOAD m = 1 self . _block2_receive [ key_token ] = BlockItem ( byte , num , m , size ) if len ( transaction . response . payload ) > ( byte + size ) : m = 1 else : m = 0 transaction . response . payload = transaction . response . payload [ byte : byte + size ] del transaction . response . block2 transaction . response . block2 = ( num , m , size ) self . _block2_receive [ key_token ] . byte += size self . _block2_receive [ key_token ] . num += 1 if m == 0 : del self . _block2_receive [ key_token ] return transaction | Handles the Blocks option in a outgoing response . |
21,787 | def send_request ( self , request ) : assert isinstance ( request , Request ) if request . block1 or ( request . payload is not None and len ( request . payload ) > defines . MAX_PAYLOAD ) : host , port = request . destination key_token = hash ( str ( host ) + str ( port ) + str ( request . token ) ) if request . block1 : num , m , size = request . block1 else : num = 0 m = 1 size = defines . MAX_PAYLOAD self . _block1_sent [ key_token ] = BlockItem ( size , num , m , size , request . payload , request . content_type ) request . payload = request . payload [ 0 : size ] del request . block1 request . block1 = ( num , m , size ) elif request . block2 : host , port = request . destination key_token = hash ( str ( host ) + str ( port ) + str ( request . token ) ) num , m , size = request . block2 item = BlockItem ( size , num , m , size , "" , None ) self . _block2_sent [ key_token ] = item return request return request | Handles the Blocks option in a outgoing request . |
21,788 | def incomplete ( transaction ) : transaction . block_transfer = True transaction . response = Response ( ) transaction . response . destination = transaction . request . source transaction . response . token = transaction . request . token transaction . response . code = defines . Codes . REQUEST_ENTITY_INCOMPLETE . number return transaction | Notifies incomplete blockwise exchange . |
21,789 | def error ( transaction , code ) : transaction . block_transfer = True transaction . response = Response ( ) transaction . response . destination = transaction . request . source transaction . response . type = defines . Types [ "RST" ] transaction . response . token = transaction . request . token transaction . response . code = code return transaction | Notifies generic error on blockwise exchange . |
21,790 | def send_request ( self , request ) : if request . observe == 0 : host , port = request . destination key_token = hash ( str ( host ) + str ( port ) + str ( request . token ) ) self . _relations [ key_token ] = ObserveItem ( time . time ( ) , None , True , None ) return request | Add itself to the observing list |
21,791 | def receive_response ( self , transaction ) : host , port = transaction . response . source key_token = hash ( str ( host ) + str ( port ) + str ( transaction . response . token ) ) if key_token in self . _relations and transaction . response . type == defines . Types [ "CON" ] : transaction . notification = True return transaction | Sets notification s parameters . |
21,792 | def send_empty ( self , message ) : host , port = message . destination key_token = hash ( str ( host ) + str ( port ) + str ( message . token ) ) if key_token in self . _relations and message . type == defines . Types [ "RST" ] : del self . _relations [ key_token ] return message | Eventually remove from the observer list in case of a RST message . |
21,793 | def receive_request ( self , transaction ) : if transaction . request . observe == 0 : host , port = transaction . request . source key_token = hash ( str ( host ) + str ( port ) + str ( transaction . request . token ) ) non_counter = 0 if key_token in self . _relations : allowed = True else : allowed = False self . _relations [ key_token ] = ObserveItem ( time . time ( ) , non_counter , allowed , transaction ) elif transaction . request . observe == 1 : host , port = transaction . request . source key_token = hash ( str ( host ) + str ( port ) + str ( transaction . request . token ) ) logger . info ( "Remove Subscriber" ) try : del self . _relations [ key_token ] except KeyError : pass return transaction | Manage the observe option in the request end eventually initialize the client for adding to the list of observers or remove from the list . |
21,794 | def receive_empty ( self , empty , transaction ) : if empty . type == defines . Types [ "RST" ] : host , port = transaction . request . source key_token = hash ( str ( host ) + str ( port ) + str ( transaction . request . token ) ) logger . info ( "Remove Subscriber" ) try : del self . _relations [ key_token ] except KeyError : pass transaction . completed = True return transaction | Manage the observe feature to remove a client in case of a RST message receveide in reply to a notification . |
21,795 | def send_response ( self , transaction ) : host , port = transaction . request . source key_token = hash ( str ( host ) + str ( port ) + str ( transaction . request . token ) ) if key_token in self . _relations : if transaction . response . code == defines . Codes . CONTENT . number : if transaction . resource is not None and transaction . resource . observable : transaction . response . observe = transaction . resource . observe_count self . _relations [ key_token ] . allowed = True self . _relations [ key_token ] . transaction = transaction self . _relations [ key_token ] . timestamp = time . time ( ) else : del self . _relations [ key_token ] elif transaction . response . code >= defines . Codes . ERROR_LOWER_BOUND : del self . _relations [ key_token ] return transaction | Finalize to add the client to the list of observer . |
21,796 | def notify ( self , resource , root = None ) : ret = [ ] if root is not None : resource_list = root . with_prefix_resource ( resource . path ) else : resource_list = [ resource ] for key in list ( self . _relations . keys ( ) ) : if self . _relations [ key ] . transaction . resource in resource_list : if self . _relations [ key ] . non_counter > defines . MAX_NON_NOTIFICATIONS or self . _relations [ key ] . transaction . request . type == defines . Types [ "CON" ] : self . _relations [ key ] . transaction . response . type = defines . Types [ "CON" ] self . _relations [ key ] . non_counter = 0 elif self . _relations [ key ] . transaction . request . type == defines . Types [ "NON" ] : self . _relations [ key ] . non_counter += 1 self . _relations [ key ] . transaction . response . type = defines . Types [ "NON" ] self . _relations [ key ] . transaction . resource = resource del self . _relations [ key ] . transaction . response . mid del self . _relations [ key ] . transaction . response . token ret . append ( self . _relations [ key ] . transaction ) return ret | Prepare notification for the resource to all interested observers . |
21,797 | def remove_subscriber ( self , message ) : logger . debug ( "Remove Subcriber" ) host , port = message . destination key_token = hash ( str ( host ) + str ( port ) + str ( message . token ) ) try : self . _relations [ key_token ] . transaction . completed = True del self . _relations [ key_token ] except KeyError : logger . warning ( "No Subscriber" ) | Remove a subscriber based on token . |
21,798 | def purge ( self ) : while not self . stopped . isSet ( ) : self . stopped . wait ( timeout = defines . EXCHANGE_LIFETIME ) self . _messageLayer . purge ( ) | Clean old transactions |
21,799 | def send_datagram ( self , message ) : if not self . stopped . isSet ( ) : host , port = message . destination logger . debug ( "send_datagram - " + str ( message ) ) serializer = Serializer ( ) message = serializer . serialize ( message ) self . _socket . sendto ( message , ( host , port ) ) | Send a message through the udp socket . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.