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 , session , _claims ) else : return None | 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 : ex = exc finally : barrier . wait ( ) self . loop . call_soon_threadsafe ( call ) barrier . wait ( ) if ex : raise ex or Exception ( "Unknown error" ) return result return wrapper | 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 False : callbacks [ ki ] . remove ( cb ) if not callbacks [ ki ] : del callbacks [ ki ] rm_cb = True with self . lock : if rm_cb : self . callbacks . clear ( ) for k , v in callbacks . items ( ) : self . callbacks [ k ] . extend ( v ) return len ( self . callbacks ) | 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 ( self . list_arc_lines ) if number_arc_lines == 0 : raise ValueError ( "Number of available arc lines is 0" ) self . x_inter_rect = np . array ( [ ] ) self . y_inter_rect = np . array ( [ ] ) for arcline in self . list_arc_lines : spectrail = self . list_spectrails [ self . i_middle_spectrail ] xroot , yroot = intersection_spectrail_arcline ( spectrail = spectrail , arcline = arcline ) arcline . x_rectified = xroot self . x_inter_rect = np . append ( self . x_inter_rect , [ xroot ] * number_spectrum_trails ) for spectrail in self . list_spectrails : y_expected = self . corr_yrect_a + self . corr_yrect_b * spectrail . y_rectified self . y_inter_rect = np . append ( self . y_inter_rect , y_expected ) if abs ( self . debugplot ) >= 10 : print ( '>>> y0_frontier_lower_expected........: ' , self . y0_frontier_lower_expected ) print ( '>>> y0_frontier_upper_expected........: ' , self . y0_frontier_upper_expected ) print ( '>>> shifted y0_frontier_upper_expected: ' , self . corr_yrect_a + self . corr_yrect_b * self . y0_frontier_lower ) print ( '>>> shifted y0_frontier_lower_expected: ' , self . corr_yrect_a + self . corr_yrect_b * self . y0_frontier_upper ) self . x_inter_orig = np . array ( [ ] ) self . y_inter_orig = np . array ( [ ] ) for arcline in self . list_arc_lines : for spectrail in self . list_spectrails : xroot , yroot = intersection_spectrail_arcline ( spectrail = spectrail , arcline = arcline ) self . x_inter_orig = np . append ( self . x_inter_orig , xroot ) self . y_inter_orig = np . append ( self . y_inter_orig , yroot ) if abs ( self . debugplot % 10 ) != 0 and slitlet2d is not None : title = "Slitlet#" + str ( self . islitlet ) + " (xy_spectrail_arc_intersections)" ax = ximshow ( slitlet2d , title = title , first_pixel = ( self . bb_nc1_orig , self . bb_ns1_orig ) , show = False ) for spectrail in self . list_spectrails : xdum , ydum = spectrail . linspace_pix ( start = self . bb_nc1_orig , stop = self . bb_nc2_orig ) ax . plot ( xdum , ydum , 'g' ) for arcline in self . list_arc_lines : xdum , ydum = arcline . linspace_pix ( start = self . bb_ns1_orig , stop = self . bb_ns2_orig ) ax . plot ( xdum , ydum , 'g' ) ax . plot ( self . x_inter_orig , self . y_inter_orig , 'co' ) ax . plot ( self . x_inter_rect , self . y_inter_rect , 'bo' ) pause_debugplot ( self . debugplot , pltshow = True ) | 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 * scale , a2 * scale ) else : if a1 <= b1 : return slice ( b1 * scale , b2 * scale ) else : return slice ( a1 * scale , b2 * scale ) | 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 ) variable_manager = VariableManager ( loader = loader , inventory = inventory ) if basedir : variable_manager . safe_basedir = True if extra_vars : variable_manager . extra_vars = extra_vars Options = namedtuple ( "Options" , [ "listtags" , "listtasks" , "listhosts" , "syntax" , "connection" , "module_path" , "forks" , "private_key_file" , "ssh_common_args" , "ssh_extra_args" , "sftp_extra_args" , "scp_extra_args" , "become" , "become_method" , "become_user" , "remote_user" , "verbosity" , "check" , "tags" , "diff" , "basedir" ] ) options = Options ( listtags = False , listtasks = False , listhosts = False , syntax = False , connection = "ssh" , module_path = None , forks = 100 , private_key_file = None , ssh_common_args = None , ssh_extra_args = None , sftp_extra_args = None , scp_extra_args = None , become = None , become_method = "sudo" , become_user = "root" , remote_user = None , verbosity = 2 , check = False , tags = tags , diff = None , basedir = basedir ) return inventory , variable_manager , loader , options | 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 = { } tqm = task_queue_manager . TaskQueueManager ( inventory = inventory , variable_manager = variable_manager , loader = loader , options = options , passwords = passwords , stdout_callback = callback ) play_inst = play . Play ( ) . load ( play_source , variable_manager = variable_manager , loader = loader ) try : tqm . run ( play_inst ) finally : tqm . cleanup ( ) failed_hosts = [ ] unreachable_hosts = [ ] for r in results : if r . status == STATUS_UNREACHABLE : unreachable_hosts . append ( r ) if r . status == STATUS_FAILED : failed_hosts . append ( r ) if len ( failed_hosts ) > 0 : logger . error ( "Failed hosts: %s" % failed_hosts ) if not on_error_continue : raise EnosFailedHostsError ( failed_hosts ) if len ( unreachable_hosts ) > 0 : logger . error ( "Unreachable hosts: %s" % unreachable_hosts ) if not on_error_continue : raise EnosUnreachableHostsError ( unreachable_hosts ) return results | 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 ( "stdout" ) , "stderr" : r . payload . get ( "stderr" ) } ] for r in _r ] ) return s play_source = { "hosts" : pattern_hosts , "tasks" : [ { "name" : COMMAND_NAME , "shell" : command , } ] } results = run_play ( play_source , inventory_path = inventory_path , roles = roles , extra_vars = extra_vars ) ok = filter_results ( results , STATUS_OK ) failed = filter_results ( results , STATUS_FAILED ) return { "ok" : ok , "failed" : failed , "results" : results } | 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 = basedir ) passwords = { } for path in playbooks : logger . info ( "Running playbook %s with vars:\n%s" % ( path , extra_vars ) ) pbex = PlaybookExecutor ( playbooks = [ path ] , inventory = inventory , variable_manager = variable_manager , loader = loader , options = options , passwords = passwords ) code = pbex . run ( ) stats = pbex . _tqm . _stats hosts = stats . processed . keys ( ) result = [ { h : stats . summarize ( h ) } for h in hosts ] results = { "code" : code , "result" : result , "playbook" : path } print ( results ) failed_hosts = [ ] unreachable_hosts = [ ] for h in hosts : t = stats . summarize ( h ) if t [ "failures" ] > 0 : failed_hosts . append ( h ) if t [ "unreachable" ] > 0 : unreachable_hosts . append ( h ) if len ( failed_hosts ) > 0 : logger . error ( "Failed hosts: %s" % failed_hosts ) if not on_error_continue : raise EnosFailedHostsError ( failed_hosts ) if len ( unreachable_hosts ) > 0 : logger . error ( "Unreachable hosts: %s" % unreachable_hosts ) if not on_error_continue : raise EnosUnreachableHostsError ( unreachable_hosts ) | 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 . append ( interface ) return devices wait_ssh ( roles ) tmpdir = os . path . join ( os . getcwd ( ) , TMP_DIRNAME ) _check_tmpdir ( tmpdir ) fake_interfaces = fake_interfaces or [ ] fake_networks = fake_networks or [ ] utils_playbook = os . path . join ( ANSIBLE_DIR , 'utils.yml' ) facts_file = os . path . join ( tmpdir , 'facts.json' ) options = { 'enos_action' : 'check_network' , 'facts_file' : facts_file , 'fake_interfaces' : fake_interfaces } run_ansible ( [ utils_playbook ] , roles = roles , extra_vars = options , on_error_continue = False ) with open ( facts_file ) as f : facts = json . load ( f ) for _ , host_facts in facts . items ( ) : host_nets = _map_device_on_host_networks ( networks , get_devices ( host_facts ) ) host_facts [ 'networks' ] = host_nets extra_mapping = dict ( zip ( fake_networks , fake_interfaces ) ) _update_hosts ( roles , facts , extra_mapping = extra_mapping ) | 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 , fake_networks = fake_networks ) with open ( inventory_path , "w" ) as f : f . write ( _generate_inventory ( roles ) ) | 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 nodes' ) tmpdir = os . path . join ( os . getcwd ( ) , TMP_DIRNAME ) _check_tmpdir ( tmpdir ) utils_playbook = os . path . join ( ANSIBLE_DIR , 'utils.yml' ) ips_file = os . path . join ( tmpdir , 'ips.txt' ) options = { 'enos_action' : 'tc_ips' , 'ips_file' : ips_file } run_ansible ( [ utils_playbook ] , roles = roles , extra_vars = options ) logger . debug ( 'Building all the constraints' ) constraints = _build_grp_constraints ( roles , network_constraints ) with open ( ips_file ) as f : ips = yaml . safe_load ( f ) ips_with_constraints = _build_ip_constraints ( roles , ips , constraints ) ips_with_constraints_file = os . path . join ( tmpdir , 'ips_with_constraints.yml' ) with open ( ips_with_constraints_file , 'w' ) as g : yaml . dump ( ips_with_constraints , g ) logger . info ( 'Enforcing the constraints' ) enable = network_constraints . setdefault ( 'enable' , True ) utils_playbook = os . path . join ( ANSIBLE_DIR , 'utils.yml' ) options = { 'enos_action' : 'tc_apply' , 'ips_with_constraints' : ips_with_constraints , 'tc_enable' : enable , } options . update ( extra_vars ) run_ansible ( [ utils_playbook ] , roles = roles , inventory_path = inventory_path , extra_vars = options ) | 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 EnosUnreachableHostsError as e : logger . info ( "Hosts unreachable: %s " % e . hosts ) logger . info ( "Retrying... %s/%s" % ( i + 1 , retries ) ) time . sleep ( interval ) else : raise EnosSSHNotReady ( 'Maximum retries reached' ) | 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' , [ ] ) grps = network_constraints . get ( 'groups' , roles . keys ( ) ) grps = [ expand_groups ( g ) for g in grps ] grps = [ x for expanded_group in grps for x in expanded_group ] return [ { 'src' : grp1 , 'dst' : grp2 , 'delay' : default_delay , 'rate' : default_rate , 'loss' : default_loss } for grp1 in grps for grp2 in grps if ( ( grp1 != grp2 or _src_equals_dst_in_constraints ( network_constraints , grp1 ) ) and grp1 not in except_groups and grp2 not in except_groups ) ] | 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 = desc . copy ( ) sym [ 'src' ] = desc [ 'dst' ] sym [ 'dst' ] = desc [ 'src' ] actual . append ( sym ) return actual | 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 ( ips , list ) : ips = [ ips ] if len ( ips ) < 1 : continue ip = IPAddress ( ips [ 0 ] [ 'address' ] ) if ip in ip_set : network [ 'device' ] = device [ 'device' ] continue return networks | 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" ] = data . get ( "thumb" , dict ( ) ) add [ "checksum" ] = data [ "checksum" ] add [ "expire_time" ] = data [ "expires" ] / 1000 add [ "size" ] = data [ "size" ] add [ "info" ] = data . get ( add [ "filetype" ] , dict ( ) ) add [ "uploader" ] = data [ "user" ] if self . room . admin : add [ "info" ] . update ( { "room" : data . get ( "room" ) } ) add [ "info" ] . update ( { "uploader_ip" : data . get ( "uploader_ip" ) } ) self . updated = True | 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 . MEDIA_ROOT , uri . replace ( settings . MEDIA_URL , "" ) ) else : path = os . path . join ( settings . STATIC_ROOT , uri ) if not os . path . isfile ( path ) : raise UnsupportedMediaPathException ( "media urls must start with {} or {}" . format ( settings . MEDIA_ROOT , settings . STATIC_ROOT ) ) return path . replace ( "\\" , "/" ) | 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 PDF document" ) for entry in pdf . log : if entry [ 0 ] == xhtml2pdf . default . PML_ERROR : logger_x2p . error ( "line %s, msg: %s, fragment: %s" , entry [ 1 ] , entry [ 2 ] , entry [ 3 ] ) raise PDFRenderingError ( "Errors rendering PDF" , content = content , log = pdf . log ) if pdf . warn : for entry in pdf . log : if entry [ 0 ] == xhtml2pdf . default . PML_WARNING : logger_x2p . warning ( "line %s, msg: %s, fragment: %s" , entry [ 1 ] , entry [ 2 ] , entry [ 3 ] ) return dest . getvalue ( ) | 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 ( e . message ) return HttpResponse ( e . message ) | 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 . delimiters : m = delimiter [ 0 ] . match ( text , pos = index ) if m : if self . context_visible_first is True : new_text . append ( text [ last : m . start ( 0 ) ] ) else : new_text . append ( m . group ( delimiter [ 1 ] ) ) index = m . end ( 0 ) last = index handled = True break if handled : continue index += 1 if last < end and self . context_visible_first is True : new_text . append ( text [ last : end ] ) return ' ' . join ( new_text ) | 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 ) exceptions = [ ] for family , type , proto , cname , address in host_addrs : sock = None try : sock = socket . socket ( family = family , type = type , proto = proto ) sock . setblocking ( False ) if local_addr is not None : sock . bind ( local_addr ) yield from loop . sock_connect ( sock , address ) except OSError as exc : if sock is not None : sock . close ( ) exceptions . append ( exc ) else : break else : if len ( exceptions ) == 1 : raise exceptions [ 0 ] model = str ( exceptions [ 0 ] ) if all ( str ( exc ) == model for exc in exceptions ) : raise exceptions [ 0 ] try : from aioxmpp . errors import MultiOSError except ImportError : MultiOSError = OSError exc = MultiOSError ( "could not connect to [{}]:{}" . format ( host , port ) , exceptions ) raise exc elif sock is None : raise ValueError ( "sock must not be None if host and/or port are None" ) else : sock . setblocking ( False ) protocol = protocol_factory ( ) waiter = asyncio . Future ( loop = loop ) transport = STARTTLSTransport ( loop , sock , protocol , ssl_context_factory = ssl_context_factory , waiter = waiter , use_starttls = use_starttls , ** kwargs ) yield from waiter return transport , protocol | 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 self . _loop = 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 . _ssl_context = self . _ssl_context_factory ( self ) if post_handshake_callback is not None : self . _tls_post_handshake_callback = post_handshake_callback self . _waiter = asyncio . Future ( ) self . _waiter . add_done_callback ( self . _waiter_done ) self . _initiate_tls ( ) try : yield from self . _waiter finally : self . _waiter = None | 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 : self . _loop . add_writer ( self . _raw_fd , self . _write_ready ) self . _buffer . extend ( data ) | 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 ( event_field ) is list : for i , value in enumerate ( event_field ) : for key , val in value . items ( ) : if not i == 0 : yield ( "{}_{}" . format ( key , i ) , val ) else : yield ( key , val ) return compose ( _app , add_column_prefix ( prefix ) ) | 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 ) : enc = 'utf-32-be' text = m . group ( 2 ) elif m . group ( 3 ) : enc = 'utf-32-le' text = m . group ( 3 ) elif m . group ( 4 ) : enc = 'utf-16-be' text = m . group ( 4 ) elif m . group ( 5 ) : enc = 'utf-16-le' text = m . group ( 5 ) try : m2 = RE_XML_ENCODE_U . match ( text . decode ( enc ) ) except Exception : m2 = None if m2 : enc = m2 . group ( 2 ) try : codecs . getencoder ( enc ) encode = enc except Exception : pass return encode | 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 attr in self . attributes : value = tree . attrs . get ( attr , '' ) . strip ( ) if value : sel = self . construct_selector ( tree , attr = attr ) attributes . append ( ( value , sel ) ) for child in tree . children : string = str ( child ) . strip ( ) is_comment = isinstance ( child , bs4 . Comment ) if isinstance ( child , bs4 . element . Tag ) : t , b , a , c = self . to_text ( child ) text . extend ( t ) attributes . extend ( a ) comments . extend ( c ) blocks . extend ( b ) elif not isinstance ( child , NON_CONTENT ) and ( not is_comment or self . comments ) : string = str ( child ) . strip ( ) if string : if is_comment : sel = self . construct_selector ( tree ) + '<!--comment comments . append ( ( string , sel ) ) elif capture : text . append ( string ) text . append ( ' ' ) elif self . comments : for child in tree . descendants : if isinstance ( child , bs4 . Comment ) : string = str ( child ) . strip ( ) if string : sel = self . construct_selector ( tree ) + '<!--comment comments . append ( ( string , sel ) ) text = self . store_blocks ( tree , blocks , text , force_root ) if tree . parent is None or force_root : return blocks , attributes , comments else : return text , blocks , attributes , comments | 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' ) ) if self . attributes : for a , desc in attributes : content . append ( filters . SourceText ( a , context + ': ' + desc , encoding , self . type + 'attribute' ) ) for b , desc in blocks : content . append ( filters . SourceText ( b , context + ': ' + desc , encoding , self . type + 'content' ) ) return content | 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_to_list ( current_tuple ) if len ( csv_list ) != len ( fields ) : e = { "input" : "unexpected number of fields {} obtained {} expected" . format ( len ( csv_list ) , len ( fields ) ) } return None , e return { k : v for ( k , v ) in zip ( fields , csv_list ) } , e if fields is None or len ( fields ) == 0 : return fixed_input ( None , "no fields provided, cannot proceed without order" ) return _app | 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 None : return None , e csv_list = [ ] for f in fields : if f in current_tuple : csv_list . append ( current_tuple [ f ] ) else : e . update ( { "output" : "expected field {} not found" . format ( f ) } ) return None , e return _list_to_csv ( csv_list ) , e if fields is None or len ( fields ) == 0 : return fixed_input ( None , "no fields provided, cannot proceed without order" ) return _app | 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 ] , func ( * newargs , ** kwargs ) ) else : return func ( * args , ** kwargs ) return wrapper | 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 ( func ) def wrapper ( * args , ** kwargs ) : depth = [ s . function for s in stack ( ) ] . index ( '<module>' ) f_globals = getframe ( depth ) . f_globals params = signature ( func ) . parameters for i , ( key , val ) in enumerate ( params . items ( ) ) : if not val . kind == Parameter . POSITIONAL_OR_KEYWORD : break try : kwargs . update ( { key : args [ i ] } ) except IndexError : kwargs . setdefault ( key , val . default ) n_chunks = DEFAULT_N_CHUNKS n_processes = MAX_WORKERS if argnames : length = len ( kwargs [ argnames [ 0 ] ] ) if 'numchunk' in kwargs : n_chunks = kwargs . pop ( 'numchunk' ) elif 'timechunk' in kwargs : n_chunks = round ( length / kwargs . pop ( 'timechunk' ) ) elif 'numchunk' in f_globals : n_chunks = f_globals [ 'numchunk' ] elif 'timechunk' in f_globals : n_chunks = round ( length / f_globals [ 'timechunk' ] ) if 'n_processes' in kwargs : n_processes = kwargs . pop ( 'n_processes' ) elif 'n_processes' in f_globals : n_processes = f_globals [ 'n_processes' ] chunks = { } for name in argnames : arg = kwargs . pop ( name ) try : chunks . update ( { name : np . array_split ( arg , n_chunks ) } ) except TypeError : chunks . update ( { name : np . tile ( arg , n_chunks ) } ) futures = [ ] results = [ ] with dc . utils . one_thread_per_process ( ) , Pool ( n_processes ) as p : for i in range ( n_chunks ) : chunk = { key : val [ i ] for key , val in chunks . items ( ) } futures . append ( p . submit ( orgfunc , ** { ** chunk , ** kwargs } ) ) for future in futures : results . append ( future . result ( ) ) if concatfunc is not None : return concatfunc ( results ) try : return xr . concat ( results , 't' ) except TypeError : return np . concatenate ( results , 0 ) return wrapper return _chunk | 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 feed as a collection of CSV files to that directory creating the directory if it does not exist . |
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 . warning ( 'warning: length of data is not power of 2: {}' . format ( len ( data ) ) ) size = int ( len ( data ) / ndivide ) if bin ( size ) . count ( '1' ) != 1. : if overlap_half : logger . warning ( 'warning: ((length of data) / (ndivide+1)) * 2 is not power of 2: {}' . format ( size ) ) else : logger . warning ( 'warning: (length of data) / ndivide is not power of 2: {}' . format ( size ) ) psd = np . zeros ( size ) T = ( size - 1 ) * dt vs = 1 / dt vk_ = fftfreq ( size , dt ) vk = vk_ [ np . where ( vk_ >= 0 ) ] for i in range ( ndivide ) : d = data [ i * step : i * step + size ] if window is None : w = np . ones ( size ) corr = 1.0 else : w = window ( size ) corr = np . mean ( w ** 2 ) psd = psd + 2 * ( np . abs ( fft ( d * w ) ) ) ** 2 / size * dt / corr return vk , psd [ : len ( vk ) ] / ndivide | 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 ] ) ** 2 ) . mean ( ) / 2 ) return dt * np . arange ( 1 , nmax + 1 ) , np . array ( allanvar ) | 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 ( path ) ) except api . exceptions . DoesNotExist : return yield collection if depth == "0" : return if len ( attributes ) == 0 : yield cls ( posixpath . join ( path , cls . user ) , principal = True ) elif len ( attributes ) == 1 : for journal in cls . etesync . list ( ) : if journal . collection . TYPE in ( api . AddressBook . TYPE , api . Calendar . TYPE , api . TaskList . TYPE ) : yield cls ( posixpath . join ( path , journal . uid ) , principal = False ) elif len ( attributes ) == 2 : for item in collection . list ( ) : yield collection . get ( item ) elif len ( attributes ) > 2 : raise RuntimeError ( "Found more than one attribute. Shouldn't happen" ) | 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 , principal = False , tag = props . get ( "tag" ) ) except api . exceptions . DoesNotExist : user_path = posixpath . join ( '/' , cls . user ) collection_name = hashlib . sha256 ( str ( time . time ( ) ) . encode ( ) ) . hexdigest ( ) sane_path = posixpath . join ( user_path , collection_name ) if props . get ( "tag" ) == "VCALENDAR" : inst = api . Calendar . create ( cls . etesync , collection_name , None ) elif props . get ( "tag" ) == "VADDRESSBOOK" : inst = api . AddressBook . create ( cls . etesync , collection_name , None ) else : raise RuntimeError ( "Bad tag." ) inst . save ( ) self = cls ( sane_path , principal = False ) self . set_meta ( props ) if collection : if props . get ( "tag" ) == "VCALENDAR" : collection , = collection items = [ ] for content in ( "vevent" , "vtodo" , "vjournal" ) : items . extend ( getattr ( collection , "%s_list" % content , [ ] ) ) items_by_uid = groupby ( sorted ( items , key = get_uid ) , get_uid ) vobject_items = { } for uid , items in items_by_uid : new_collection = vobject . iCalendar ( ) for item in items : new_collection . add ( item ) href = self . _find_available_file_name ( vobject_items . get ) vobject_items [ href ] = new_collection self . upload_all_nonatomic ( vobject_items ) elif props . get ( "tag" ) == "VADDRESSBOOK" : vobject_items = { } for card in collection : href = self . _find_available_file_name ( vobject_items . get ) vobject_items [ href ] = card self . upload_all_nonatomic ( vobject_items ) return self | 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 item %r in %r" % ( href , self . path ) ) from e last_modified = time . strftime ( "%a, %d %b %Y %H:%M:%S GMT" , time . gmtime ( time . time ( ) ) ) return EteSyncItem ( self , item , href , last_modified = last_modified , etesync_item = etesync_item ) | 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 ( self . collection , content ) etesync_item . save ( ) return self . get ( href ) | 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 ( self . journal . info , key ) return value | 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_begin ) . total_seconds ( ) , self . path ) if self . get_meta ( "tag" ) == "VCALENDAR" : collection = vobject . iCalendar ( ) for item in items : for content in ( "vevent" , "vtodo" , "vjournal" ) : if content in item . contents : for item_part in getattr ( item , "%s_list" % content ) : collection . add ( item_part ) break return collection . serialize ( ) elif self . get_meta ( "tag" ) == "VADDRESSBOOK" : return "" . join ( [ item . serialize ( ) for item in items ] ) return "" | 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 ( ) for journal in cls . etesync . list ( ) : cls . etesync . pull_journal ( journal . uid ) yield if cls . etesync . journal_list_is_dirty ( ) : cls . etesync . sync_journal_list ( ) for journal in cls . etesync . list ( ) : if cls . etesync . journal_is_dirty ( journal . uid ) : cls . etesync . sync_journal ( journal . uid ) cls . etesync = None cls . user = None | 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' return name | 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 ( [ groups [ 'line' ] [ 2 : ] . replace ( '\\\n' , '' ) , self . line_num , self . current_encoding ] ) self . leading = groups [ 'leading_space' ] self . prev_line = self . line_num | 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 = m . groupdict ( ) esc = m . group ( 0 ) value = esc if groups . get ( 'special' ) : value = BACK_SLASH_TRANSLATION [ esc ] elif groups . get ( 'char' ) or groups . get ( 'oct' ) : integer = int ( esc [ 2 : ] , 16 ) if groups . get ( 'char' ) else int ( esc [ 1 : ] , 8 ) if ( ( length < 2 and integer <= 0xFF ) or ( length < 4 and integer <= 0xFFFF ) or ( length >= 4 and integer <= 0x10FFFF ) ) : try : value = chr ( integer ) except Exception : value = ' ' return value return self . norm_nl ( RE_UESC . sub ( replace_unicode , value ) . replace ( '\x00' , '\n' ) ) , encoding | 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 [ size | CURRENT_ENDIAN ] max_value = 2 ** ( size * 8 ) - 1 def replace ( m ) : groups = m . groupdict ( ) esc = m . group ( 0 ) value = esc if groups . get ( 'special' ) : value = BACK_SLASH_TRANSLATION [ esc ] elif groups . get ( 'char' ) : if value . startswith ( '\\x' ) : values = [ int ( x , 16 ) for x in value [ 2 : ] . split ( '\\x' ) ] for i , v in enumerate ( values ) : if v <= max_value : values [ i ] = struct . pack ( pack , v ) else : values [ i ] = b' ' value = b'' . join ( values ) . decode ( encoding , errors = 'replace' ) else : integer = int ( value [ 2 : ] , 16 ) value = chr ( integer ) . encode ( encoding , errors = 'replace' ) . decode ( encoding ) elif groups . get ( 'oct' ) : values = [ int ( x , 8 ) for x in value [ 1 : ] . split ( '\\' ) ] for i , v in enumerate ( values ) : if v <= max_value : values [ i ] = struct . pack ( pack , v ) else : values [ i ] = b' ' value = b'' . join ( values ) . decode ( encoding , errors = 'replace' ) return value return self . norm_nl ( RE_ESC . sub ( replace , value ) ) . replace ( '\x00' , '\n' ) , encoding | 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 : ( 'x' , xcoords [ key ] ) for key in xcoords } ) if ycoords is not None : cube . coords . update ( { key : ( 'y' , ycoords [ key ] ) for key in ycoords } ) if chcoords is not None : cube . coords . update ( { key : ( 'ch' , chcoords [ key ] ) for key in chcoords } ) if datacoords is not None : cube . coords . update ( { key : ( ( 'x' , 'y' , 'ch' ) , datacoords [ key ] ) for key in datacoords } ) if scalarcoords is not None : cube . coords . update ( scalarcoords ) return cube | 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 ) ) : array [ : , ch ] = map_coordinates ( cube . values [ : , : , ch ] , ( ix , iy ) ) return array | 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 ) ) . sum ( dim = 'ch' ) / ( 1 / weight ** 2 ) . sum ( dim = 'ch' ) xcoords = { 'x' : cube . x . values } ycoords = { 'y' : cube . y . values } chcoords = { 'masterid' : np . array ( [ 0 ] ) , 'kidid' : np . array ( [ 0 ] ) , 'kidfq' : np . array ( [ 0 ] ) , 'kidtp' : np . array ( [ 1 ] ) } scalarcoords = { 'coordsys' : cube . coordsys . values , 'datatype' : cube . datatype . values , 'xref' : cube . xref . values , 'yref' : cube . yref . values } return dc . cube ( cont . values , xcoords = xcoords , ycoords = ycoords , chcoords = chcoords , scalarcoords = scalarcoords ) | 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 ) : encoding = 'utf-16' return encoding | 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 ( self . header_check ( f . read ( 1024 ) ) ) f . seek ( 0 ) if encoding is None : encoding = self . _utf_strip_bom ( self . content_check ( f ) ) f . seek ( 0 ) return encoding | 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 : content = self . filter ( source_file , self . default_encoding ) else : raise return content | 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 ( 'None' , b'' , 0 , 0 , 'Unicode cannot be detected.' ) if encoding != BINARY_ENCODE : encoding = self . _verify_encoding ( encoding ) else : raise UnicodeDecodeError ( 'None' , b'' , 0 , 0 , 'Unicode detection is not applied to very large files!' ) return encoding | 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'Under None' ) answer = six . moves . input ( display ) answer = answer . lower ( ) if answer == u'' : log . debug ( u'Under blank' ) return default if answer in yes : log . debug ( u'Must be true' ) return True elif answer in no : log . debug ( u'Must be false' ) return False else : sys . stdout . write ( u'Please answer yes or no only!\n\n' ) sys . stdout . flush ( ) answer = None six . moves . input ( u'Press enter to continue' ) sys . stdout . write ( '\n\n\n\n\n' ) sys . stdout . flush ( ) | 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 None : answer = six . moves . input ( prompt ) if answer == '' and required and default is not None : print ( u'You have to enter a value\n\n' ) six . moves . input ( u'Press enter to continue' ) print ( u'\n\n' ) answer = None continue if answer == u'' and default is not None : answer = default _ans = ask_yes_no ( u'You entered {}, is this ' u'correct?' . format ( answer ) , answer = is_answer_correct ) if _ans : return answer else : answer = None | 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 . PIPE , shell = False ) else : process = subprocess . Popen ( cmd , stdout = subprocess . PIPE , stderr = subprocess . STDOUT , stdin = subprocess . PIPE , shell = False ) return process | 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 [ 0 ] . rstrip ( ) . decode ( encoding , errors = 'replace' ) ) ) return output [ 0 ] . decode ( encoding , errors = 'replace' ) | 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 , encoding ) | 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 , offset , chunk_end ) if m : chunk_end = m . start ( 1 ) chunk = line [ offset : m . start ( 1 ) ] offset = m . end ( 1 ) else : chunk = line [ offset : chunk_end ] offset = chunk_end if chunk and not chunk . isspace ( ) : process . stdin . write ( chunk + b'\n' ) if offset >= end : break return get_process_output ( process , encoding ) | 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.