idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
229,700 | def update ( self , state , tnow ) : self . state = state self . update_time = tnow | update the threat state | 24 | 4 |
229,701 | def cmd_ADSB ( self , args ) : usage = "usage: adsb <set>" if len ( args ) == 0 : print ( usage ) return if args [ 0 ] == "status" : print ( "total threat count: %u active threat count: %u" % ( len ( self . threat_vehicles ) , len ( self . active_threat_ids ) ) ) for id in self . threat_vehicles . keys ( ) : print ( "id: %s distance: %.2f m callsign: %s alt: %.2f" % ( id , self . threat_vehicles [ id ] . distance , self . threat_vehicles [ id ] . state [ 'callsign' ] , self . threat_vehicles [ id ] . state [ 'altitude' ] ) ) elif args [ 0 ] == "set" : self . ADSB_settings . command ( args [ 1 : ] ) else : print ( usage ) | adsb command parser | 210 | 4 |
229,702 | def update_threat_distances ( self , latlonalt ) : for id in self . threat_vehicles . keys ( ) : threat_latlonalt = ( self . threat_vehicles [ id ] . state [ 'lat' ] * 1e-7 , self . threat_vehicles [ id ] . state [ 'lon' ] * 1e-7 , self . threat_vehicles [ id ] . state [ 'altitude' ] ) self . threat_vehicles [ id ] . h_distance = self . get_h_distance ( latlonalt , threat_latlonalt ) self . threat_vehicles [ id ] . v_distance = self . get_v_distance ( latlonalt , threat_latlonalt ) # calculate and set the total distance between threat and vehicle self . threat_vehicles [ id ] . distance = sqrt ( self . threat_vehicles [ id ] . h_distance ** 2 + ( self . threat_vehicles [ id ] . v_distance ) ** 2 ) | update the distance between threats and vehicle | 222 | 7 |
229,703 | def check_threat_timeout ( self ) : for id in self . threat_vehicles . keys ( ) : if self . threat_vehicles [ id ] . update_time == 0 : self . threat_vehicles [ id ] . update_time = self . get_time ( ) dt = self . get_time ( ) - self . threat_vehicles [ id ] . update_time if dt > self . ADSB_settings . timeout : # if the threat has timed out... del self . threat_vehicles [ id ] # remove the threat from the dict for mp in self . module_matching ( 'map*' ) : # remove the threat from the map mp . map . remove_object ( id ) mp . map . remove_object ( id + ":circle" ) # we've modified the dict we're iterating over, so # we'll get any more timed-out threats next time we're # called: return | check and handle threat time out | 203 | 6 |
229,704 | def cmd_gopro_status ( self , args ) : master = self . master if 'GOPRO_HEARTBEAT' in master . messages : print ( master . messages [ 'GOPRO_HEARTBEAT' ] ) else : print ( "No GOPRO_HEARTBEAT messages" ) | show gopro status | 67 | 5 |
229,705 | def on_text_url ( self , event ) : try : import webbrowser except ImportError : return mouse_event = event . GetMouseEvent ( ) if mouse_event . LeftDClick ( ) : url_start = event . GetURLStart ( ) url_end = event . GetURLEnd ( ) url = self . control . GetRange ( url_start , url_end ) try : # attempt to use google-chrome browser_controller = webbrowser . get ( 'google-chrome' ) browser_controller . open_new_tab ( url ) except webbrowser . Error : # use the system configured default browser webbrowser . open_new_tab ( url ) | handle double clicks on URL text | 144 | 6 |
229,706 | def update_channels ( self ) : self . interlock_channel = - 1 self . override_channel = - 1 self . zero_I_channel = - 1 self . no_vtol_channel = - 1 # output channels self . rsc_out_channel = 9 self . fwd_thr_channel = 10 for ch in range ( 1 , 16 ) : option = self . get_mav_param ( "RC%u_OPTION" % ch , 0 ) if option == 32 : self . interlock_channel = ch elif option == 63 : self . override_channel = ch elif option == 64 : self . zero_I_channel = ch elif option == 65 : self . override_channel = ch elif option == 66 : self . no_vtol_channel = ch function = self . get_mav_param ( "SERVO%u_FUNCTION" % ch , 0 ) if function == 32 : self . rsc_out_channel = ch if function == 70 : self . fwd_thr_channel = ch | update which channels provide input | 232 | 5 |
229,707 | def rallyloader ( self ) : if not self . target_system in self . rallyloader_by_sysid : self . rallyloader_by_sysid [ self . target_system ] = mavwp . MAVRallyLoader ( self . settings . target_system , self . settings . target_component ) return self . rallyloader_by_sysid [ self . target_system ] | rally loader by system ID | 84 | 6 |
229,708 | def packet_is_for_me ( self , m ) : if m . target_system != self . master . mav . srcSystem : return False if m . target_component != self . master . mav . srcComponent : return False # if have a sender we can also check the source address: if self . sender is not None : if ( m . get_srcSystem ( ) , m . get_srcComponent ( ) ) != self . sender : return False return True | returns true if this packet is appropriately addressed | 102 | 9 |
229,709 | def _convert_agg_to_wx_image ( agg , bbox ) : if bbox is None : # agg => rgb -> image image = wx . EmptyImage ( int ( agg . width ) , int ( agg . height ) ) image . SetData ( agg . tostring_rgb ( ) ) return image else : # agg => rgba buffer -> bitmap => clipped bitmap => image return wx . ImageFromBitmap ( _WX28_clipped_agg_as_bitmap ( agg , bbox ) ) | Convert the region of the agg buffer bounded by bbox to a wx . Image . If bbox is None the entire buffer is converted . | 117 | 30 |
229,710 | def _convert_agg_to_wx_bitmap ( agg , bbox ) : if bbox is None : # agg => rgba buffer -> bitmap return wx . BitmapFromBufferRGBA ( int ( agg . width ) , int ( agg . height ) , agg . buffer_rgba ( ) ) else : # agg => rgba buffer -> bitmap => clipped bitmap return _WX28_clipped_agg_as_bitmap ( agg , bbox ) | Convert the region of the agg buffer bounded by bbox to a wx . Bitmap . If bbox is None the entire buffer is converted . | 105 | 31 |
229,711 | def _WX28_clipped_agg_as_bitmap ( agg , bbox ) : l , b , width , height = bbox . bounds r = l + width t = b + height srcBmp = wx . BitmapFromBufferRGBA ( int ( agg . width ) , int ( agg . height ) , agg . buffer_rgba ( ) ) srcDC = wx . MemoryDC ( ) srcDC . SelectObject ( srcBmp ) destBmp = wx . EmptyBitmap ( int ( width ) , int ( height ) ) destDC = wx . MemoryDC ( ) destDC . SelectObject ( destBmp ) destDC . BeginDrawing ( ) x = int ( l ) y = int ( int ( agg . height ) - t ) destDC . Blit ( 0 , 0 , int ( width ) , int ( height ) , srcDC , x , y ) destDC . EndDrawing ( ) srcDC . SelectObject ( wx . NullBitmap ) destDC . SelectObject ( wx . NullBitmap ) return destBmp | Convert the region of a the agg buffer bounded by bbox to a wx . Bitmap . | 234 | 21 |
229,712 | def draw ( self , drawDC = None ) : DEBUG_MSG ( "draw()" , 1 , self ) FigureCanvasAgg . draw ( self ) self . bitmap = _convert_agg_to_wx_bitmap ( self . get_renderer ( ) , None ) self . _isDrawn = True self . gui_repaint ( drawDC = drawDC ) | Render the figure using agg . | 84 | 6 |
229,713 | def blit ( self , bbox = None ) : if bbox is None : self . bitmap = _convert_agg_to_wx_bitmap ( self . get_renderer ( ) , None ) self . gui_repaint ( ) return l , b , w , h = bbox . bounds r = l + w t = b + h x = int ( l ) y = int ( self . bitmap . GetHeight ( ) - t ) srcBmp = _convert_agg_to_wx_bitmap ( self . get_renderer ( ) , None ) srcDC = wx . MemoryDC ( ) srcDC . SelectObject ( srcBmp ) destDC = wx . MemoryDC ( ) destDC . SelectObject ( self . bitmap ) destDC . BeginDrawing ( ) destDC . Blit ( x , y , int ( w ) , int ( h ) , srcDC , x , y ) destDC . EndDrawing ( ) destDC . SelectObject ( wx . NullBitmap ) srcDC . SelectObject ( wx . NullBitmap ) self . gui_repaint ( ) | Transfer the region of the agg buffer defined by bbox to the display . If bbox is None the entire buffer is transferred . | 246 | 26 |
229,714 | def cmd_antenna ( self , args ) : if len ( args ) != 2 : if self . gcs_location is None : print ( "GCS location not set" ) else : print ( "GCS location %s" % str ( self . gcs_location ) ) return self . gcs_location = ( float ( args [ 0 ] ) , float ( args [ 1 ] ) ) | set gcs location | 86 | 4 |
229,715 | def passphrase_to_key ( self , passphrase ) : import hashlib h = hashlib . new ( 'sha256' ) h . update ( passphrase ) return h . digest ( ) | convert a passphrase to a 32 byte key | 42 | 10 |
229,716 | def cmd_signing_setup ( self , args ) : if len ( args ) == 0 : print ( "usage: signing setup passphrase" ) return if not self . master . mavlink20 ( ) : print ( "You must be using MAVLink2 for signing" ) return passphrase = args [ 0 ] key = self . passphrase_to_key ( passphrase ) secret_key = [ ] for b in key : secret_key . append ( ord ( b ) ) epoch_offset = 1420070400 now = max ( time . time ( ) , epoch_offset ) initial_timestamp = int ( ( now - epoch_offset ) * 1e5 ) self . master . mav . setup_signing_send ( self . target_system , self . target_component , secret_key , initial_timestamp ) print ( "Sent secret_key" ) self . cmd_signing_key ( [ passphrase ] ) | setup signing key on board | 204 | 5 |
229,717 | def allow_unsigned ( self , mav , msgId ) : if self . allow is None : self . allow = { mavutil . mavlink . MAVLINK_MSG_ID_RADIO : True , mavutil . mavlink . MAVLINK_MSG_ID_RADIO_STATUS : True } if msgId in self . allow : return True if self . settings . allow_unsigned : return True return False | see if an unsigned packet should be allowed | 98 | 8 |
229,718 | def cmd_signing_key ( self , args ) : if len ( args ) == 0 : print ( "usage: signing setup passphrase" ) return if not self . master . mavlink20 ( ) : print ( "You must be using MAVLink2 for signing" ) return passphrase = args [ 0 ] key = self . passphrase_to_key ( passphrase ) self . master . setup_signing ( key , sign_outgoing = True , allow_unsigned_callback = self . allow_unsigned ) print ( "Setup signing key" ) | set signing key on connection | 121 | 5 |
229,719 | def cmd_signing_remove ( self , args ) : if not self . master . mavlink20 ( ) : print ( "You must be using MAVLink2 for signing" ) return self . master . mav . setup_signing_send ( self . target_system , self . target_component , [ 0 ] * 32 , 0 ) self . master . disable_signing ( ) print ( "Removed signing" ) | remove signing from server | 93 | 4 |
229,720 | def cmd_output ( self , args ) : if len ( args ) < 1 or args [ 0 ] == "list" : self . cmd_output_list ( ) elif args [ 0 ] == "add" : if len ( args ) != 2 : print ( "Usage: output add OUTPUT" ) return self . cmd_output_add ( args [ 1 : ] ) elif args [ 0 ] == "remove" : if len ( args ) != 2 : print ( "Usage: output remove OUTPUT" ) return self . cmd_output_remove ( args [ 1 : ] ) elif args [ 0 ] == "sysid" : if len ( args ) != 3 : print ( "Usage: output sysid SYSID OUTPUT" ) return self . cmd_output_sysid ( args [ 1 : ] ) else : print ( "usage: output <list|add|remove|sysid>" ) | handle output commands | 196 | 3 |
229,721 | def cmd_output_add ( self , args ) : device = args [ 0 ] print ( "Adding output %s" % device ) try : conn = mavutil . mavlink_connection ( device , input = False , source_system = self . settings . source_system ) conn . mav . srcComponent = self . settings . source_component except Exception : print ( "Failed to connect to %s" % device ) return self . mpstate . mav_outputs . append ( conn ) try : mp_util . child_fd_list_add ( conn . port . fileno ( ) ) except Exception : pass | add new output | 136 | 3 |
229,722 | def cmd_output_sysid ( self , args ) : sysid = int ( args [ 0 ] ) device = args [ 1 ] print ( "Adding output %s for sysid %u" % ( device , sysid ) ) try : conn = mavutil . mavlink_connection ( device , input = False , source_system = self . settings . source_system ) conn . mav . srcComponent = self . settings . source_component except Exception : print ( "Failed to connect to %s" % device ) return try : mp_util . child_fd_list_add ( conn . port . fileno ( ) ) except Exception : pass if sysid in self . mpstate . sysid_outputs : self . mpstate . sysid_outputs [ sysid ] . close ( ) self . mpstate . sysid_outputs [ sysid ] = conn | add new output for a specific MAVLink sysID | 191 | 11 |
229,723 | def cmd_output_remove ( self , args ) : device = args [ 0 ] for i in range ( len ( self . mpstate . mav_outputs ) ) : conn = self . mpstate . mav_outputs [ i ] if str ( i ) == device or conn . address == device : print ( "Removing output %s" % conn . address ) try : mp_util . child_fd_list_add ( conn . port . fileno ( ) ) except Exception : pass conn . close ( ) self . mpstate . mav_outputs . pop ( i ) return | remove an output | 129 | 3 |
229,724 | def set_center ( self , lat , lon ) : self . object_queue . put ( SlipCenter ( ( lat , lon ) ) ) | set center of view | 32 | 4 |
229,725 | def get_event ( self ) : if self . event_queue . qsize ( ) == 0 : return None evt = self . event_queue . get ( ) while isinstance ( evt , win_layout . WinLayout ) : win_layout . set_layout ( evt , self . set_layout ) if self . event_queue . qsize ( ) == 0 : return None evt = self . event_queue . get ( ) return evt | return next event or None | 99 | 5 |
229,726 | def cmd_layout ( self , args ) : from MAVProxy . modules . lib import win_layout if len ( args ) < 1 : print ( "usage: layout <save|load>" ) return if args [ 0 ] == "load" : win_layout . load_layout ( self . mpstate . settings . vehicle_name ) elif args [ 0 ] == "save" : win_layout . save_layout ( self . mpstate . settings . vehicle_name ) | handle layout command | 102 | 3 |
229,727 | def download_files ( files ) : for ( url , file ) in files : print ( "Downloading %s as %s" % ( url , file ) ) data = download_url ( url ) if data is None : continue try : open ( file , mode = 'wb' ) . write ( data ) except Exception as e : print ( "Failed to save to %s : %s" % ( file , e ) ) | download an array of files | 92 | 5 |
229,728 | def null_term ( str ) : if sys . version_info . major < 3 : return str if isinstance ( str , bytes ) : str = str . decode ( "utf-8" ) idx = str . find ( "\0" ) if idx != - 1 : str = str [ : idx ] return str | null terminate a string for py3 | 70 | 7 |
229,729 | def decode_devid ( devid , pname ) : devid = int ( devid ) if devid == 0 : return bus_type = devid & 0x07 bus = ( devid >> 3 ) & 0x1F address = ( devid >> 8 ) & 0xFF devtype = ( devid >> 16 ) bustypes = { 1 : "I2C" , 2 : "SPI" , 3 : "UAVCAN" , 4 : "SITL" } compass_types = { 0x01 : "DEVTYPE_HMC5883_OLD" , 0x07 : "DEVTYPE_HMC5883" , 0x02 : "DEVTYPE_LSM303D" , 0x04 : "DEVTYPE_AK8963 " , 0x05 : "DEVTYPE_BMM150 " , 0x06 : "DEVTYPE_LSM9DS1" , 0x08 : "DEVTYPE_LIS3MDL" , 0x09 : "DEVTYPE_AK09916" , 0x0A : "DEVTYPE_IST8310" , 0x0B : "DEVTYPE_ICM20948" , 0x0C : "DEVTYPE_MMC3416" , 0x0D : "DEVTYPE_QMC5883L" , 0x0E : "DEVTYPE_MAG3110" , 0x0F : "DEVTYPE_SITL" , 0x10 : "DEVTYPE_IST8308" , 0x11 : "DEVTYPE_RM3100" , } imu_types = { 0x09 : "DEVTYPE_BMI160" , 0x10 : "DEVTYPE_L3G4200D" , 0x11 : "DEVTYPE_ACC_LSM303D" , 0x12 : "DEVTYPE_ACC_BMA180" , 0x13 : "DEVTYPE_ACC_MPU6000" , 0x16 : "DEVTYPE_ACC_MPU9250" , 0x17 : "DEVTYPE_ACC_IIS328DQ" , 0x21 : "DEVTYPE_GYR_MPU6000" , 0x22 : "DEVTYPE_GYR_L3GD20" , 0x24 : "DEVTYPE_GYR_MPU9250" , 0x25 : "DEVTYPE_GYR_I3G4250D" , 0x26 : "DEVTYPE_GYR_LSM9DS1" , 0x27 : "DEVTYPE_INS_ICM20789" , 0x28 : "DEVTYPE_INS_ICM20689" , 0x29 : "DEVTYPE_INS_BMI055" , 0x2A : "DEVTYPE_SITL" , 0x2B : "DEVTYPE_INS_BMI088" , 0x2C : "DEVTYPE_INS_ICM20948" , 0x2D : "DEVTYPE_INS_ICM20648" , 0x2E : "DEVTYPE_INS_ICM20649" , 0x2F : "DEVTYPE_INS_ICM20602" , } decoded_devname = "" if pname . startswith ( "COMPASS" ) : decoded_devname = compass_types . get ( devtype , "UNKNOWN" ) if pname . startswith ( "INS" ) : decoded_devname = imu_types . get ( devtype , "UNKNOWN" ) print ( "%s: bus_type:%s(%u) bus:%u address:%u(0x%x) devtype:%u(0x%x) %s" % ( pname , bustypes . get ( bus_type , "UNKNOWN" ) , bus_type , bus , address , address , devtype , devtype , decoded_devname ) ) | decode one device ID . Used for devid command in mavproxy and MAVExplorer | 849 | 20 |
229,730 | def _authenticate_user_dn ( self , password ) : if self . dn is None : raise self . AuthenticationFailed ( "failed to map the username to a DN." ) try : sticky = self . settings . BIND_AS_AUTHENTICATING_USER self . _bind_as ( self . dn , password , sticky = sticky ) except ldap . INVALID_CREDENTIALS : raise self . AuthenticationFailed ( "user DN/password rejected by LDAP server." ) | Binds to the LDAP server with the user s DN and password . Raises AuthenticationFailed on failure . | 112 | 23 |
229,731 | def _load_user_dn ( self ) : if self . _using_simple_bind_mode ( ) : self . _user_dn = self . _construct_simple_user_dn ( ) else : if self . settings . CACHE_TIMEOUT > 0 : cache_key = valid_cache_key ( "django_auth_ldap.user_dn.{}" . format ( self . _username ) ) self . _user_dn = cache . get_or_set ( cache_key , self . _search_for_user_dn , self . settings . CACHE_TIMEOUT ) else : self . _user_dn = self . _search_for_user_dn ( ) | Populates self . _user_dn with the distinguished name of our user . | 156 | 16 |
229,732 | def _search_for_user_dn ( self ) : search = self . settings . USER_SEARCH if search is None : raise ImproperlyConfigured ( "AUTH_LDAP_USER_SEARCH must be an LDAPSearch instance." ) results = search . execute ( self . connection , { "user" : self . _username } ) if results is not None and len ( results ) == 1 : ( user_dn , self . _user_attrs ) = next ( iter ( results ) ) else : user_dn = None return user_dn | Searches the directory for a user matching AUTH_LDAP_USER_SEARCH . Populates self . _user_dn and self . _user_attrs . | 122 | 36 |
229,733 | def _normalize_group_dns ( self , group_dns ) : if isinstance ( group_dns , LDAPGroupQuery ) : query = group_dns elif isinstance ( group_dns , str ) : query = LDAPGroupQuery ( group_dns ) elif isinstance ( group_dns , ( list , tuple ) ) and len ( group_dns ) > 0 : query = reduce ( operator . or_ , map ( LDAPGroupQuery , group_dns ) ) else : raise ValueError ( group_dns ) return query | Converts one or more group DNs to an LDAPGroupQuery . | 126 | 15 |
229,734 | def _normalize_mirror_settings ( self ) : def malformed_mirror_groups_except ( ) : return ImproperlyConfigured ( "{} must be a collection of group names" . format ( self . settings . _name ( "MIRROR_GROUPS_EXCEPT" ) ) ) def malformed_mirror_groups ( ) : return ImproperlyConfigured ( "{} must be True or a collection of group names" . format ( self . settings . _name ( "MIRROR_GROUPS" ) ) ) mge = self . settings . MIRROR_GROUPS_EXCEPT mg = self . settings . MIRROR_GROUPS if mge is not None : if isinstance ( mge , ( set , frozenset ) ) : pass elif isinstance ( mge , ( list , tuple ) ) : mge = self . settings . MIRROR_GROUPS_EXCEPT = frozenset ( mge ) else : raise malformed_mirror_groups_except ( ) if not all ( isinstance ( value , str ) for value in mge ) : raise malformed_mirror_groups_except ( ) elif mg : warnings . warn ( ConfigurationWarning ( "Ignoring {} in favor of {}" . format ( self . settings . _name ( "MIRROR_GROUPS" ) , self . settings . _name ( "MIRROR_GROUPS_EXCEPT" ) , ) ) ) mg = self . settings . MIRROR_GROUPS = None if mg is not None : if isinstance ( mg , ( bool , set , frozenset ) ) : pass elif isinstance ( mg , ( list , tuple ) ) : mg = self . settings . MIRROR_GROUPS = frozenset ( mg ) else : raise malformed_mirror_groups ( ) if isinstance ( mg , ( set , frozenset ) ) and ( not all ( isinstance ( value , str ) for value in mg ) ) : raise malformed_mirror_groups ( ) | Validates the group mirroring settings and converts them as necessary . | 451 | 13 |
229,735 | def _get_groups ( self ) : if self . _groups is None : self . _groups = _LDAPUserGroups ( self ) return self . _groups | Returns an _LDAPUserGroups object which can determine group membership . | 36 | 15 |
229,736 | def _bind ( self ) : self . _bind_as ( self . settings . BIND_DN , self . settings . BIND_PASSWORD , sticky = True ) | Binds to the LDAP server with AUTH_LDAP_BIND_DN and AUTH_LDAP_BIND_PASSWORD . | 38 | 30 |
229,737 | def _bind_as ( self , bind_dn , bind_password , sticky = False ) : self . _get_connection ( ) . simple_bind_s ( bind_dn , bind_password ) self . _connection_bound = sticky | Binds to the LDAP server with the given credentials . This does not trap exceptions . | 52 | 18 |
229,738 | def _init_group_settings ( self ) : self . _group_type = self . settings . GROUP_TYPE if self . _group_type is None : raise ImproperlyConfigured ( "AUTH_LDAP_GROUP_TYPE must be an LDAPGroupType instance." ) self . _group_search = self . settings . GROUP_SEARCH if self . _group_search is None : raise ImproperlyConfigured ( "AUTH_LDAP_GROUP_SEARCH must be an LDAPSearch instance." ) | Loads the settings we need to deal with groups . | 114 | 11 |
229,739 | def get_group_names ( self ) : if self . _group_names is None : self . _load_cached_attr ( "_group_names" ) if self . _group_names is None : group_infos = self . _get_group_infos ( ) self . _group_names = { self . _group_type . group_name_from_info ( group_info ) for group_info in group_infos } self . _cache_attr ( "_group_names" ) return self . _group_names | Returns the set of Django group names that this user belongs to by virtue of LDAP group memberships . | 119 | 21 |
229,740 | def is_member_of ( self , group_dn ) : is_member = None # Normalize the DN group_dn = group_dn . lower ( ) # If we have self._group_dns, we'll use it. Otherwise, we'll try to # avoid the cost of loading it. if self . _group_dns is None : is_member = self . _group_type . is_member ( self . _ldap_user , group_dn ) if is_member is None : is_member = group_dn in self . get_group_dns ( ) logger . debug ( "{} is{}a member of {}" . format ( self . _ldap_user . dn , is_member and " " or " not " , group_dn ) ) return is_member | Returns true if our user is a member of the given group . | 176 | 13 |
229,741 | def get_ldap ( cls , global_options = None ) : # Apply global LDAP options once if not cls . _ldap_configured and global_options is not None : for opt , value in global_options . items ( ) : ldap . set_option ( opt , value ) cls . _ldap_configured = True return ldap | Returns the configured ldap module . | 82 | 8 |
229,742 | def search_with_additional_terms ( self , term_dict , escape = True ) : term_strings = [ self . filterstr ] for name , value in term_dict . items ( ) : if escape : value = self . ldap . filter . escape_filter_chars ( value ) term_strings . append ( "({}={})" . format ( name , value ) ) filterstr = "(&{})" . format ( "" . join ( term_strings ) ) return self . __class__ ( self . base_dn , self . scope , filterstr , attrlist = self . attrlist ) | Returns a new search object with additional search terms and - ed to the filter string . term_dict maps attribute names to assertion values . If you don t want the values escaped pass escape = False . | 136 | 40 |
229,743 | def user_groups ( self , ldap_user , group_search ) : groups = [ ] try : user_uid = ldap_user . attrs [ "uid" ] [ 0 ] if "gidNumber" in ldap_user . attrs : user_gid = ldap_user . attrs [ "gidNumber" ] [ 0 ] filterstr = "(|(gidNumber={})(memberUid={}))" . format ( self . ldap . filter . escape_filter_chars ( user_gid ) , self . ldap . filter . escape_filter_chars ( user_uid ) , ) else : filterstr = "(memberUid={})" . format ( self . ldap . filter . escape_filter_chars ( user_uid ) ) search = group_search . search_with_additional_term_string ( filterstr ) groups = search . execute ( ldap_user . connection ) except ( KeyError , IndexError ) : pass return groups | Searches for any group that is either the user s primary or contains the user as a member . | 228 | 21 |
229,744 | def is_member ( self , ldap_user , group_dn ) : try : user_uid = ldap_user . attrs [ "uid" ] [ 0 ] try : is_member = ldap_user . connection . compare_s ( group_dn , "memberUid" , user_uid . encode ( ) ) except ( ldap . UNDEFINED_TYPE , ldap . NO_SUCH_ATTRIBUTE ) : is_member = False if not is_member : try : user_gid = ldap_user . attrs [ "gidNumber" ] [ 0 ] is_member = ldap_user . connection . compare_s ( group_dn , "gidNumber" , user_gid . encode ( ) ) except ( ldap . UNDEFINED_TYPE , ldap . NO_SUCH_ATTRIBUTE ) : is_member = False except ( KeyError , IndexError ) : is_member = False return is_member | Returns True if the group is the user s primary group or if the user is listed in the group s memberUid attribute . | 226 | 26 |
229,745 | def user_groups ( self , ldap_user , group_search ) : group_info_map = { } # Maps group_dn to group_info of groups we've found member_dn_set = { ldap_user . dn } # Member DNs to search with next handled_dn_set = set ( ) # Member DNs that we've already searched with while len ( member_dn_set ) > 0 : group_infos = self . find_groups_with_any_member ( member_dn_set , group_search , ldap_user . connection ) new_group_info_map = { info [ 0 ] : info for info in group_infos } group_info_map . update ( new_group_info_map ) handled_dn_set . update ( member_dn_set ) # Get ready for the next iteration. To avoid cycles, we make sure # never to search with the same member DN twice. member_dn_set = set ( new_group_info_map . keys ( ) ) - handled_dn_set return group_info_map . values ( ) | This searches for all of a user s groups from the bottom up . In other words it returns the groups that the user belongs to the groups that those groups belong to etc . Circular references will be detected and pruned . | 245 | 45 |
229,746 | def aggregator ( self ) : if self . connector == self . AND : aggregator = all elif self . connector == self . OR : aggregator = any else : raise ValueError ( self . connector ) return aggregator | Returns a function for aggregating a sequence of sub - results . | 47 | 13 |
229,747 | def _resolve_children ( self , ldap_user , groups ) : for child in self . children : if isinstance ( child , LDAPGroupQuery ) : yield child . resolve ( ldap_user , groups ) else : yield groups . is_member_of ( child ) | Generates the query result for each child . | 63 | 9 |
229,748 | def gather_positions ( tree ) : pos = { 'data-x' : 'r0' , 'data-y' : 'r0' , 'data-z' : 'r0' , 'data-rotate-x' : 'r0' , 'data-rotate-y' : 'r0' , 'data-rotate-z' : 'r0' , 'data-scale' : 'r0' , 'is_path' : False } steps = 0 default_movement = True for step in tree . findall ( 'step' ) : steps += 1 for key in POSITION_ATTRIBS : value = step . get ( key ) if value is not None : # We have a new value default_movement = False # No longer use the default movement pos [ key ] = value elif pos [ key ] and not pos [ key ] . startswith ( 'r' ) : # The old value was absolute and no new value, so stop pos [ key ] = 'r0' # We had no new value, and the old value was a relative # movement, so we just keep moving. if steps == 1 and pos [ 'data-scale' ] == 'r0' : # No scale given for first slide, it needs to start at 1 pos [ 'data-scale' ] = '1' if default_movement and steps != 1 : # No positioning has been given, use default: pos [ 'data-x' ] = 'r%s' % DEFAULT_MOVEMENT if 'data-rotate' in step . attrib : # data-rotate is an alias for data-rotate-z pos [ 'data-rotate-z' ] = step . get ( 'data-rotate' ) del step . attrib [ 'data-rotate' ] if 'hovercraft-path' in step . attrib : # Path given x and y will be calculated from the path default_movement = False # No longer use the default movement pos [ 'is_path' ] = True # Add the path spec pos [ 'path' ] = step . attrib [ 'hovercraft-path' ] yield pos . copy ( ) # And get rid of it for the next step del pos [ 'path' ] else : if 'data-x' in step . attrib or 'data-y' in step . attrib : # No longer using a path pos [ 'is_path' ] = False yield pos . copy ( ) | Makes a list of positions and position commands from the tree | 540 | 12 |
229,749 | def calculate_positions ( positions ) : current_position = { 'data-x' : 0 , 'data-y' : 0 , 'data-z' : 0 , 'data-rotate-x' : 0 , 'data-rotate-y' : 0 , 'data-rotate-z' : 0 , 'data-scale' : 1 , } positer = iter ( positions ) position = next ( positer ) _update_position ( current_position , position ) while True : if 'path' in position : # Start of a new path! path = position [ 'path' ] # Follow the path specification first_point = _pos_to_cord ( current_position ) # Paths that end in Z or z are closed. closed_path = path . strip ( ) [ - 1 ] . upper ( ) == 'Z' path = parse_path ( path ) # Find out how many positions should be calculated: count = 1 last = False deferred_positions = [ ] while True : try : position = next ( positer ) deferred_positions . append ( position ) except StopIteration : last = True # This path goes to the end break if not position . get ( 'is_path' ) or 'path' in position : # The end of the path, or the start of a new one break count += 1 if count < 2 : raise AssertionError ( "The path specification is only used for " "one slide, which makes it pointless." ) if closed_path : # This path closes in on itself. Skip the last part, so that # the first and last step doesn't overlap. endcount = count + 1 else : endcount = count multiplier = ( endcount * DEFAULT_MOVEMENT ) / path . length ( ) offset = path . point ( 0 ) path_iter = iter ( deferred_positions ) for x in range ( count ) : point = path . point ( x / ( endcount - 1 ) ) point = ( ( point - offset ) * multiplier ) + first_point current_position . update ( _coord_to_pos ( point ) ) rotation = _path_angle ( path , x / ( endcount - 1 ) ) current_position [ 'data-rotate-z' ] = rotation yield current_position . copy ( ) try : position = next ( path_iter ) except StopIteration : last = True break _update_position ( current_position , position ) if last : break continue yield current_position . copy ( ) try : position = next ( positer ) except StopIteration : break _update_position ( current_position , position ) | Calculates position information | 563 | 5 |
229,750 | def update_positions ( tree , positions ) : for step , pos in zip ( tree . findall ( 'step' ) , positions ) : for key in sorted ( pos ) : value = pos . get ( key ) if key . endswith ( "-rel" ) : abs_key = key [ : key . index ( "-rel" ) ] if value is not None : els = tree . findall ( ".//*[@id='" + value + "']" ) for el in els : pos [ abs_key ] = num ( el . get ( abs_key ) ) + pos . get ( abs_key ) step . attrib [ abs_key ] = str ( pos . get ( abs_key ) ) else : step . attrib [ key ] = str ( pos [ key ] ) if 'hovercraft-path' in step . attrib : del step . attrib [ 'hovercraft-path' ] | Updates the tree with new positions | 201 | 7 |
229,751 | def position_slides ( tree ) : positions = gather_positions ( tree ) positions = calculate_positions ( positions ) update_positions ( tree , positions ) | Position the slides in the tree | 36 | 6 |
229,752 | def copy_node ( node ) : element = node . makeelement ( node . tag ) element . text = node . text element . tail = node . tail for key , value in node . items ( ) : element . set ( key , value ) return element | Makes a copy of a node with the same attributes and text but no children . | 54 | 17 |
229,753 | def copy_resource ( self , resource , targetdir ) : final_path = resource . final_path ( ) if final_path [ 0 ] == '/' or ( ':' in final_path ) or ( '?' in final_path ) : # Absolute path or URI: Do nothing return source_path = self . get_source_path ( resource ) if resource . resource_type == DIRECTORY_RESOURCE : for file_path in glob . iglob ( os . path . join ( source_path , '**' ) , recursive = True ) : if os . path . isdir ( file_path ) : continue rest_target_path = file_path [ len ( source_path ) + 1 : ] target_path = os . path . join ( targetdir , final_path , rest_target_path ) # Don't yield the result, we don't monitor these. self . _copy_file ( file_path , target_path ) else : target_path = os . path . join ( targetdir , final_path ) yield self . _copy_file ( source_path , target_path ) | Copies a resource file and returns the source path for monitoring | 240 | 12 |
229,754 | def generate ( args ) : source_files = { args . presentation } # Parse the template info template_info = Template ( args . template ) if args . css : presentation_dir = os . path . split ( args . presentation ) [ 0 ] target_path = os . path . relpath ( args . css , presentation_dir ) template_info . add_resource ( args . css , CSS_RESOURCE , target = target_path , extra_info = 'all' ) source_files . add ( args . css ) if args . js : presentation_dir = os . path . split ( args . presentation ) [ 0 ] target_path = os . path . relpath ( args . js , presentation_dir ) template_info . add_resource ( args . js , JS_RESOURCE , target = target_path , extra_info = JS_POSITION_BODY ) source_files . add ( args . js ) # Make the resulting HTML htmldata , dependencies = rst2html ( args . presentation , template_info , args . auto_console , args . skip_help , args . skip_notes , args . mathjax , args . slide_numbers ) source_files . update ( dependencies ) # Write the HTML out if not os . path . exists ( args . targetdir ) : os . makedirs ( args . targetdir ) with open ( os . path . join ( args . targetdir , 'index.html' ) , 'wb' ) as outfile : outfile . write ( htmldata ) # Copy supporting files source_files . update ( template_info . copy_resources ( args . targetdir ) ) # Copy images from the source: sourcedir = os . path . split ( os . path . abspath ( args . presentation ) ) [ 0 ] tree = html . fromstring ( htmldata ) for image in tree . iterdescendants ( 'img' ) : filename = image . attrib [ 'src' ] source_files . add ( copy_resource ( filename , sourcedir , args . targetdir ) ) RE_CSS_URL = re . compile ( br"""url\(['"]?(.*?)['"]?[\)\?\#]""" ) # Copy any files referenced by url() in the css-files: for resource in template_info . resources : if resource . resource_type != CSS_RESOURCE : continue # path in CSS is relative to CSS file; construct source/dest accordingly css_base = template_info . template_root if resource . is_in_template else sourcedir css_sourcedir = os . path . dirname ( os . path . join ( css_base , resource . filepath ) ) css_targetdir = os . path . dirname ( os . path . join ( args . targetdir , resource . final_path ( ) ) ) uris = RE_CSS_URL . findall ( template_info . read_data ( resource ) ) uris = [ uri . decode ( ) for uri in uris ] if resource . is_in_template and template_info . builtin_template : for filename in uris : template_info . add_resource ( filename , OTHER_RESOURCE , target = css_targetdir , is_in_template = True ) else : for filename in uris : source_files . add ( copy_resource ( filename , css_sourcedir , css_targetdir ) ) # All done! return { os . path . abspath ( f ) for f in source_files if f } | Generates the presentation and returns a list of files used | 774 | 11 |
229,755 | def port ( self , port = None ) : if ( port is None ) or ( port == self . __port ) : return self . __port # when port change ensure old socket is close self . close ( ) # valid port ? if 0 < int ( port ) < 65536 : self . __port = int ( port ) return self . __port else : return None | Get or set TCP port | 78 | 5 |
229,756 | def unit_id ( self , unit_id = None ) : if unit_id is None : return self . __unit_id if 0 <= int ( unit_id ) < 256 : self . __unit_id = int ( unit_id ) return self . __unit_id else : return None | Get or set unit ID field | 64 | 6 |
229,757 | def timeout ( self , timeout = None ) : if timeout is None : return self . __timeout if 0 < float ( timeout ) < 3600 : self . __timeout = float ( timeout ) return self . __timeout else : return None | Get or set timeout field | 49 | 5 |
229,758 | def debug ( self , state = None ) : if state is None : return self . __debug self . __debug = bool ( state ) return self . __debug | Get or set debug mode | 34 | 5 |
229,759 | def auto_open ( self , state = None ) : if state is None : return self . __auto_open self . __auto_open = bool ( state ) return self . __auto_open | Get or set automatic TCP connect mode | 42 | 7 |
229,760 | def _can_read ( self ) : if self . __sock is None : return None if select . select ( [ self . __sock ] , [ ] , [ ] , self . __timeout ) [ 0 ] : return True else : self . __last_error = const . MB_TIMEOUT_ERR self . __debug_msg ( 'timeout error' ) self . close ( ) return None | Wait data available for socket read | 87 | 6 |
229,761 | def _send ( self , data ) : # check link if self . __sock is None : self . __debug_msg ( 'call _send on close socket' ) return None # send data_l = len ( data ) try : send_l = self . __sock . send ( data ) except socket . error : send_l = None # handle send error if ( send_l is None ) or ( send_l != data_l ) : self . __last_error = const . MB_SEND_ERR self . __debug_msg ( '_send error' ) self . close ( ) return None else : return send_l | Send data over current socket | 140 | 5 |
229,762 | def _recv ( self , max_size ) : # wait for read if not self . _can_read ( ) : self . close ( ) return None # recv try : r_buffer = self . __sock . recv ( max_size ) except socket . error : r_buffer = None # handle recv error if not r_buffer : self . __last_error = const . MB_RECV_ERR self . __debug_msg ( '_recv error' ) self . close ( ) return None return r_buffer | Receive data over current socket | 118 | 6 |
229,763 | def _send_mbus ( self , frame ) : # for auto_open mode, check TCP and open if need if self . __auto_open and not self . is_open ( ) : self . open ( ) # send request bytes_send = self . _send ( frame ) if bytes_send : if self . __debug : self . _pretty_dump ( 'Tx' , frame ) return bytes_send else : return None | Send modbus frame | 93 | 4 |
229,764 | def _wc_hard_wrap ( line , length ) : chars = [ ] chars_len = 0 for char in line : char_len = wcwidth ( char ) if chars_len + char_len > length : yield "" . join ( chars ) chars = [ ] chars_len = 0 chars . append ( char ) chars_len += char_len if chars : yield "" . join ( chars ) | Wrap text to length characters breaking when target length is reached taking into account character width . | 88 | 18 |
229,765 | def wc_wrap ( text , length ) : line_words = [ ] line_len = 0 words = re . split ( r"\s+" , text . strip ( ) ) for word in words : word_len = wcswidth ( word ) if line_words and line_len + word_len > length : line = " " . join ( line_words ) if line_len <= length : yield line else : yield from _wc_hard_wrap ( line , length ) line_words = [ ] line_len = 0 line_words . append ( word ) line_len += word_len + 1 # add 1 to account for space between words if line_words : line = " " . join ( line_words ) if line_len <= length : yield line else : yield from _wc_hard_wrap ( line , length ) | Wrap text to given length breaking on whitespace and taking into account character width . | 186 | 17 |
229,766 | def trunc ( text , length ) : if length < 1 : raise ValueError ( "length should be 1 or larger" ) # Remove whitespace first so no unneccesary truncation is done. text = text . strip ( ) text_length = wcswidth ( text ) if text_length <= length : return text # We cannot just remove n characters from the end since we don't know how # wide these characters are and how it will affect text length. # Use wcwidth to determine how many characters need to be truncated. chars_to_truncate = 0 trunc_length = 0 for char in reversed ( text ) : chars_to_truncate += 1 trunc_length += wcwidth ( char ) if text_length - trunc_length <= length : break # Additional char to make room for elipsis n = chars_to_truncate + 1 return text [ : - n ] . strip ( ) + '…' | Truncates text to given length taking into account wide characters . | 204 | 13 |
229,767 | def pad ( text , length ) : text_length = wcswidth ( text ) if text_length < length : return text + ' ' * ( length - text_length ) return text | Pads text to given length taking into account wide characters . | 41 | 12 |
229,768 | def fit_text ( text , length ) : text_length = wcswidth ( text ) if text_length > length : return trunc ( text , length ) if text_length < length : return pad ( text , length ) return text | Makes text fit the given length by padding or truncating it . | 51 | 14 |
229,769 | def _get_error_message ( response ) : try : data = response . json ( ) if "error_description" in data : return data [ 'error_description' ] if "error" in data : return data [ 'error' ] except Exception : pass return "Unknown error" | Attempt to extract an error message from response body | 61 | 9 |
229,770 | def _get_next_path ( headers ) : links = headers . get ( 'Link' , '' ) matches = re . match ( '<([^>]+)>; rel="next"' , links ) if matches : parsed = urlparse ( matches . group ( 1 ) ) return "?" . join ( [ parsed . path , parsed . query ] ) | Given timeline response headers returns the path to the next batch | 75 | 11 |
229,771 | def select_previous ( self ) : self . footer . clear_message ( ) if self . selected == 0 : self . footer . draw_message ( "Cannot move beyond first toot." , Color . GREEN ) return old_index = self . selected new_index = self . selected - 1 self . selected = new_index self . redraw_after_selection_change ( old_index , new_index ) | Move to the previous status in the timeline . | 92 | 9 |
229,772 | def select_next ( self ) : self . footer . clear_message ( ) old_index = self . selected new_index = self . selected + 1 # Load more statuses if no more are available if self . selected + 1 >= len ( self . statuses ) : self . fetch_next ( ) self . left . draw_statuses ( self . statuses , self . selected , new_index - 1 ) self . draw_footer_status ( ) self . selected = new_index self . redraw_after_selection_change ( old_index , new_index ) | Move to the next status in the timeline . | 126 | 9 |
229,773 | def full_redraw ( self ) : self . left . draw_statuses ( self . statuses , self . selected ) self . right . draw ( self . get_selected_status ( ) ) self . header . draw ( self . user ) self . draw_footer_status ( ) | Perform a full redraw of the UI . | 63 | 10 |
229,774 | def size_as_drawn ( lines , screen_width ) : y = 0 x = 0 for line in lines : wrapped = list ( wc_wrap ( line , screen_width ) ) if len ( wrapped ) > 0 : for wrapped_line in wrapped : x = len ( wrapped_line ) y += 1 else : x = 0 y += 1 return y - 1 , x - 1 if x != 0 else 0 | Get the bottom - right corner of some text as would be drawn by draw_lines | 89 | 17 |
229,775 | def _find_account ( app , user , account_name ) : if not account_name : raise ConsoleError ( "Empty account name given" ) accounts = api . search_accounts ( app , user , account_name ) if account_name [ 0 ] == "@" : account_name = account_name [ 1 : ] for account in accounts : if account [ 'acct' ] == account_name : return account raise ConsoleError ( "Account not found" ) | For a given account name returns the Account object . | 101 | 10 |
229,776 | def add_username ( user , apps ) : if not user : return None apps = [ a for a in apps if a . instance == user . instance ] if not apps : return None from toot . api import verify_credentials creds = verify_credentials ( apps . pop ( ) , user ) return User ( user . instance , creds [ 'username' ] , user . access_token ) | When using broser login username was not stored so look it up | 88 | 13 |
229,777 | def get_text ( html ) : # Ignore warnings made by BeautifulSoup, if passed something that looks like # a file (e.g. a dot which matches current dict), it will warn that the file # should be opened instead of passing a filename. with warnings . catch_warnings ( ) : warnings . simplefilter ( "ignore" ) text = BeautifulSoup ( html . replace ( ''' , "'" ) , "html.parser" ) . get_text ( ) return unicodedata . normalize ( 'NFKC' , text ) | Converts html to text strips all tags . | 121 | 9 |
229,778 | def parse_html ( html ) : paragraphs = re . split ( "</?p[^>]*>" , html ) # Convert <br>s to line breaks and remove empty paragraphs paragraphs = [ re . split ( "<br */?>" , p ) for p in paragraphs if p ] # Convert each line in each paragraph to plain text: return [ [ get_text ( l ) for l in p ] for p in paragraphs ] | Attempt to convert html to plain text while keeping line breaks . Returns a list of paragraphs each being a list of lines . | 91 | 24 |
229,779 | def format_content ( content ) : paragraphs = parse_html ( content ) first = True for paragraph in paragraphs : if not first : yield "" for line in paragraph : yield line first = False | Given a Status contents in HTML converts it into lines of plain text . | 40 | 14 |
229,780 | def multiline_input ( ) : lines = [ ] while True : try : lines . append ( input ( ) ) except EOFError : break return "\n" . join ( lines ) . strip ( ) | Lets user input multiple lines of text terminated by EOF . | 45 | 13 |
229,781 | def to_dict ( self ) : return { "name" : self . table_name , "kind" : self . table_kind , "data" : [ r . to_dict ( ) for r in self ] } | Converts the table to a dict . | 48 | 8 |
229,782 | def to_datetime ( value ) : if value is None : return None if isinstance ( value , six . integer_types ) : return parser . parse ( value ) return parser . isoparse ( value ) | Converts a string to a datetime . | 45 | 9 |
229,783 | def to_timedelta ( value ) : if value is None : return None if isinstance ( value , ( six . integer_types , float ) ) : return timedelta ( microseconds = ( float ( value ) / 10 ) ) match = _TIMESPAN_PATTERN . match ( value ) if match : if match . group ( 1 ) == "-" : factor = - 1 else : factor = 1 return factor * timedelta ( days = int ( match . group ( "d" ) or 0 ) , hours = int ( match . group ( "h" ) ) , minutes = int ( match . group ( "m" ) ) , seconds = float ( match . group ( "s" ) ) , ) else : raise ValueError ( "Timespan value '{}' cannot be decoded" . format ( value ) ) | Converts a string to a timedelta . | 180 | 9 |
229,784 | def acquire_authorization_header ( self ) : try : return self . _acquire_authorization_header ( ) except AdalError as error : if self . _authentication_method is AuthenticationMethod . aad_username_password : kwargs = { "username" : self . _username , "client_id" : self . _client_id } elif self . _authentication_method is AuthenticationMethod . aad_application_key : kwargs = { "client_id" : self . _client_id } elif self . _authentication_method is AuthenticationMethod . aad_device_login : kwargs = { "client_id" : self . _client_id } elif self . _authentication_method is AuthenticationMethod . aad_application_certificate : kwargs = { "client_id" : self . _client_id , "thumbprint" : self . _thumbprint } else : raise error kwargs [ "resource" ] = self . _kusto_cluster kwargs [ "authority" ] = self . _adal_context . authority . url raise KustoAuthenticationError ( self . _authentication_method . value , error , * * kwargs ) | Acquire tokens from AAD . | 275 | 7 |
229,785 | def _execute ( self , endpoint , database , query , default_timeout , properties = None ) : request_payload = { "db" : database , "csl" : query } if properties : request_payload [ "properties" ] = properties . to_json ( ) request_headers = { "Accept" : "application/json" , "Accept-Encoding" : "gzip,deflate" , "Content-Type" : "application/json; charset=utf-8" , "x-ms-client-version" : "Kusto.Python.Client:" + VERSION , "x-ms-client-request-id" : "KPC.execute;" + str ( uuid . uuid4 ( ) ) , } if self . _auth_provider : request_headers [ "Authorization" ] = self . _auth_provider . acquire_authorization_header ( ) timeout = self . _get_timeout ( properties , default_timeout ) response = self . _session . post ( endpoint , headers = request_headers , json = request_payload , timeout = timeout . seconds ) if response . status_code == 200 : if endpoint . endswith ( "v2/rest/query" ) : return KustoResponseDataSetV2 ( response . json ( ) ) return KustoResponseDataSetV1 ( response . json ( ) ) raise KustoServiceError ( [ response . json ( ) ] , response ) | Executes given query against this client | 319 | 7 |
229,786 | def set_option ( self , name , value ) : _assert_value_is_valid ( name ) self . _options [ name ] = value | Sets an option s value | 32 | 6 |
229,787 | def parse ( cls , uri ) : match = _URI_FORMAT . search ( uri ) return cls ( match . group ( 1 ) , match . group ( 2 ) , match . group ( 3 ) , match . group ( 4 ) ) | Parses uri into a ResourceUri object | 55 | 11 |
229,788 | def get_mapping_format ( self ) : if self . format == DataFormat . json or self . format == DataFormat . avro : return self . format . name else : return DataFormat . csv . name | Dictating the corresponding mapping to the format . | 47 | 10 |
229,789 | def getAtomChars ( t ) : s = c_char_p ( ) if PL_get_atom_chars ( t , byref ( s ) ) : return s . value else : raise InvalidTypeError ( "atom" ) | If t is an atom return it as a string otherwise raise InvalidTypeError . | 53 | 16 |
229,790 | def getBool ( t ) : b = c_int ( ) if PL_get_long ( t , byref ( b ) ) : return bool ( b . value ) else : raise InvalidTypeError ( "bool" ) | If t is of type bool return it otherwise raise InvalidTypeError . | 49 | 14 |
229,791 | def getLong ( t ) : i = c_long ( ) if PL_get_long ( t , byref ( i ) ) : return i . value else : raise InvalidTypeError ( "long" ) | If t is of type long return it otherwise raise InvalidTypeError . | 45 | 14 |
229,792 | def getFloat ( t ) : d = c_double ( ) if PL_get_float ( t , byref ( d ) ) : return d . value else : raise InvalidTypeError ( "float" ) | If t is of type float return it otherwise raise InvalidTypeError . | 45 | 14 |
229,793 | def getString ( t ) : slen = c_int ( ) s = c_char_p ( ) if PL_get_string_chars ( t , byref ( s ) , byref ( slen ) ) : return s . value else : raise InvalidTypeError ( "string" ) | If t is of type string return it otherwise raise InvalidTypeError . | 65 | 14 |
229,794 | def getList ( x ) : t = PL_copy_term_ref ( x ) head = PL_new_term_ref ( ) result = [ ] while PL_get_list ( t , head , t ) : result . append ( getTerm ( head ) ) head = PL_new_term_ref ( ) return result | Return t as a list . | 71 | 6 |
229,795 | def fromTerm ( cls , term ) : if isinstance ( term , Term ) : term = term . handle elif not isinstance ( term , ( c_void_p , int ) ) : raise ArgumentTypeError ( ( str ( Term ) , str ( c_void_p ) ) , str ( type ( term ) ) ) a = atom_t ( ) if PL_get_atom ( term , byref ( a ) ) : return cls ( a . value ) | Create an atom from a Term or term handle . | 103 | 10 |
229,796 | def fromTerm ( cls , term ) : if isinstance ( term , Term ) : term = term . handle elif not isinstance ( term , ( c_void_p , int ) ) : raise ArgumentTypeError ( ( str ( Term ) , str ( int ) ) , str ( type ( term ) ) ) f = functor_t ( ) if PL_get_functor ( term , byref ( f ) ) : # get args args = [ ] arity = PL_functor_arity ( f . value ) # let's have all args be consecutive a0 = PL_new_term_refs ( arity ) for i , a in enumerate ( range ( 1 , arity + 1 ) ) : if PL_get_arg ( a , term , a0 + i ) : args . append ( getTerm ( a0 + i ) ) return cls ( f . value , args = args , a0 = a0 ) | Create a functor from a Term or term handle . | 204 | 11 |
229,797 | def _findSwiplWin ( ) : import re dllNames = ( 'swipl.dll' , 'libswipl.dll' ) # First try: check the usual installation path (this is faster but # hardcoded) programFiles = os . getenv ( 'ProgramFiles' ) paths = [ os . path . join ( programFiles , r'pl\bin' , dllName ) for dllName in dllNames ] for path in paths : if os . path . exists ( path ) : return ( path , None ) # Second try: use the find_library path = _findSwiplPathFromFindLib ( ) if path is not None and os . path . exists ( path ) : return ( path , None ) # Third try: use reg.exe to find the installation path in the registry # (reg should be installed in all Windows XPs) try : cmd = Popen ( [ 'reg' , 'query' , r'HKEY_LOCAL_MACHINE\Software\SWI\Prolog' , '/v' , 'home' ] , stdout = PIPE ) ret = cmd . communicate ( ) # Result is like: # ! REG.EXE VERSION 3.0 # # HKEY_LOCAL_MACHINE\Software\SWI\Prolog # home REG_SZ C:\Program Files\pl # (Note: spaces may be \t or spaces in the output) ret = ret [ 0 ] . splitlines ( ) ret = [ line . decode ( "utf-8" ) for line in ret if len ( line ) > 0 ] pattern = re . compile ( '[^h]*home[^R]*REG_SZ( |\t)*(.*)$' ) match = pattern . match ( ret [ - 1 ] ) if match is not None : path = match . group ( 2 ) paths = [ os . path . join ( path , 'bin' , dllName ) for dllName in dllNames ] for path in paths : if os . path . exists ( path ) : return ( path , None ) except OSError : # reg.exe not found? Weird... pass # May the exec is on path? ( path , swiHome ) = _findSwiplFromExec ( ) if path is not None : return ( path , swiHome ) # Last try: maybe it is in the current dir for dllName in dllNames : if os . path . exists ( dllName ) : return ( dllName , None ) return ( None , None ) | This function uses several heuristics to gues where SWI - Prolog is installed in Windows . It always returns None as the path of the resource file because in Windows the way to find it is more robust so the SWI - Prolog DLL is always able to find it . | 550 | 59 |
229,798 | def _findSwiplLin ( ) : # Maybe the exec is on path? ( path , swiHome ) = _findSwiplFromExec ( ) if path is not None : return ( path , swiHome ) # If it is not, use find_library path = _findSwiplPathFromFindLib ( ) if path is not None : return ( path , swiHome ) # Our last try: some hardcoded paths. paths = [ '/lib' , '/usr/lib' , '/usr/local/lib' , '.' , './lib' ] names = [ 'libswipl.so' , 'libpl.so' ] path = None for name in names : for try_ in paths : try_ = os . path . join ( try_ , name ) if os . path . exists ( try_ ) : path = try_ break if path is not None : return ( path , swiHome ) return ( None , None ) | This function uses several heuristics to guess where SWI - Prolog is installed in Linuxes . | 204 | 21 |
229,799 | def _findSwiplDar ( ) : # If the exec is in path ( path , swiHome ) = _findSwiplFromExec ( ) if path is not None : return ( path , swiHome ) # If it is not, use find_library path = _findSwiplPathFromFindLib ( ) if path is not None : return ( path , swiHome ) # Last guess, searching for the file paths = [ '.' , './lib' , '/usr/lib/' , '/usr/local/lib' , '/opt/local/lib' ] names = [ 'libswipl.dylib' , 'libpl.dylib' ] for name in names : for path in paths : path = os . path . join ( path , name ) if os . path . exists ( path ) : return ( path , None ) return ( None , None ) | This function uses several heuristics to guess where SWI - Prolog is installed in MacOS . | 186 | 21 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.