idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
49,500 | def userinfo_in_id_token_claims ( endpoint_context , session , def_itc = None ) : if def_itc : itc = def_itc else : itc = { } itc . update ( id_token_claims ( session ) ) if not itc : return None _claims = by_schema ( endpoint_context . id_token_schema , ** itc ) if _claims : return collect_user_info ( endpoint_context... | Collect user info claims that are to be placed in the id token . |
49,501 | def value_matrix ( self ) : if self . __value_matrix : return self . __value_matrix self . __value_matrix = [ [ value_dp . data for value_dp in value_dp_list ] for value_dp_list in self . value_dp_matrix ] return self . __value_matrix | Converted rows of tabular data . |
49,502 | def from_dataframe ( dataframe , table_name = "" ) : return TableData ( table_name , list ( dataframe . columns . values ) , dataframe . values . tolist ( ) ) | Initialize TableData instance from a pandas . DataFrame instance . |
49,503 | def call_async ( func ) : @ wraps ( func ) def wrapper ( self , * args , ** kw ) : def call ( ) : try : func ( self , * args , ** kw ) except Exception : logger . exception ( "failed to call async [%r] with [%r] [%r]" , func , args , kw ) self . loop . call_soon_threadsafe ( call ) return wrapper | Decorates a function to be called async on the loop thread |
49,504 | def call_sync ( func ) : @ wraps ( func ) def wrapper ( self , * args , ** kw ) : if self . thread . ident == get_ident ( ) : return func ( self , * args , ** kw ) barrier = Barrier ( 2 ) result = None ex = None def call ( ) : nonlocal result , ex try : result = func ( self , * args , ** kw ) except Exception as exc : ... | Decorates a function to be called sync on the loop thread |
49,505 | def close ( self , proto ) : try : proto . sendClose ( ) except Exception as ex : logger . exception ( "Failed to send close" ) proto . reraise ( ex ) | Closes a connection |
49,506 | def process ( self ) : with self . lock , self . enlock : queue = copy ( self . queue ) self . queue . clear ( ) callbacks = copy ( self . callbacks ) with self . lock : rm_cb = False for ki , vi in queue . items ( ) : if ki in self . callbacks : for item in vi : for cb in self . callbacks [ ki ] : if cb ( item ) is Fa... | Process queue for these listeners . Only the items with type that matches |
49,507 | def add ( self , callback_type , callback ) : with self . lock : self . callbacks [ callback_type ] . append ( callback ) | Add a new listener |
49,508 | def enqueue ( self , item_type , item ) : with self . enlock : self . queue [ item_type ] . append ( item ) | Queue a new data item make item iterable |
49,509 | def xy_spectrail_arc_intersections ( self , slitlet2d = None ) : if self . list_arc_lines is None : raise ValueError ( "Arc lines not sought" ) number_spectrum_trails = len ( self . list_spectrails ) if number_spectrum_trails == 0 : raise ValueError ( "Number of available spectrum trails is 0" ) number_arc_lines = len ... | Compute intersection points of spectrum trails with arc lines . |
49,510 | def intersection ( a , b , scale = 1 ) : try : a1 , a2 = a except TypeError : a1 = a . start a2 = a . stop try : b1 , b2 = b except TypeError : b1 = b . start b2 = b . stop if a2 <= b1 : return None if a1 >= b2 : return None if a2 <= b2 : if a1 <= b1 : return slice ( b1 * scale , a2 * scale ) else : return slice ( a1 *... | Intersection between two segments . |
49,511 | def clip_slices ( r , region , scale = 1 ) : t = [ ] for ch in r : a1 = intersection ( ch [ 0 ] , region [ 0 ] , scale = scale ) if a1 is None : continue a2 = intersection ( ch [ 1 ] , region [ 1 ] , scale = scale ) if a2 is None : continue t . append ( ( a1 , a2 ) ) return t | Intersect slices with a region . |
49,512 | def _load_defaults ( inventory_path = None , roles = None , extra_vars = None , tags = None , basedir = False ) : extra_vars = extra_vars or { } tags = tags or [ ] loader = DataLoader ( ) if basedir : loader . set_basedir ( basedir ) inventory = EnosInventory ( loader = loader , sources = inventory_path , roles = roles... | Load common defaults data structures . |
49,513 | def run_play ( play_source , inventory_path = None , roles = None , extra_vars = None , on_error_continue = False ) : results = [ ] inventory , variable_manager , loader , options = _load_defaults ( inventory_path = inventory_path , roles = roles , extra_vars = extra_vars ) callback = _MyCallback ( results ) passwords ... | Run a play . |
49,514 | def run_command ( pattern_hosts , command , inventory_path = None , roles = None , extra_vars = None , on_error_continue = False ) : def filter_results ( results , status ) : _r = [ r for r in results if r . status == status and r . task == COMMAND_NAME ] s = dict ( [ [ r . host , { "stdout" : r . payload . get ( "stdo... | Run a shell command on some remote hosts . |
49,515 | def run_ansible ( playbooks , inventory_path = None , roles = None , extra_vars = None , tags = None , on_error_continue = False , basedir = '.' ) : inventory , variable_manager , loader , options = _load_defaults ( inventory_path = inventory_path , roles = roles , extra_vars = extra_vars , tags = tags , basedir = base... | Run Ansible . |
49,516 | def discover_networks ( roles , networks , fake_interfaces = None , fake_networks = None ) : def get_devices ( facts ) : devices = [ ] for interface in facts [ 'ansible_interfaces' ] : ansible_interface = 'ansible_' + interface if 'ansible_' + interface in facts : interface = facts [ ansible_interface ] devices . appen... | Checks the network interfaces on the nodes . |
49,517 | def generate_inventory ( roles , networks , inventory_path , check_networks = False , fake_interfaces = None , fake_networks = None ) : with open ( inventory_path , "w" ) as f : f . write ( _generate_inventory ( roles ) ) if check_networks : discover_networks ( roles , networks , fake_interfaces = fake_interfaces , fak... | Generate an inventory file in the ini format . |
49,518 | def emulate_network ( network_constraints , roles = None , inventory_path = None , extra_vars = None ) : if not network_constraints : return if roles is None and inventory is None : raise ValueError ( "roles and inventory can't be None" ) if not extra_vars : extra_vars = { } logger . debug ( 'Getting the ips of all nod... | Emulate network links . |
49,519 | def wait_ssh ( roles , retries = 100 , interval = 30 ) : utils_playbook = os . path . join ( ANSIBLE_DIR , 'utils.yml' ) options = { 'enos_action' : 'ping' } for i in range ( 0 , retries ) : try : run_ansible ( [ utils_playbook ] , roles = roles , extra_vars = options , on_error_continue = False ) break except EnosUnre... | Wait for all the machines to be ssh - reachable |
49,520 | def expand_groups ( grp ) : p = re . compile ( r"(?P<name>.+)\[(?P<start>\d+)-(?P<end>\d+)\]" ) m = p . match ( grp ) if m is not None : s = int ( m . group ( 'start' ) ) e = int ( m . group ( 'end' ) ) n = m . group ( 'name' ) return list ( map ( lambda x : n + str ( x ) , range ( s , e + 1 ) ) ) else : return [ grp ] | Expand group names . |
49,521 | def _generate_default_grp_constraints ( roles , network_constraints ) : default_delay = network_constraints . get ( 'default_delay' ) default_rate = network_constraints . get ( 'default_rate' ) default_loss = network_constraints . get ( 'default_loss' , 0 ) except_groups = network_constraints . get ( 'except' , [ ] ) g... | Generate default symetric grp constraints . |
49,522 | def _generate_actual_grp_constraints ( network_constraints ) : if 'constraints' not in network_constraints : return [ ] constraints = network_constraints [ 'constraints' ] actual = [ ] for desc in constraints : descs = _expand_description ( desc ) for desc in descs : actual . append ( desc ) if 'symetric' in desc : sym... | Generate the user specified constraints |
49,523 | def _merge_constraints ( constraints , overrides ) : for o in overrides : i = 0 while i < len ( constraints ) : c = constraints [ i ] if _same ( o , c ) : constraints [ i ] . update ( o ) break i = i + 1 | Merge the constraints avoiding duplicates Change constraints in place . |
49,524 | def _build_grp_constraints ( roles , network_constraints ) : constraints = _generate_default_grp_constraints ( roles , network_constraints ) if 'constraints' in network_constraints : actual = _generate_actual_grp_constraints ( network_constraints ) _merge_constraints ( constraints , actual ) return constraints | Generate constraints at the group level It expands the group names and deal with symetric constraints . |
49,525 | def _map_device_on_host_networks ( provider_nets , devices ) : networks = copy . deepcopy ( provider_nets ) for network in networks : for device in devices : network . setdefault ( 'device' , None ) ip_set = IPSet ( [ network [ 'cidr' ] ] ) if 'ipv4' not in device : continue ips = device [ 'ipv4' ] if not isinstance ( ... | Decorate each networks with the corresponding nic name . |
49,526 | def f_energy ( ac_power , times ) : dt = np . diff ( times ) dt = dt . astype ( 'timedelta64[s]' ) . astype ( 'float' ) / sc_const . hour energy = dt * ( ac_power [ : - 1 ] + ac_power [ 1 : ] ) / 2 return energy , times [ 1 : ] | Calculate the total energy accumulated from AC power at the end of each timestep between the given times . |
49,527 | def fileupdate ( self , data ) : self . name = data [ "name" ] add = self . __additional add [ "filetype" ] = "other" for filetype in ( "book" , "image" , "video" , "audio" , "archive" ) : if filetype in data : add [ "filetype" ] = filetype break if add [ "filetype" ] in ( "image" , "video" , "audio" ) : add [ "thumb" ... | Method to update extra metadata fields with dict obtained through fileinfo |
49,528 | def thumbnail ( self ) : if self . filetype not in ( "video" , "image" , "audio" ) : raise RuntimeError ( "Only video, audio and image files can have thumbnails" ) thumb_srv = self . thumb . get ( "server" ) url = f"https://{thumb_srv}" if thumb_srv else None return f"{url}/asset/{self.fid}/thumb" if url else "" | Returns the thumbnail s url for this image audio or video file . Returns empty string if the file has no thumbnail |
49,529 | def duration ( self ) : if self . filetype not in ( "video" , "audio" ) : raise RuntimeError ( "Only videos and audio have durations" ) return self . info . get ( "length" ) or self . info . get ( "duration" ) | Returns the duration in seconds of this audio or video file |
49,530 | def delete ( self ) : self . room . check_owner ( ) self . conn . make_call ( "deleteFiles" , [ self . fid ] ) | Remove this file |
49,531 | def timeout ( self , duration = 3600 ) : self . room . check_owner ( ) self . conn . make_call ( "timeoutFile" , self . fid , duration ) | Timeout the uploader of this file |
49,532 | def set_gid ( self ) : if self . group : gid = getgrnam ( self . group ) . gr_gid try : os . setgid ( gid ) except Exception : message = ( "Unable to switch ownership to {0}:{1}. " + "Did you start the daemon as root?" ) print ( message . format ( self . user , self . group ) ) sys . exit ( 1 ) | Change the group of the running process |
49,533 | def set_uid ( self ) : if self . user : uid = getpwnam ( self . user ) . pw_uid try : os . setuid ( uid ) except Exception : message = ( 'Unable to switch ownership to {0}:{1}. ' + 'Did you start the daemon as root?' ) print ( message . format ( self . user , self . group ) ) sys . exit ( 1 ) | Change the user of the running process |
49,534 | def setup_logging ( self ) : self . logger = logging . getLogger ( ) if os . path . exists ( '/dev/log' ) : handler = SysLogHandler ( '/dev/log' ) else : handler = SysLogHandler ( ) self . logger . addHandler ( handler ) | Set up self . logger |
49,535 | def status ( self ) : my_name = os . path . basename ( sys . argv [ 0 ] ) if self . _already_running ( ) : message = "{0} (pid {1}) is running...\n" . format ( my_name , self . pid ) sys . stdout . write ( message ) return 0 sys . stdout . write ( "{0} is stopped\n" . format ( my_name ) ) return 3 | Determine the status of the daemon |
49,536 | def fetch_resources ( uri , rel ) : if settings . STATIC_URL and uri . startswith ( settings . STATIC_URL ) : path = os . path . join ( settings . STATIC_ROOT , uri . replace ( settings . STATIC_URL , "" ) ) elif settings . MEDIA_URL and uri . startswith ( settings . MEDIA_URL ) : path = os . path . join ( settings . M... | Retrieves embeddable resource from given uri . |
49,537 | def html_to_pdf ( content , encoding = "utf-8" , link_callback = fetch_resources , ** kwargs ) : src = BytesIO ( content . encode ( encoding ) ) dest = BytesIO ( ) pdf = pisa . pisaDocument ( src , dest , encoding = encoding , link_callback = link_callback , ** kwargs ) if pdf . err : logger . error ( "Error rendering ... | Converts html content into PDF document . |
49,538 | def make_response ( content , filename = None , content_type = "application/pdf" ) : response = HttpResponse ( content , content_type = content_type ) if filename is not None : response [ "Content-Disposition" ] = "attachment; %s" % encode_filename ( filename ) return response | Wraps content into HTTP response . |
49,539 | def render_to_pdf ( template , context , using = None , request = None , encoding = "utf-8" , ** kwargs ) : content = loader . render_to_string ( template , context , request = request , using = using ) return html_to_pdf ( content , encoding , ** kwargs ) | Create PDF document from Django html template . |
49,540 | def render_to_pdf_response ( request , template , context , using = None , filename = None , encoding = "utf-8" , ** kwargs ) : try : pdf = render_to_pdf ( template , context , using = using , encoding = encoding , ** kwargs ) return make_response ( pdf , filename ) except PDFRenderingError as e : logger . exception ( ... | Renders a PDF response using given request template and context . |
49,541 | def get_pdf_response ( self , context , ** response_kwargs ) : return render_to_pdf_response ( request = self . request , template = self . get_template_names ( ) , context = context , using = self . template_engine , filename = self . get_pdf_filename ( ) , ** self . get_pdf_kwargs ( ) ) | Renders PDF document and prepares response . |
49,542 | def compile_patterns_in_dictionary ( dictionary ) : for key , value in dictionary . items ( ) : if isinstance ( value , str ) : dictionary [ key ] = re . compile ( value ) elif isinstance ( value , dict ) : compile_patterns_in_dictionary ( value ) return dictionary | Replace all strings in dictionary with compiled version of themselves and return dictionary . |
49,543 | def filter ( self , source_file , encoding ) : with codecs . open ( source_file , 'r' , encoding = encoding ) as f : text = f . read ( ) return [ filters . SourceText ( self . _filter ( text ) , source_file , encoding , 'context' ) ] | Parse file . |
49,544 | def _filter ( self , text ) : if self . line_endings : text = self . norm_nl ( text ) new_text = [ ] index = 0 last = 0 end = len ( text ) while index < end : m = self . escapes . match ( text , pos = index ) if self . escapes else None if m : index = m . end ( 0 ) continue handled = False for delimiter in self . delim... | Context delimiter filter . |
49,545 | def create_starttls_connection ( loop , protocol_factory , host = None , port = None , * , sock = None , ssl_context_factory = None , use_starttls = False , local_addr = None , ** kwargs ) : if host is not None and port is not None : host_addrs = yield from loop . getaddrinfo ( host , port , type = socket . SOCK_STREAM... | Create a connection which can later be upgraded to use TLS . |
49,546 | def _call_connection_lost_and_clean_up ( self , exc ) : self . _state = _State . CLOSED try : self . _protocol . connection_lost ( exc ) finally : self . _rawsock . close ( ) if self . _tls_conn is not None : self . _tls_conn . set_app_data ( None ) self . _tls_conn = None self . _rawsock = None self . _protocol = None... | Clean up all resources and call the protocols connection lost method . |
49,547 | def abort ( self ) : if self . _state == _State . CLOSED : self . _invalid_state ( "abort() called" ) return self . _force_close ( None ) | Immediately close the stream without sending remaining buffers or performing a proper shutdown . |
49,548 | def starttls ( self , ssl_context = None , post_handshake_callback = None ) : if self . _state != _State . RAW_OPEN or self . _closing : raise self . _invalid_state ( "starttls() called" ) if ssl_context is not None : self . _ssl_context = ssl_context self . _extra . update ( sslcontext = ssl_context ) else : self . _s... | Start a TLS stream on top of the socket . This is an invalid operation if the stream is not in RAW_OPEN state . |
49,549 | def write ( self , data ) : if not isinstance ( data , ( bytes , bytearray , memoryview ) ) : raise TypeError ( 'data argument must be byte-ish (%r)' , type ( data ) ) if not self . _state . is_writable or self . _closing : raise self . _invalid_state ( "write() called" ) if not data : return if not self . _buffer : se... | Write data to the transport . This is an invalid operation if the stream is not writable that is if it is closed . During TLS negotiation the data is buffered . |
49,550 | def explode ( prefix : str ) : def _app ( i , e = None ) : if i is not None : return { k : v for ( k , v ) in iter_fields ( i ) } , None return i , e def iter_fields ( event_field : Union [ dict , list ] ) : if type ( event_field ) is dict : for key , val in event_field . items ( ) : yield ( key , val ) elif type ( eve... | given an array of objects de - normalized into fields |
49,551 | def _has_xml_encode ( self , content ) : encode = None m = RE_XML_START . match ( content ) if m : if m . group ( 1 ) : m2 = RE_XML_ENCODE . match ( m . group ( 1 ) ) if m2 : enc = m2 . group ( 2 ) . decode ( 'ascii' ) try : codecs . getencoder ( enc ) encode = enc except LookupError : pass else : if m . group ( 2 ) : ... | Check XML encoding . |
49,552 | def to_text ( self , tree , force_root = False ) : self . extract_tag_metadata ( tree ) text = [ ] attributes = [ ] comments = [ ] blocks = [ ] if not ( self . ignores . match ( tree ) if self . ignores else None ) : capture = self . captures . match ( tree ) if self . captures is not None else None if capture : for at... | Extract text from tags . |
49,553 | def _filter ( self , text , context , encoding ) : content = [ ] blocks , attributes , comments = self . to_text ( bs4 . BeautifulSoup ( text , self . parser ) ) if self . comments : for c , desc in comments : content . append ( filters . SourceText ( c , context + ': ' + desc , encoding , self . type + 'comment' ) ) i... | Filter the source text . |
49,554 | def lazy_import ( func ) : try : f = sys . _getframe ( 1 ) except Exception : namespace = None else : namespace = f . f_locals return _LazyImport ( func . __name__ , func , namespace ) | Decorator for declaring a lazy import . |
49,555 | def csv_to_map ( fields , delimiter = ',' ) : def _csv_to_list ( csv_input ) : io_file = io . StringIO ( csv_input ) return next ( csv . reader ( io_file , delimiter = delimiter ) ) def _app ( current_tuple , e = None ) : if current_tuple is None or len ( current_tuple ) == 0 : return None , "no input" csv_list = _csv_... | Convert csv to dict |
49,556 | def map_to_csv ( fields , delimiter = "," ) : def _list_to_csv ( l ) : io_file = io . StringIO ( ) writer = csv . writer ( io_file , quoting = csv . QUOTE_NONNUMERIC , lineterminator = '' , delimiter = delimiter ) writer . writerow ( l ) return io_file . getvalue ( ) def _app ( current_tuple , e = None ) : if e is not ... | Convert dict to csv |
49,557 | def xarrayfunc ( func ) : @ wraps ( func ) def wrapper ( * args , ** kwargs ) : if any ( isinstance ( arg , xr . DataArray ) for arg in args ) : newargs = [ ] for arg in args : if isinstance ( arg , xr . DataArray ) : newargs . append ( arg . values ) else : newargs . append ( arg ) return dc . full_like ( args [ 0 ] ,... | Make a function compatible with xarray . DataArray . |
49,558 | def chunk ( * argnames , concatfunc = None ) : def _chunk ( func ) : depth = [ s . function for s in stack ( ) ] . index ( '<module>' ) f_globals = getframe ( depth ) . f_globals orgname = '_original_' + func . __name__ orgfunc = dc . utils . copy_function ( func , orgname ) f_globals [ orgname ] = orgfunc @ wraps ( fu... | Make a function compatible with multicore chunk processing . |
49,559 | def _filter ( self , text ) : self . markdown . reset ( ) return self . markdown . convert ( text ) | Filter markdown . |
49,560 | def format_sec ( s ) : prefixes = [ "" , "m" , "u" , "n" ] unit = 0 while s < 1 and unit + 1 < len ( prefixes ) : s *= 1000 unit += 1 return "{:.1f} {}s" . format ( s , prefixes [ unit ] ) | Format seconds in a more human readable way . It supports units down to nanoseconds . |
49,561 | def make_gtfs ( source_path , target_path , buffer , ndigits ) : pfeed = pf . read_protofeed ( source_path ) feed = m . build_feed ( pfeed , buffer = buffer ) gt . write_gtfs ( feed , target_path , ndigits = ndigits ) | Create a GTFS feed from the files in the directory SOURCE_PATH . See the project README for a description of the required source files . Save the feed to the file or directory TARGET_PATH . If the target path ends in . zip then write the feed as a zip archive . Otherwise assume the path is a directory and write the fee... |
49,562 | def psd ( data , dt , ndivide = 1 , window = hanning , overlap_half = False ) : logger = getLogger ( 'decode.utils.ndarray.psd' ) if overlap_half : step = int ( len ( data ) / ( ndivide + 1 ) ) size = step * 2 else : step = int ( len ( data ) / ndivide ) size = step if bin ( len ( data ) ) . count ( '1' ) != 1 : logger... | Calculate power spectrum density of data . |
49,563 | def allan_variance ( data , dt , tmax = 10 ) : allanvar = [ ] nmax = len ( data ) if len ( data ) < tmax / dt else int ( tmax / dt ) for i in range ( 1 , nmax + 1 ) : databis = data [ len ( data ) % i : ] y = databis . reshape ( len ( data ) // i , i ) . mean ( axis = 1 ) allanvar . append ( ( ( y [ 1 : ] - y [ : - 1 ]... | Calculate Allan variance . |
49,564 | def discover ( cls , path , depth = "0" ) : attributes = _get_attributes_from_path ( path ) try : if len ( attributes ) == 3 : item = attributes . pop ( ) path = "/" . join ( attributes ) collection = cls ( path , _is_principal ( path ) ) yield collection . get ( item ) return collection = cls ( path , _is_principal ( ... | Discover a list of collections under the given path . |
49,565 | def create_collection ( cls , href , collection = None , props = None ) : attributes = _get_attributes_from_path ( href ) if len ( attributes ) <= 1 : raise PrincipalNotAllowedError if not props : props = { } if not props . get ( "tag" ) and collection : props [ "tag" ] = collection [ 0 ] . name try : self = cls ( href... | Create a collection . |
49,566 | def sync ( self , old_token = None ) : token = "http://radicale.org/ns/sync/%s" % self . etag . strip ( "\"" ) if old_token : raise ValueError ( "Sync token are not supported (you can ignore this warning)" ) return token , self . list ( ) | Get the current sync token and changed items for synchronization . |
49,567 | def list ( self ) : if self . is_fake : return for item in self . collection . list ( ) : yield item . uid + self . content_suffix | List collection items . |
49,568 | def get ( self , href ) : if self . is_fake : return uid = _trim_suffix ( href , ( '.ics' , '.ical' , '.vcf' ) ) etesync_item = self . collection . get ( uid ) if etesync_item is None : return None try : item = vobject . readOne ( etesync_item . content ) except Exception as e : raise RuntimeError ( "Failed to parse it... | Fetch a single item . |
49,569 | def upload ( self , href , vobject_item ) : if self . is_fake : return content = vobject_item . serialize ( ) try : item = self . get ( href ) etesync_item = item . etesync_item etesync_item . content = content except api . exceptions . DoesNotExist : etesync_item = self . collection . get_content_class ( ) . create ( ... | Upload a new or replace an existing item . |
49,570 | def get_meta ( self , key = None ) : if self . is_fake : return { } if key == "tag" : return self . tag elif key is None : ret = { } for key in self . journal . info . keys ( ) : ret [ key ] = self . meta_mappings . map_get ( self . journal . info , key ) [ 1 ] return ret else : key , value = self . meta_mappings . map... | Get metadata value for collection . |
49,571 | def last_modified ( self ) : last_modified = time . strftime ( "%a, %d %b %Y %H:%M:%S GMT" , time . gmtime ( time . time ( ) ) ) return last_modified | Get the HTTP - datetime of when the collection was modified . |
49,572 | def serialize ( self ) : import datetime items = [ ] time_begin = datetime . datetime . now ( ) for href in self . list ( ) : items . append ( self . get ( href ) . item ) time_end = datetime . datetime . now ( ) self . logger . info ( "Collection read %d items in %s sec from %s" , len ( items ) , ( time_end - time_beg... | Get the unicode string representing the whole collection . |
49,573 | def acquire_lock ( cls , mode , user = None ) : if not user : return with EteSyncCache . lock : cls . user = user cls . etesync = cls . _get_etesync_for_user ( cls . user ) if cls . _should_sync ( ) : cls . _mark_sync ( ) cls . etesync . get_or_create_user_info ( force_fetch = True ) cls . etesync . sync_journal_list (... | Set a context manager to lock the whole storage . |
49,574 | def match_string ( self , stype ) : return not ( stype - self . string_types ) or bool ( stype & self . wild_string_types ) | Match string type . |
49,575 | def get_encoding_name ( self , name ) : name = codecs . lookup ( filters . PYTHON_ENCODING_NAMES . get ( name , name ) . lower ( ) ) . name if name . startswith ( ( 'utf-32' , 'utf-16' ) ) : name = name [ : 6 ] if CURRENT_ENDIAN == BIG_ENDIAN : name += '-be' else : name += '-le' if name == 'utf-8-sig' : name = 'utf-8' ... | Get encoding name . |
49,576 | def evaluate_inline_tail ( self , groups ) : if self . lines : self . line_comments . append ( [ groups [ 'line' ] [ 2 : ] . replace ( '\\\n' , '' ) , self . line_num , self . current_encoding ] ) | Evaluate inline comments at the tail of source code . |
49,577 | def evaluate_inline ( self , groups ) : if self . lines : if ( self . group_comments and self . line_num == self . prev_line + 1 and groups [ 'leading_space' ] == self . leading ) : self . line_comments [ - 1 ] [ 0 ] += '\n' + groups [ 'line' ] [ 2 : ] . replace ( '\\\n' , '' ) else : self . line_comments . append ( [ ... | Evaluate inline comments on their own lines . |
49,578 | def evaluate_unicode ( self , value ) : if value . startswith ( 'u8' ) : length = 1 value = value [ 3 : - 1 ] encoding = 'utf-8' elif value . startswith ( 'u' ) : length = 2 value = value [ 2 : - 1 ] encoding = 'utf-16' else : length = 4 value = value [ 2 : - 1 ] encoding = 'utf-32' def replace_unicode ( m ) : groups =... | Evaluate Unicode . |
49,579 | def evaluate_normal ( self , value ) : if value . startswith ( 'L' ) : size = self . wide_charset_size encoding = self . wide_exec_charset value = value [ 2 : - 1 ] pack = BYTE_STORE [ size | CURRENT_ENDIAN ] else : size = self . charset_size encoding = self . exec_charset value = value [ 1 : - 1 ] pack = BYTE_STORE [ ... | Evaluate normal string . |
49,580 | def extend_src_text ( self , content , context , text_list , category ) : prefix = self . prefix + '-' if self . prefix else '' for comment , line , encoding in text_list : content . append ( filters . SourceText ( textwrap . dedent ( comment ) , "%s (%d)" % ( context , line ) , encoding , prefix + category ) ) | Extend the source text list with the gathered text data . |
49,581 | def cube ( data , xcoords = None , ycoords = None , chcoords = None , scalarcoords = None , datacoords = None , attrs = None , name = None ) : cube = xr . DataArray ( data , dims = ( 'x' , 'y' , 'ch' ) , attrs = attrs , name = name ) cube . dcc . _initcoords ( ) if xcoords is not None : cube . coords . update ( { key :... | Create a cube as an instance of xarray . DataArray with Decode accessor . |
49,582 | def fromcube ( cube , template ) : array = dc . zeros_like ( template ) y , x = array . y . values , array . x . values gy , gx = cube . y . values , cube . x . values iy = interp1d ( gy , np . arange ( len ( gy ) ) ) ( y ) ix = interp1d ( gx , np . arange ( len ( gx ) ) ) ( x ) for ch in range ( len ( cube . ch ) ) : ... | Covert a decode cube to a decode array . |
49,583 | def makecontinuum ( cube , ** kwargs ) : inchs = kwargs . pop ( 'inchs' , None ) exchs = kwargs . pop ( 'exchs' , None ) if ( inchs is not None ) or ( exchs is not None ) : raise KeyError ( 'Inchs and exchs are no longer supported. Use weight instead.' ) if weight is None : weight = 1. cont = ( cube * ( 1 / weight ** 2... | Make a continuum array . |
49,584 | def _verify_encoding ( self , enc ) : enc = PYTHON_ENCODING_NAMES . get ( enc , enc ) try : codecs . getencoder ( enc ) encoding = enc except LookupError : encoding = None return encoding | Verify encoding is okay . |
49,585 | def has_bom ( self , f ) : content = f . read ( 4 ) encoding = None m = RE_UTF_BOM . match ( content ) if m is not None : if m . group ( 1 ) : encoding = 'utf-8-sig' elif m . group ( 2 ) : encoding = 'utf-32' elif m . group ( 3 ) : encoding = 'utf-32' elif m . group ( 4 ) : encoding = 'utf-16' elif m . group ( 5 ) : en... | Check for UTF8 UTF16 and UTF32 BOMs . |
49,586 | def _utf_strip_bom ( self , encoding ) : if encoding is None : pass elif encoding . lower ( ) == 'utf-8' : encoding = 'utf-8-sig' elif encoding . lower ( ) . startswith ( 'utf-16' ) : encoding = 'utf-16' elif encoding . lower ( ) . startswith ( 'utf-32' ) : encoding = 'utf-32' return encoding | Return an encoding that will ignore the BOM . |
49,587 | def _detect_buffer_encoding ( self , f ) : encoding = None with contextlib . closing ( mmap . mmap ( f . fileno ( ) , 0 , access = mmap . ACCESS_READ ) ) as m : encoding = self . _analyze_file ( m ) return encoding | Guess by checking BOM and checking _special_encode_check and using memory map . |
49,588 | def _analyze_file ( self , f ) : f . seek ( 0 ) if self . CHECK_BOM : encoding = self . has_bom ( f ) f . seek ( 0 ) else : util . warn_deprecated ( "'CHECK_BOM' attribute is deprecated. " "Please override 'has_bom` function to control or avoid BOM detection." ) if encoding is None : encoding = self . _utf_strip_bom ( ... | Analyze the file . |
49,589 | def _detect_encoding ( self , source_file ) : encoding = self . _guess ( source_file ) if encoding is None : encoding = self . default_encoding return encoding | Detect encoding . |
49,590 | def _run_first ( self , source_file ) : self . reset ( ) self . current_encoding = self . default_encoding encoding = None try : encoding = self . _detect_encoding ( source_file ) content = self . filter ( source_file , encoding ) except UnicodeDecodeError : if not encoding or encoding != self . default_encoding : cont... | Run on as first in chain . |
49,591 | def _guess ( self , filename ) : encoding = None file_size = os . path . getsize ( filename ) if not self . _is_very_large ( file_size ) : with open ( filename , "rb" ) as f : if file_size == 0 : encoding = 'ascii' else : encoding = self . _detect_buffer_encoding ( f ) if encoding is None : raise UnicodeDecodeError ( '... | Guess the encoding and decode the content of the file . |
49,592 | def ask_yes_no ( question , default = 'no' , answer = None ) : u default = default . lower ( ) yes = [ u'yes' , u'ye' , u'y' ] no = [ u'no' , u'n' ] if default in no : help_ = u'[N/y]?' default = False else : default = True help_ = u'[Y/n]?' while 1 : display = question + '\n' + help_ if answer is None : log . debug ( ... | u Will ask a question and keeps prompting until answered . |
49,593 | def get_correct_answer ( question , default = None , required = False , answer = None , is_answer_correct = None ) : u while 1 : if default is None : msg = u' - No Default Available' else : msg = ( u'\n[DEFAULT] -> {}\nPress Enter To ' u'Use Default' . format ( default ) ) prompt = question + msg + u'\n if answer is No... | u Ask user a question and confirm answer |
49,594 | def get_process ( cmd ) : if sys . platform . startswith ( 'win' ) : startupinfo = subprocess . STARTUPINFO ( ) startupinfo . dwFlags |= subprocess . STARTF_USESHOWWINDOW process = subprocess . Popen ( cmd , startupinfo = startupinfo , stdout = subprocess . PIPE , stderr = subprocess . STDOUT , stdin = subprocess . PIP... | Get a command process . |
49,595 | def get_process_output ( process , encoding = None ) : output = process . communicate ( ) returncode = process . returncode if not encoding : try : encoding = sys . stdout . encoding except Exception : encoding = locale . getpreferredencoding ( ) if returncode != 0 : raise RuntimeError ( "Runtime Error: %s" % ( output ... | Get the output from the process . |
49,596 | def call ( cmd , input_file = None , input_text = None , encoding = None ) : process = get_process ( cmd ) if input_file is not None : with open ( input_file , 'rb' ) as f : process . stdin . write ( f . read ( ) ) if input_text is not None : process . stdin . write ( input_text ) return get_process_output ( process , ... | Call with arguments . |
49,597 | def call_spellchecker ( cmd , input_text = None , encoding = None ) : process = get_process ( cmd ) if input_text is not None : for line in input_text . splitlines ( ) : offset = 0 end = len ( line ) while True : chunk_end = offset + 0x1fff m = None if chunk_end >= end else RE_LAST_SPACE_IN_CHUNK . search ( line , offs... | Call spell checker with arguments . |
49,598 | def random_name_gen ( size = 6 ) : return '' . join ( [ random . choice ( string . ascii_uppercase ) ] + [ random . choice ( string . ascii_uppercase + string . digits ) for i in range ( size - 1 ) ] ) if size > 0 else '' | Generate a random python attribute name . |
49,599 | def yaml_load ( source , loader = yaml . Loader ) : def construct_yaml_str ( self , node ) : return self . construct_scalar ( node ) class Loader ( loader ) : Loader . add_constructor ( 'tag:yaml.org,2002:str' , construct_yaml_str ) return yaml . load ( source , Loader ) | Wrap PyYaml s loader so we can extend it to suit our needs . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.