idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
60,800 | def open_list ( ctx , document , par , root , elem ) : _ls = None if par . ilvl != ctx . ilvl or par . numid != ctx . numid : if ctx . ilvl is not None and ( par . ilvl > ctx . ilvl ) : fmt = _get_numbering ( document , par . numid , par . ilvl ) if par . ilvl > 0 : _b = list ( root ) [ - 1 ] _ls = etree . SubElement (... | Open list if it is needed and place current element as first member of a list . |
60,801 | def serialize_break ( ctx , document , elem , root ) : "Serialize break element." if elem . break_type == u'textWrapping' : _div = etree . SubElement ( root , 'br' ) else : _div = etree . SubElement ( root , 'span' ) if ctx . options [ 'embed_styles' ] : _div . set ( 'style' , 'page-break-after: always;' ) fire_hooks (... | Serialize break element . |
60,802 | def serialize_math ( ctx , document , elem , root ) : _div = etree . SubElement ( root , 'span' ) if ctx . options [ 'embed_styles' ] : _div . set ( 'style' , 'border: 1px solid red' ) _div . text = 'We do not support Math blocks at the moment.' fire_hooks ( ctx , document , elem , _div , ctx . get_hook ( 'math' ) ) re... | Serialize math element . |
60,803 | def serialize_link ( ctx , document , elem , root ) : _a = etree . SubElement ( root , 'a' ) for el in elem . elements : _ser = ctx . get_serializer ( el ) if _ser : _td = _ser ( ctx , document , el , _a ) else : if isinstance ( el , doc . Text ) : children = list ( _a ) if len ( children ) == 0 : _text = _a . text or ... | Serilaze link element . |
60,804 | def serialize_image ( ctx , document , elem , root ) : _img = etree . SubElement ( root , 'img' ) if elem . rid in document . relationships [ ctx . options [ 'relationship' ] ] : img_src = document . relationships [ ctx . options [ 'relationship' ] ] [ elem . rid ] . get ( 'target' , '' ) img_name , img_extension = os ... | Serialize image element . |
60,805 | def fire_hooks ( ctx , document , elem , element , hooks ) : if not hooks : return for hook in hooks : hook ( ctx , document , elem , element ) | Fire hooks on newly created element . |
60,806 | def has_style ( node ) : elements = [ 'b' , 'i' , 'u' , 'strike' , 'color' , 'jc' , 'sz' , 'ind' , 'superscript' , 'subscript' , 'small_caps' ] return any ( [ True for elem in elements if elem in node . rpr ] ) | Tells us if node element has defined styling . |
60,807 | def get_style_css ( ctx , node , embed = True , fontsize = - 1 ) : style = [ ] if not node : return if fontsize in [ - 1 , 2 ] : if 'sz' in node . rpr : size = int ( node . rpr [ 'sz' ] ) / 2 if ctx . options [ 'embed_fontsize' ] : if ctx . options [ 'scale_to_size' ] : multiplier = size - ctx . options [ 'scale_to_siz... | Returns as string defined CSS for this node . |
60,808 | def get_all_styles ( document , style ) : classes = [ ] while True : classes . insert ( 0 , get_style_name ( style ) ) if style . based_on : style = document . styles . get_by_id ( style . based_on ) else : break return classes | Returns list of styles on which specified style is based on . |
60,809 | def get_css_classes ( document , style ) : lst = [ st . lower ( ) for st in get_all_styles ( document , style ) [ - 1 : ] ] + [ '{}-fontsize' . format ( st . lower ( ) ) for st in get_all_styles ( document , style ) [ - 1 : ] ] return ' ' . join ( lst ) | Returns CSS classes for this style . |
60,810 | def serialize_symbol ( ctx , document , el , root ) : "Serialize special symbols." span = etree . SubElement ( root , 'span' ) span . text = el . value ( ) fire_hooks ( ctx , document , el , span , ctx . get_hook ( 'symbol' ) ) return root | Serialize special symbols . |
60,811 | def serialize_footnote ( ctx , document , el , root ) : "Serializes footnotes." footnote_num = el . rid if el . rid not in ctx . footnote_list : ctx . footnote_id += 1 ctx . footnote_list [ el . rid ] = ctx . footnote_id footnote_num = ctx . footnote_list [ el . rid ] note = etree . SubElement ( root , 'sup' ) link = e... | Serializes footnotes . |
60,812 | def serialize_comment ( ctx , document , el , root ) : "Serializes comment." if el . comment_type == 'end' : ctx . opened_comments . remove ( el . cid ) else : if el . comment_type != 'reference' : ctx . opened_comments . append ( el . cid ) if ctx . options [ 'comment_span' ] : link = etree . SubElement ( root , 'a' )... | Serializes comment . |
60,813 | def serialize_endnote ( ctx , document , el , root ) : "Serializes endnotes." footnote_num = el . rid if el . rid not in ctx . endnote_list : ctx . endnote_id += 1 ctx . endnote_list [ el . rid ] = ctx . endnote_id footnote_num = ctx . endnote_list [ el . rid ] note = etree . SubElement ( root , 'sup' ) link = etree . ... | Serializes endnotes . |
60,814 | def serialize_smarttag ( ctx , document , el , root ) : "Serializes smarttag." if ctx . options [ 'smarttag_span' ] : _span = etree . SubElement ( root , 'span' , { 'class' : 'smarttag' , 'data-smarttag-element' : el . element } ) else : _span = root for elem in el . elements : _ser = ctx . get_serializer ( elem ) if _... | Serializes smarttag . |
60,815 | def serialize_table ( ctx , document , table , root ) : if root is None : return root if ctx . ilvl != None : root = close_list ( ctx , root ) ctx . ilvl , ctx . numid = None , None _table = etree . SubElement ( root , 'table' ) _table . set ( 'border' , '1' ) _table . set ( 'width' , '100%' ) style = get_style ( docum... | Serializes table element . |
60,816 | def serialize_textbox ( ctx , document , txtbox , root ) : _div = etree . SubElement ( root , 'div' ) _div . set ( 'class' , 'textbox' ) for elem in txtbox . elements : _ser = ctx . get_serializer ( elem ) if _ser : _ser ( ctx , document , elem , _div ) fire_hooks ( ctx , document , txtbox , _div , ctx . get_hook ( 'te... | Serialize textbox element . |
60,817 | def serialize_elements ( document , elements , options = None ) : ctx = Context ( document , options ) tree_root = root = etree . Element ( 'div' ) for elem in elements : _ser = ctx . get_serializer ( elem ) if _ser : root = _ser ( ctx , document , elem , root ) return etree . tostring ( tree_root , pretty_print = ctx ... | Serialize list of elements into HTML string . |
60,818 | def is_header ( self , elem , font_size , node , style = None ) : if hasattr ( style , 'style_id' ) : fnt_size = _get_font_size ( self . doc , style ) from . importer import calculate_weight weight = calculate_weight ( self . doc , elem ) if weight > 50 : return False if fnt_size in self . doc . possible_headers_style ... | Used for checking if specific element is a header or not . |
60,819 | def get_header ( self , elem , style , node ) : font_size = style if hasattr ( elem , 'possible_header' ) : if elem . possible_header : return 'h1' if not style : return 'h6' if hasattr ( style , 'style_id' ) : font_size = _get_font_size ( self . doc , style ) try : if font_size in self . doc . possible_headers_style :... | Returns HTML tag representing specific header for this element . |
60,820 | def get_serializer ( self , node ) : return self . options [ 'serializers' ] . get ( type ( node ) , None ) if type ( node ) in self . options [ 'serializers' ] : return self . options [ 'serializers' ] [ type ( node ) ] return None | Returns serializer for specific element . |
60,821 | def priority ( self , priority ) : with self . __lock : old_priorities = { } try : for thread in self . __threads : old_priorities [ thread ] = thread . priority thread . priority = priority except Exception : for ( thread , old_priority ) in old_priorities . iteritems ( ) : try : thread . priority = old_priority excep... | Set the priority for all threads in this group . |
60,822 | def affinity ( self , affinity ) : with self . __lock : old_affinities = { } try : for thread in self . __threads : old_affinities [ thread ] = thread . affinity thread . affinity = affinity except Exception : for ( thread , old_affinity ) in old_affinities . iteritems ( ) : try : thread . affinity = old_affinity excep... | Set the affinity for all threads in this group . |
60,823 | def join ( self , timeout = None ) : if timeout is None : for thread in self . __threads : thread . join ( ) else : deadline = _time ( ) + timeout for thread in self . __threads : delay = deadline - _time ( ) if delay <= 0 : return False if not thread . join ( delay ) : return False return True | Join all threads in this group . |
60,824 | def text_length ( elem ) : if not elem : return 0 value = elem . value ( ) try : value = len ( value ) except : value = 0 try : for a in elem . elements : value += len ( a . value ( ) ) except : pass return value | Returns length of the content in this element . |
60,825 | def reset ( self ) : "Resets the values." self . zf = zipfile . ZipFile ( self . file_name , 'r' ) self . _doc = None | Resets the values . |
60,826 | def build_rrule ( count = None , interval = None , bysecond = None , byminute = None , byhour = None , byweekno = None , bymonthday = None , byyearday = None , bymonth = None , until = None , bysetpos = None , wkst = None , byday = None , freq = None ) : result = { } if count is not None : result [ 'COUNT' ] = count if... | Build rrule dictionary for vRecur class . |
60,827 | def build_rrule_from_recurrences_rrule ( rule ) : from recurrence import serialize line = serialize ( rule ) if line . startswith ( 'RRULE:' ) : line = line [ 6 : ] return build_rrule_from_text ( line ) | Build rrule dictionary for vRecur class from a django_recurrences rrule . |
60,828 | def build_rrule_from_dateutil_rrule ( rule ) : lines = str ( rule ) . splitlines ( ) for line in lines : if line . startswith ( 'DTSTART:' ) : continue if line . startswith ( 'RRULE:' ) : line = line [ 6 : ] return build_rrule_from_text ( line ) | Build rrule dictionary for vRecur class from a dateutil rrule . |
60,829 | def write ( self , outfile , encoding ) : u cal = Calendar ( ) cal . add ( 'version' , '2.0' ) cal . add ( 'calscale' , 'GREGORIAN' ) for ifield , efield in FEED_FIELD_MAP : val = self . feed . get ( ifield ) if val is not None : cal . add ( efield , val ) self . write_items ( cal ) to_ical = getattr ( cal , 'as_string... | u Writes the feed to the specified file in the specified encoding . |
60,830 | def write_items ( self , calendar ) : for item in self . items : event = Event ( ) for ifield , efield in ITEM_EVENT_FIELD_MAP : val = item . get ( ifield ) if val is not None : event . add ( efield , val ) calendar . add_component ( event ) | Write all events to the calendar |
60,831 | def _textlist ( self , _addtail = False ) : result = [ ] if ( not _addtail ) and ( self . text is not None ) : result . append ( self . text ) for elem in self : result . extend ( elem . textlist ( True ) ) if _addtail and self . tail is not None : result . append ( self . tail ) return result | Returns a list of text strings contained within an element and its sub - elements . |
60,832 | def _reindent ( s , indent , reformat = True ) : s = textwrap . dedent ( s ) s = s . split ( '\n' ) s = [ x . rstrip ( ) for x in s ] while s and ( not s [ 0 ] ) : s = s [ 1 : ] while s and ( not s [ - 1 ] ) : s = s [ : - 1 ] if reformat : s = '\n' . join ( s ) s = textwrap . wrap ( s , initial_indent = indent , subseq... | Remove the existing indentation from each line of a chunk of text s and then prefix each line with a new indent string . |
60,833 | def generate_docstr ( element , indent = '' , wrap = None ) : result = [ ] txt = element . text and element . text . rstrip ( ) if txt : result . append ( _reindent ( txt , indent ) ) result . append ( indent ) for d in element . findall ( 'doc' ) + element . findall ( 'rule' ) : docval = '' . join ( d . textlist ( ) )... | Generate a Python docstr for a given element in the AMQP XML spec file . The element could be a class or method |
60,834 | def generate_module ( spec , out ) : for amqp_class in spec . findall ( 'class' ) : if amqp_class . attrib [ 'name' ] == 'access' : amqp_class . attrib [ 'handler' ] = 'channel' for domain in spec . findall ( 'domain' ) : domains [ domain . attrib [ 'name' ] ] = domain . attrib [ 'type' ] for amqp_class in spec . finda... | Given an AMQP spec parsed into an xml . etree . ElemenTree and a file - like out object to write to generate the skeleton of a Python module . |
60,835 | def _process_method_frame ( self , channel , payload ) : method_sig = unpack ( '>HH' , payload [ : 4 ] ) args = AMQPReader ( payload [ 4 : ] ) if method_sig in _CONTENT_METHODS : self . partial_messages [ channel ] = _PartialMessage ( method_sig , args ) self . expected_types [ channel ] = 2 else : self . queue . put (... | Process Method frames |
60,836 | def _alert ( self , args ) : reply_code = args . read_short ( ) reply_text = args . read_shortstr ( ) details = args . read_table ( ) self . alerts . put ( ( reply_code , reply_text , details ) ) | This method allows the server to send a non - fatal warning to the client . This is used for methods that are normally asynchronous and thus do not have confirmations and for which the server may detect errors that need to be reported . Fatal errors are handled as channel or connection exceptions ; non - fatal errors a... |
60,837 | def access_request ( self , realm , exclusive = False , passive = False , active = False , write = False , read = False ) : args = AMQPWriter ( ) args . write_shortstr ( realm ) args . write_bit ( exclusive ) args . write_bit ( passive ) args . write_bit ( active ) args . write_bit ( write ) args . write_bit ( read ) s... | request an access ticket |
60,838 | def exchange_declare ( self , exchange , type , passive = False , durable = False , auto_delete = True , internal = False , nowait = False , arguments = None , ticket = None ) : if arguments is None : arguments = { } args = AMQPWriter ( ) if ticket is not None : args . write_short ( ticket ) else : args . write_short (... | declare exchange create if needed |
60,839 | def exchange_delete ( self , exchange , if_unused = False , nowait = False , ticket = None ) : args = AMQPWriter ( ) if ticket is not None : args . write_short ( ticket ) else : args . write_short ( self . default_ticket ) args . write_shortstr ( exchange ) args . write_bit ( if_unused ) args . write_bit ( nowait ) sel... | delete an exchange |
60,840 | def queue_bind ( self , queue , exchange , routing_key = '' , nowait = False , arguments = None , ticket = None ) : if arguments is None : arguments = { } args = AMQPWriter ( ) if ticket is not None : args . write_short ( ticket ) else : args . write_short ( self . default_ticket ) args . write_shortstr ( queue ) args ... | bind queue to an exchange |
60,841 | def _queue_declare_ok ( self , args ) : queue = args . read_shortstr ( ) message_count = args . read_long ( ) consumer_count = args . read_long ( ) return queue , message_count , consumer_count | confirms a queue definition |
60,842 | def basic_consume ( self , queue = '' , consumer_tag = '' , no_local = False , no_ack = False , exclusive = False , nowait = False , callback = None , ticket = None ) : args = AMQPWriter ( ) if ticket is not None : args . write_short ( ticket ) else : args . write_short ( self . default_ticket ) args . write_shortstr (... | start a queue consumer |
60,843 | def _basic_deliver ( self , args , msg ) : consumer_tag = args . read_shortstr ( ) delivery_tag = args . read_longlong ( ) redelivered = args . read_bit ( ) exchange = args . read_shortstr ( ) routing_key = args . read_shortstr ( ) msg . delivery_info = { 'channel' : self , 'consumer_tag' : consumer_tag , 'delivery_tag... | notify the client of a consumer message |
60,844 | def basic_get ( self , queue = '' , no_ack = False , ticket = None ) : args = AMQPWriter ( ) if ticket is not None : args . write_short ( ticket ) else : args . write_short ( self . default_ticket ) args . write_shortstr ( queue ) args . write_bit ( no_ack ) self . _send_method ( ( 60 , 70 ) , args ) return self . wait... | direct access to a queue |
60,845 | def basic_publish ( self , msg , exchange = '' , routing_key = '' , mandatory = False , immediate = False , ticket = None ) : args = AMQPWriter ( ) if ticket is not None : args . write_short ( ticket ) else : args . write_short ( self . default_ticket ) args . write_shortstr ( exchange ) args . write_shortstr ( routing... | publish a message |
60,846 | def _basic_return ( self , args , msg ) : reply_code = args . read_short ( ) reply_text = args . read_shortstr ( ) exchange = args . read_shortstr ( ) routing_key = args . read_shortstr ( ) self . returned_messages . put ( ( reply_code , reply_text , exchange , routing_key , msg ) ) | return a failed message |
60,847 | def _wait_method ( self , channel_id , allowed_methods ) : method_queue = self . channels [ channel_id ] . method_queue for queued_method in method_queue : method_sig = queued_method [ 0 ] if ( allowed_methods is None ) or ( method_sig in allowed_methods ) or ( method_sig == ( 20 , 40 ) ) : method_queue . remove ( queu... | Wait for a method from the server destined for a particular channel . |
60,848 | def channel ( self , channel_id = None ) : if channel_id in self . channels : return self . channels [ channel_id ] return Channel ( self , channel_id ) | Fetch a Channel object identified by the numeric channel_id or create that object if it doesn t already exist . |
60,849 | def _close ( self , args ) : reply_code = args . read_short ( ) reply_text = args . read_shortstr ( ) class_id = args . read_short ( ) method_id = args . read_short ( ) self . _x_close_ok ( ) raise AMQPConnectionException ( reply_code , reply_text , ( class_id , method_id ) ) | request a connection close |
60,850 | def _x_open ( self , virtual_host , capabilities = '' , insist = False ) : args = AMQPWriter ( ) args . write_shortstr ( virtual_host ) args . write_shortstr ( capabilities ) args . write_bit ( insist ) self . _send_method ( ( 10 , 40 ) , args ) return self . wait ( allowed_methods = [ ( 10 , 41 ) , ( 10 , 50 ) , ] ) | open connection to virtual host |
60,851 | def _open_ok ( self , args ) : self . known_hosts = args . read_shortstr ( ) AMQP_LOGGER . debug ( 'Open OK! known_hosts [%s]' % self . known_hosts ) return None | signal that the connection is ready |
60,852 | def _redirect ( self , args ) : host = args . read_shortstr ( ) self . known_hosts = args . read_shortstr ( ) AMQP_LOGGER . debug ( 'Redirected to [%s], known_hosts [%s]' % ( host , self . known_hosts ) ) return host | asks the client to use a different server |
60,853 | def _start ( self , args ) : self . version_major = args . read_octet ( ) self . version_minor = args . read_octet ( ) self . server_properties = args . read_table ( ) self . mechanisms = args . read_longstr ( ) . split ( ' ' ) self . locales = args . read_longstr ( ) . split ( ' ' ) AMQP_LOGGER . debug ( 'Start from s... | start connection negotiation |
60,854 | def _x_start_ok ( self , client_properties , mechanism , response , locale ) : args = AMQPWriter ( ) args . write_table ( client_properties ) args . write_shortstr ( mechanism ) args . write_longstr ( response ) args . write_shortstr ( locale ) self . _send_method ( ( 10 , 11 ) , args ) | select security mechanism and locale |
60,855 | def _tune ( self , args ) : self . channel_max = args . read_short ( ) or self . channel_max self . frame_max = args . read_long ( ) or self . frame_max self . method_writer . frame_max = self . frame_max self . heartbeat = args . read_short ( ) self . _x_tune_ok ( self . channel_max , self . frame_max , 0 ) | propose connection tuning parameters |
60,856 | def _send_method ( self , method_sig , args = bytes ( ) , content = None ) : if isinstance ( args , AMQPWriter ) : args = args . getvalue ( ) self . connection . method_writer . write_method ( self . channel_id , method_sig , args , content ) | Send a method for our channel . |
60,857 | def read_frame ( self ) : frame_type , channel , size = unpack ( '>BHI' , self . _read ( 7 ) ) payload = self . _read ( size ) ch = ord ( self . _read ( 1 ) ) if ch == 206 : return frame_type , channel , payload else : raise Exception ( 'Framing Error, received 0x%02x while expecting 0xce' % ch ) | Read an AMQP frame . |
60,858 | def write_frame ( self , frame_type , channel , payload ) : size = len ( payload ) self . _write ( pack ( '>BHI%dsB' % size , frame_type , channel , size , payload , 0xce ) ) | Write out an AMQP frame . |
60,859 | def _setup_transport ( self ) : if HAVE_PY26_SSL : if hasattr ( self , 'sslopts' ) : self . sslobj = ssl . wrap_socket ( self . sock , ** self . sslopts ) else : self . sslobj = ssl . wrap_socket ( self . sock ) self . sslobj . do_handshake ( ) else : self . sslobj = socket . ssl ( self . sock ) | Wrap the socket in an SSL object either the new Python 2 . 6 version or the older Python 2 . 5 and lower version . |
60,860 | def write_bit ( self , b ) : if b : b = 1 else : b = 0 shift = self . bitcount % 8 if shift == 0 : self . bits . append ( 0 ) self . bits [ - 1 ] |= ( b << shift ) self . bitcount += 1 | Write a boolean value . |
60,861 | def on_unexpected_error ( e ) : sys . stderr . write ( 'Unexpected error: {} ({})\n' . format ( str ( e ) , e . __class__ . __name__ ) ) sys . stderr . write ( 'See file slam_error.log for additional details.\n' ) sys . exit ( 1 ) | Catch - all error handler |
60,862 | def init ( name , description , bucket , timeout , memory , stages , requirements , function , runtime , config_file , ** kwargs ) : if os . path . exists ( config_file ) : raise RuntimeError ( 'Please delete the old version {} if you want to ' 'reconfigure your project.' . format ( config_file ) ) module , app = funct... | Generate a configuration file . |
60,863 | def _generate_lambda_handler ( config , output = '.slam/handler.py' ) : run_function = _run_lambda_function for name , plugin in plugins . items ( ) : if name in config and hasattr ( plugin , 'run_lambda_function' ) : run_function = plugin . run_lambda_function run_code = '' . join ( inspect . getsourcelines ( run_func... | Generate a handler . py file for the lambda function start up . |
60,864 | def build ( rebuild_deps , config_file ) : config = _load_config ( config_file ) print ( "Building lambda package..." ) package = _build ( config , rebuild_deps = rebuild_deps ) print ( "{} has been built successfully." . format ( package ) ) | Build lambda package . |
60,865 | def deploy ( stage , lambda_package , no_lambda , rebuild_deps , config_file ) : config = _load_config ( config_file ) if stage is None : stage = config [ 'devstage' ] s3 = boto3 . client ( 's3' ) cfn = boto3 . client ( 'cloudformation' ) region = _get_aws_region ( ) previous_deployment = None try : previous_deployment... | Deploy the project to the development stage . |
60,866 | def publish ( version , stage , config_file ) : config = _load_config ( config_file ) cfn = boto3 . client ( 'cloudformation' ) if version is None : version = config [ 'devstage' ] elif version not in config [ 'stage_environments' ] . keys ( ) and not version . isdigit ( ) : raise ValueError ( 'Invalid version. Use a s... | Publish a version of the project to a stage . |
60,867 | def invoke ( stage , async , dry_run , config_file , args ) : config = _load_config ( config_file ) if stage is None : stage = config [ 'devstage' ] cfn = boto3 . client ( 'cloudformation' ) lmb = boto3 . client ( 'lambda' ) try : stack = cfn . describe_stacks ( StackName = config [ 'name' ] ) [ 'Stacks' ] [ 0 ] except... | Invoke the lambda function . |
60,868 | def template ( config_file ) : config = _load_config ( config_file ) print ( get_cfn_template ( config , pretty = True ) ) | Print the default Cloudformation deployment template . |
60,869 | def register_plugins ( ) : if pkg_resources : for ep in pkg_resources . iter_entry_points ( 'slam_plugins' ) : plugin = ep . load ( ) if hasattr ( plugin , 'init' ) and hasattr ( plugin . init , '_arguments' ) : for arg in plugin . init . _arguments : init . parser . add_argument ( * arg [ 0 ] , ** arg [ 1 ] ) init . _... | find any installed plugins and register them . |
60,870 | def synchronise_device_state ( self , device_state , authentication_headers ) : payload = { 'context' : device_state , 'event' : { 'header' : { 'namespace' : 'System' , 'name' : 'SynchronizeState' , 'messageId' : '' } , 'payload' : { } } } multipart_data = MultipartEncoder ( fields = [ ( 'metadata' , ( 'metadata' , jso... | Synchronizing the component states with AVS |
60,871 | def send_audio_file ( self , audio_file , device_state , authentication_headers , dialog_request_id , distance_profile , audio_format ) : payload = { 'context' : device_state , 'event' : { 'header' : { 'namespace' : 'SpeechRecognizer' , 'name' : 'Recognize' , 'messageId' : self . generate_message_id ( ) , 'dialogReques... | Send audio to AVS |
60,872 | def retrieve_api_token ( self ) : payload = self . oauth2_manager . get_access_token_params ( refresh_token = self . refresh_token ) response = requests . post ( self . oauth2_manager . access_token_url , json = payload ) response . raise_for_status ( ) response_json = json . loads ( response . text ) return response_j... | Retrieve the access token from AVS . |
60,873 | def webpack_template_tag ( path_to_config ) : try : return webpack ( path_to_config ) except ( AttributeError , ValueError ) as e : raise six . reraise ( BundlingError , BundlingError ( * e . args ) , sys . exc_info ( ) [ 2 ] ) | A template tag that will output a webpack bundle . |
60,874 | def _prepare_key ( key , * args , ** kwargs ) : if not args and not kwargs : return key items = sorted ( kwargs . items ( ) ) hashable_args = ( args , tuple ( items ) ) args_key = hashlib . md5 ( pickle . dumps ( hashable_args ) ) . hexdigest ( ) return "%s/args:%s" % ( key , args_key ) | if arguments are given adds a hash of the args to the key . |
60,875 | def setup ( logdir = 'log' ) : logger = logging . getLogger ( ) logger . setLevel ( logging . DEBUG ) logdir = os . path . normpath ( logdir ) if not os . path . exists ( logdir ) : os . makedirs ( logdir ) t = datetime . datetime . now ( ) logfile = '{year:04d}{mon:02d}{day:02d}-' '{hour:02d}{min:02d}{sec:02d}.log' . ... | Set up dual logging to console and to logfile . |
60,876 | def get_versions ( ) -> FileVersionResult : version_counter = Counter ( ) versions_match = False version_str = None versions_discovered = OrderedDict ( ) for version_obj in version_objects : discovered = version_obj . get_version ( ) versions_discovered [ version_obj . key_name ] = discovered version_counter . update (... | Search specific project files and extract versions to check . |
60,877 | def supportedChars ( * tests ) : for test in tests : try : test . encode ( sys . stdout . encoding ) return test except UnicodeEncodeError : pass return '?' * len ( tests [ 0 ] ) | Takes any number of strings and returns the first one the terminal encoding supports . If none are supported it returns ? the length of the first string . |
60,878 | def app_templates_dirs ( self ) : app_templates_dirs = OrderedDict ( ) for app_config in apps . get_app_configs ( ) : templates_dir = os . path . join ( getattr ( app_config , 'path' , '/' ) , 'templates' ) if os . path . isdir ( templates_dir ) : templates_dir = upath ( templates_dir ) app_templates_dirs [ app_config ... | Build a cached dict with settings . INSTALLED_APPS as keys and the templates directory of each application as values . |
60,879 | def get_contents ( self , origin ) : try : path = self . get_app_template_path ( origin . app_name , origin . template_name ) with io . open ( path , encoding = self . engine . file_charset ) as fp : return fp . read ( ) except KeyError : raise TemplateDoesNotExist ( origin ) except IOError as error : if error . errno ... | Try to load the origin . |
60,880 | def load_template_source ( self , * ka ) : template_name = ka [ 0 ] for origin in self . get_template_sources ( template_name ) : try : return self . get_contents ( origin ) , origin . name except TemplateDoesNotExist : pass raise TemplateDoesNotExist ( template_name ) | Backward compatible method for Django < 2 . 0 . |
60,881 | def rotateImage ( image , angle ) : image = [ list ( row ) for row in image ] for n in range ( angle % 4 ) : image = list ( zip ( * image [ : : - 1 ] ) ) return image | rotates a 2d array to a multiple of 90 deg . 0 = default 1 = 90 deg . cw 2 = 180 deg . 3 = 90 deg . ccw |
60,882 | def overlaps ( self , canvas , exclude = [ ] ) : try : exclude = list ( exclude ) except TypeError : exclude = [ exclude ] exclude . append ( self ) for selfY , row in enumerate ( self . image . image ( ) ) : for selfX , pixel in enumerate ( row ) : canvasPixelOn = canvas . testPixel ( ( selfX + self . position [ 0 ] ,... | Returns True if sprite is touching any other sprite . |
60,883 | def onEdge ( self , canvas ) : sides = [ ] if int ( self . position [ 0 ] ) <= 0 : sides . append ( 1 ) if ( int ( self . position [ 0 ] ) + self . image . width ) >= canvas . width : sides . append ( 3 ) if int ( self . position [ 1 ] ) <= 0 : sides . append ( 2 ) if ( int ( self . position [ 1 ] ) + self . image . he... | Returns a list of the sides of the sprite which are touching the edge of the canvas . |
60,884 | def remote_property ( name , get_command , set_command , field_name , doc = None ) : def getter ( self ) : try : return getattr ( self , name ) except AttributeError : value = getattr ( self . sendCommand ( get_command ( ) ) , field_name ) setattr ( self , name , value ) return value def setter ( self , value ) : setat... | Property decorator that facilitates writing properties for values from a remote device . |
60,885 | def sendCommand ( self , command ) : command_data = [ ord ( x ) for x in buffer ( command ) ] self . hid . write ( command_data ) response_data = '' . join ( chr ( x ) for x in self . hid . read ( 64 ) ) response = command . RESPONSE . from_buffer_copy ( response_data ) if response . status != 0 : raise CommandExceptio... | Sends a Command object to the MCP2210 and returns its response . |
60,886 | def transfer ( self , data ) : settings = self . transfer_settings settings . spi_tx_size = len ( data ) self . transfer_settings = settings response = '' for i in range ( 0 , len ( data ) , 60 ) : response += self . sendCommand ( commands . SPITransferCommand ( data [ i : i + 60 ] ) ) . data time . sleep ( 0.01 ) whil... | Transfers data over SPI . |
60,887 | def render_json_response ( self , context_dict , status = 200 ) : json_context = json . dumps ( context_dict , cls = DjangoJSONEncoder , ** self . get_json_dumps_kwargs ( ) ) . encode ( u'utf-8' ) return HttpResponse ( json_context , content_type = self . get_content_type ( ) , status = status ) | Limited serialization for shipping plain data . Do not use for models or other complex or custom objects . |
60,888 | def form_valid ( self , form ) : self . object = form . save ( commit = False ) self . pre_save ( ) self . object . save ( ) if hasattr ( form , 'save_m2m' ) : form . save_m2m ( ) self . post_save ( ) if self . request . is_ajax ( ) : return self . render_json_response ( self . get_success_result ( ) ) return HttpRespo... | If the request is ajax save the form and return a json response . Otherwise return super as expected . |
60,889 | def form_invalid ( self , form ) : if self . request . is_ajax ( ) : return self . render_json_response ( self . get_error_result ( form ) ) return super ( AjaxFormMixin , self ) . form_invalid ( form ) | We have errors in the form . If ajax return them as json . Otherwise proceed as normal . |
60,890 | def assumes ( * args ) : args = tuple ( args ) def decorator ( func ) : func . assumptions = args return func return decorator | Stores a function s assumptions as an attribute . |
60,891 | def overridden_by_assumptions ( * args ) : args = tuple ( args ) def decorator ( func ) : func . overridden_by_assumptions = args return func return decorator | Stores what assumptions a function is overridden by as an attribute . |
60,892 | def equation_docstring ( quantity_dict , assumption_dict , equation = None , references = None , notes = None ) : def decorator ( func ) : out_name_end_index = func . __name__ . find ( '_from_' ) if out_name_end_index == - 1 : raise ValueError ( 'equation_docstring decorator must be applied to ' 'function whose name co... | Creates a decorator that adds a docstring to an equation function . |
60,893 | def sma ( array , window_size , axis = - 1 , mode = 'reflect' , ** kwargs ) : kwargs [ 'axis' ] = axis kwargs [ 'mode' ] = mode if not isinstance ( window_size , int ) : raise TypeError ( 'window_size must be an integer' ) if not isinstance ( kwargs [ 'axis' ] , int ) : raise TypeError ( 'axis must be an integer' ) ret... | Computes a 1D simple moving average along the given axis . |
60,894 | def assumption_list_string ( assumptions , assumption_dict ) : if isinstance ( assumptions , six . string_types ) : raise TypeError ( 'assumptions must be an iterable of strings, not a ' 'string itself' ) for a in assumptions : if a not in assumption_dict . keys ( ) : raise ValueError ( '{} not present in assumption_di... | Takes in a list of short forms of assumptions and an assumption dictionary and returns a list form of the long form of the assumptions . |
60,895 | def quantity_spec_string ( name , quantity_dict ) : if name not in quantity_dict . keys ( ) : raise ValueError ( '{0} not present in quantity_dict' . format ( name ) ) s = '{0} : float or ndarray\n' . format ( name ) s += doc_paragraph ( 'Data for {0}.' . format ( quantity_string ( name , quantity_dict ) ) , indent = 4... | Returns a quantity specification for docstrings . |
60,896 | def doc_paragraph ( s , indent = 0 ) : return '\n' . join ( [ ' ' * indent + l for l in wrap ( s , width = 80 - indent ) ] ) | Takes in a string without wrapping corresponding to a paragraph and returns a version of that string wrapped to be at most 80 characters in length on each line . If indent is given ensures each line is indented to that number of spaces . |
60,897 | def closest_val ( x , L ) : if len ( L ) == 0 : raise ValueError ( 'L must not be empty' ) if isinstance ( L , np . ndarray ) : return ( np . abs ( L - x ) ) . argmin ( ) min_index = 0 min_diff = abs ( L [ 0 ] - x ) i = 1 while i < len ( L ) : diff = abs ( L [ i ] - x ) if diff < min_diff : min_index = i min_diff = dif... | Finds the index value in an iterable closest to a desired value . |
60,898 | def area_poly_sphere ( lat , lon , r_sphere ) : dtr = np . pi / 180. def _tranlon ( plat , plon , qlat , qlon ) : t = np . sin ( ( qlon - plon ) * dtr ) * np . cos ( qlat * dtr ) b = ( np . sin ( qlat * dtr ) * np . cos ( plat * dtr ) - np . cos ( qlat * dtr ) * np . sin ( plat * dtr ) * np . cos ( ( qlon - plon ) * dt... | Calculates the area enclosed by an arbitrary polygon on the sphere . |
60,899 | def d_x ( data , axis , boundary = 'forward-backward' ) : if abs ( axis ) > len ( data . shape ) : raise ValueError ( 'axis is out of bounds for the shape of data' ) if boundary == 'periodic' : diff = np . roll ( data , - 1 , axis ) - np . roll ( data , 1 , axis ) elif boundary == 'forward-backward' : front = [ slice (... | Calculates a second - order centered finite difference of data along the specified axis . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.