idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
20,400
def valid_ip_prefix ( ip_prefix ) : try : ip_prefix = ipaddress . ip_network ( ip_prefix ) except ValueError : return False else : if ip_prefix . version == 4 and ip_prefix . max_prefixlen != 32 : return False if ip_prefix . version == 6 and ip_prefix . max_prefixlen != 128 : return False return True
Perform a sanity check on ip_prefix .
20,401
def get_ip_prefixes_from_config ( config , services , ip_version ) : ip_prefixes = set ( ) for service in services : ip_prefix = ipaddress . ip_network ( config . get ( service , 'ip_prefix' ) ) if ip_prefix . version == ip_version : ip_prefixes . add ( ip_prefix . with_prefixlen ) return ip_prefixes
Build a set of IP prefixes found in service configuration files .
20,402
def ip_prefixes_sanity_check ( config , bird_configuration ) : for ip_version in bird_configuration : modify_ip_prefixes ( config , bird_configuration [ ip_version ] [ 'config_file' ] , bird_configuration [ ip_version ] [ 'variable_name' ] , bird_configuration [ ip_version ] [ 'dummy_ip_prefix' ] , bird_configuration [...
Sanity check on IP prefixes .
20,403
def modify_ip_prefixes ( config , config_file , variable_name , dummy_ip_prefix , reconfigure_cmd , keep_changes , changes_counter , ip_version ) : log = logging . getLogger ( PROGRAM_NAME ) services = config . sections ( ) services . remove ( 'daemon' ) update_bird_conf = False try : ip_prefixes_in_bird = get_ip_prefi...
Modify IP prefixes in Bird configuration .
20,404
def load_configuration ( config_file , config_dir , service_file ) : config_files = [ config_file ] config = configparser . ConfigParser ( ) config . read_dict ( DEFAULT_OPTIONS ) if not os . path . isfile ( config_file ) : raise ValueError ( "{f} configuration file either isn't readable or " "doesn't exist" . format (...
Build configuration objects .
20,405
def configuration_check ( config ) : log_level = config . get ( 'daemon' , 'loglevel' ) num_level = getattr ( logging , log_level . upper ( ) , None ) pidfile = config . get ( 'daemon' , 'pidfile' ) if not os . path . isdir ( os . path . dirname ( pidfile ) ) : raise ValueError ( "{d} doesn't exit" . format ( d = os . ...
Perform a sanity check on configuration .
20,406
def build_bird_configuration ( config ) : bird_configuration = { } if config . getboolean ( 'daemon' , 'ipv4' ) : if os . path . islink ( config . get ( 'daemon' , 'bird_conf' ) ) : config_file = os . path . realpath ( config . get ( 'daemon' , 'bird_conf' ) ) print ( "'bird_conf' is set to a symbolic link ({s} -> {d},...
Build bird configuration structure .
20,407
def get_variable_name_from_bird ( bird_conf ) : bird_variable_pattern = re . compile ( r , re . VERBOSE ) with open ( bird_conf , 'r' ) as content : for line in content . readlines ( ) : variable_match = bird_variable_pattern . search ( line ) if variable_match : return variable_match . group ( 'name' ) return None
Return the variable name set in Bird configuration .
20,408
def create_bird_config_files ( bird_configuration ) : for ip_version in bird_configuration : config_file = bird_configuration [ ip_version ] [ 'config_file' ] try : touch ( config_file ) except OSError as exc : raise ValueError ( "failed to create {f}:{e}" . format ( f = config_file , e = exc ) ) if bird_configuration ...
Create bird configuration files per IP version .
20,409
def running ( processid ) : try : os . kill ( processid , 0 ) except OverflowError as exc : print ( "checking validity of pid ({p}) failed with: {e}" . format ( p = processid , e = exc ) ) sys . exit ( 1 ) except OSError : return False else : return True
Check the validity of a process ID .
20,410
def get_ip_prefixes_from_bird ( filename ) : prefixes = [ ] with open ( filename , 'r' ) as bird_conf : lines = bird_conf . read ( ) for line in lines . splitlines ( ) : line = line . strip ( ', ' ) if valid_ip_prefix ( line ) : prefixes . append ( line ) return prefixes
Build a list of IP prefixes found in Bird configuration .
20,411
def reconfigure_bird ( cmd ) : log = logging . getLogger ( PROGRAM_NAME ) cmd = shlex . split ( cmd ) log . info ( "reconfiguring BIRD by running %s" , ' ' . join ( cmd ) ) try : output = subprocess . check_output ( cmd , timeout = 2 , stderr = subprocess . STDOUT , universal_newlines = True , ) except subprocess . Tim...
Reconfigure BIRD daemon .
20,412
def write_temp_bird_conf ( dummy_ip_prefix , config_file , variable_name , prefixes ) : log = logging . getLogger ( PROGRAM_NAME ) comment = ( "# {i} is a dummy IP Prefix. It should NOT be used and " "REMOVED from the constant." . format ( i = dummy_ip_prefix ) ) tm_file = os . path . join ( os . path . dirname ( confi...
Write in a temporary file the list of IP - Prefixes .
20,413
def archive_bird_conf ( config_file , changes_counter ) : log = logging . getLogger ( PROGRAM_NAME ) history_dir = os . path . join ( os . path . dirname ( config_file ) , 'history' ) dst = os . path . join ( history_dir , str ( time . time ( ) ) ) log . debug ( "coping %s to %s" , config_file , dst ) history = [ x for...
Keep a history of Bird configuration files .
20,414
def update_pidfile ( pidfile ) : try : with open ( pidfile , mode = 'r' ) as _file : pid = _file . read ( 1024 ) . rstrip ( ) try : pid = int ( pid ) except ValueError : print ( "cleaning stale pidfile with invalid data:'{}'" . format ( pid ) ) write_pid ( pidfile ) else : if running ( pid ) : sys . exit ( "process {} ...
Update pidfile .
20,415
def write_pid ( pidfile ) : pid = str ( os . getpid ( ) ) try : with open ( pidfile , mode = 'w' ) as _file : print ( "writing processID {p} to pidfile" . format ( p = pid ) ) _file . write ( pid ) except OSError as exc : sys . exit ( "failed to write pidfile:{e}" . format ( e = exc ) )
Write processID to the pidfile .
20,416
def shutdown ( pidfile , signalnb = None , frame = None ) : log = logging . getLogger ( PROGRAM_NAME ) log . info ( "received %s at %s" , signalnb , frame ) log . info ( "going to remove pidfile %s" , pidfile ) os . unlink ( pidfile ) log . info ( 'shutdown is complete' ) sys . exit ( 0 )
Clean up pidfile upon shutdown .
20,417
def setup_logger ( config ) : logger = logging . getLogger ( PROGRAM_NAME ) num_level = getattr ( logging , config . get ( 'daemon' , 'loglevel' ) . upper ( ) , None ) logger . setLevel ( num_level ) lengths = [ ] for section in config : lengths . append ( len ( section ) ) width = sorted ( lengths ) [ - 1 ] + 1 def lo...
Configure the logging environment .
20,418
def run_custom_bird_reconfigure ( operation ) : log = logging . getLogger ( PROGRAM_NAME ) if isinstance ( operation , AddOperation ) : status = 'up' else : status = 'down' cmd = shlex . split ( operation . bird_reconfigure_cmd + " " + status ) log . info ( "reconfiguring BIRD by running custom command %s" , ' ' . join...
Reconfigure BIRD daemon by running a custom command .
20,419
def update ( self , prefixes ) : if self . ip_prefix not in prefixes : prefixes . append ( self . ip_prefix ) self . log . info ( "announcing %s for %s" , self . ip_prefix , self . name ) return True return False
Add a value to the list .
20,420
def write ( self , string ) : string = string . rstrip ( ) if string : self . logger . critical ( string )
Erase newline from a string and write to the logger .
20,421
def process_log_record ( self , log_record ) : log_record [ "version" ] = __version__ log_record [ "program" ] = PROGRAM_NAME log_record [ "service_name" ] = log_record . pop ( 'threadName' , None ) return log_record
Add customer record keys and rename threadName key .
20,422
def get_vexrc ( options , environ ) : if options . config and not os . path . exists ( options . config ) : raise exceptions . InvalidVexrc ( "nonexistent config: {0!r}" . format ( options . config ) ) filename = options . config or os . path . expanduser ( '~/.vexrc' ) vexrc = config . Vexrc . from_file ( filename , e...
Get a representation of the contents of the config file .
20,423
def get_cwd ( options ) : if not options . cwd : return None if not os . path . exists ( options . cwd ) : raise exceptions . InvalidCwd ( "can't --cwd to invalid path {0!r}" . format ( options . cwd ) ) return options . cwd
Discover what directory the command should run in .
20,424
def get_virtualenv_path ( ve_base , ve_name ) : if not ve_base : raise exceptions . NoVirtualenvsDirectory ( "could not figure out a virtualenvs directory. " "make sure $HOME is set, or $WORKON_HOME," " or set virtualenvs=something in your .vexrc" ) if not os . path . exists ( ve_base ) : message = ( "virtualenvs direc...
Check a virtualenv path raising exceptions to explain problems .
20,425
def get_command ( options , vexrc , environ ) : command = options . rest if not command : command = vexrc . get_shell ( environ ) if command and command [ 0 ] . startswith ( '--' ) : raise exceptions . InvalidCommand ( "don't put flags like '%s' after the virtualenv name." % command [ 0 ] ) if not command : raise excep...
Get a command to run .
20,426
def main ( ) : argv = sys . argv [ 1 : ] returncode = 1 try : returncode = _main ( os . environ , argv ) except exceptions . InvalidArgument as error : if error . message : sys . stderr . write ( "Error: " + error . message + '\n' ) else : raise sys . exit ( returncode )
The main command - line entry point with system interactions .
20,427
def get_processid ( config ) : pidfile = config . get ( 'daemon' , 'pidfile' , fallback = None ) if pidfile is None : raise ValueError ( "Configuration doesn't have pidfile option!" ) try : with open ( pidfile , 'r' ) as _file : pid = _file . read ( ) . rstrip ( ) try : pid = int ( pid ) except ValueError : raise Value...
Return process id of anycast - healthchecker .
20,428
def parse_services ( config , services ) : enabled = 0 for service in services : check_disabled = config . getboolean ( service , 'check_disabled' ) if not check_disabled : enabled += 1 return enabled
Parse configuration to return number of enabled service checks .
20,429
def main ( ) : arguments = docopt ( __doc__ ) config_file = '/etc/anycast-healthchecker.conf' config_dir = '/etc/anycast-healthchecker.d' config = configparser . ConfigParser ( ) config_files = [ config_file ] config_files . extend ( glob . glob ( os . path . join ( config_dir , '*.conf' ) ) ) config . read ( config_fi...
Run check .
20,430
def scary_path ( path ) : if not path : return True assert isinstance ( path , bytes ) return not NOT_SCARY . match ( path )
Whitelist the WORKON_HOME strings we re willing to substitute in to strings that we provide for user s shell to evaluate .
20,431
def shell_config_for ( shell , vexrc , environ ) : here = os . path . dirname ( os . path . abspath ( __file__ ) ) path = os . path . join ( here , 'shell_configs' , shell ) try : with open ( path , 'rb' ) as inp : data = inp . read ( ) except FileNotFoundError as error : if error . errno != 2 : raise return b'' ve_bas...
return completion config for the named shell .
20,432
def _run_check ( self ) : cmd = shlex . split ( self . config [ 'check_cmd' ] ) self . log . info ( "running %s" , ' ' . join ( cmd ) ) proc = subprocess . Popen ( cmd , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) start_time = time . time ( ) try : outs , errs = proc . communicate ( timeout = self . confi...
Execute a check command .
20,433
def _ip_assigned ( self ) : output = [ ] cmd = [ '/sbin/ip' , 'address' , 'show' , 'dev' , self . config [ 'interface' ] , 'to' , self . ip_with_prefixlen , ] if self . ip_check_disabled : self . log . info ( "checking for IP assignment on interface %s is " "disabled" , self . config [ 'interface' ] ) return True self ...
Check if IP prefix is assigned to loopback interface .
20,434
def _check_disabled ( self ) : if self . config [ 'check_disabled' ] : if self . config [ 'on_disabled' ] == 'withdraw' : self . log . info ( "Check is disabled and ip_prefix will be " "withdrawn" ) self . log . info ( "adding %s in the queue" , self . ip_with_prefixlen ) self . action . put ( self . del_operation ) se...
Check if health check is disabled .
20,435
def run ( self ) : try : self . _run ( ) except Exception : self . action . put ( ServiceCheckDiedError ( self . name , traceback . format_exc ( ) ) )
Wrap _run method .
20,436
def main ( ) : args = docopt ( __doc__ , version = __version__ ) if args [ '--print' ] : for section in DEFAULT_OPTIONS : print ( "[{}]" . format ( section ) ) for key , value in DEFAULT_OPTIONS [ section ] . items ( ) : print ( "{k} = {v}" . format ( k = key , v = value ) ) print ( ) sys . exit ( 0 ) try : config , bi...
Parse CLI and starts main program .
20,437
def get_environ ( environ , defaults , ve_path ) : env = environ . copy ( ) env . update ( defaults ) if 'PYTHONHOME' in env : del env [ 'PYTHONHOME' ] if not ve_path : raise exceptions . BadConfig ( 've_path must be set' ) if platform . system ( ) == 'Windows' : ve_bin = os . path . join ( ve_path , 'Scripts' ) else :...
Make an environment to run with .
20,438
def extract_key_value ( line , environ ) : segments = line . split ( "=" , 1 ) if len ( segments ) < 2 : return None key , value = segments value = value . strip ( ) if value [ 0 ] == "'" and _SQUOTE_RE . match ( value ) : value = value [ 1 : - 1 ] elif value [ 0 ] == '"' and _DQUOTE_RE . match ( value ) : template = v...
Return key value from given line if present else return None .
20,439
def from_file ( cls , path , environ ) : instance = cls ( ) instance . read ( path , environ ) return instance
Make a Vexrc instance from given file in given environ .
20,440
def read ( self , path , environ ) : try : inp = open ( path , 'rb' ) except FileNotFoundError as error : if error . errno != 2 : raise return None parsing = parse_vexrc ( inp , environ ) for heading , key , value in parsing : heading = self . default_heading if heading is None else heading if heading not in self . hea...
Read data from file into this vexrc instance .
20,441
def get_ve_base ( self , environ ) : ve_base_value = self . headings [ self . default_heading ] . get ( 'virtualenvs' ) if ve_base_value : ve_base = os . path . expanduser ( ve_base_value ) else : ve_base = environ . get ( 'WORKON_HOME' , '' ) if not ve_base : if platform . system ( ) == 'Windows' and os . name == 'nt'...
Find a directory to look for virtualenvs in .
20,442
def get_shell ( self , environ ) : command = self . headings [ self . default_heading ] . get ( 'shell' ) if not command and os . name != 'nt' : command = environ . get ( 'SHELL' , '' ) command = shlex . split ( command ) if command else None return command
Find a command to run .
20,443
def name ( self ) : if 'name' not in self . metainfo [ 'info' ] and self . path is not None : self . metainfo [ 'info' ] [ 'name' ] = os . path . basename ( self . path ) return self . metainfo [ 'info' ] . get ( 'name' , None )
Name of the torrent
20,444
def trackers ( self ) : announce_list = self . metainfo . get ( 'announce-list' , None ) if not announce_list : announce = self . metainfo . get ( 'announce' , None ) if announce : return [ [ announce ] ] else : return announce_list
List of tiers of announce URLs or None for no trackers
20,445
def infohash ( self ) : self . validate ( ) info = self . convert ( ) [ b'info' ] return sha1 ( bencode ( info ) ) . hexdigest ( )
SHA1 info hash
20,446
def infohash_base32 ( self ) : self . validate ( ) info = self . convert ( ) [ b'info' ] return b32encode ( sha1 ( bencode ( info ) ) . digest ( ) )
Base32 encoded SHA1 info hash
20,447
def generate ( self , callback = None , interval = 0 ) : if self . path is None : raise RuntimeError ( 'generate() called with no path specified' ) elif self . size <= 0 : raise error . PathEmptyError ( self . path ) elif not os . path . exists ( self . path ) : raise error . PathNotFoundError ( self . path ) if callba...
Hash pieces and report progress to callback
20,448
def magnet ( self , name = True , size = True , trackers = True , tracker = False , validate = True ) : if validate : self . validate ( ) parts = [ f'xt=urn:btih:{self.infohash}' ] if name : parts . append ( f'dn={utils.urlquote(self.name)}' ) if size : parts . append ( f'xl={self.size}' ) if self . trackers is not Non...
BTIH Magnet URI
20,449
def read_stream ( cls , stream , validate = True ) : try : content = stream . read ( cls . MAX_TORRENT_FILE_SIZE ) except OSError as e : raise error . ReadError ( e . errno ) else : try : metainfo_enc = bdecode ( content ) except BTFailure as e : raise error . ParseError ( ) if validate : if b'info' not in metainfo_enc...
Read torrent metainfo from file - like object
20,450
def read ( cls , filepath , validate = True ) : try : with open ( filepath , 'rb' ) as fh : return cls . read_stream ( fh ) except ( OSError , error . ReadError ) as e : raise error . ReadError ( e . errno , filepath ) except error . ParseError : raise error . ParseError ( filepath )
Read torrent metainfo from file
20,451
def copy ( self ) : from copy import deepcopy cp = type ( self ) ( ) cp . _metainfo = deepcopy ( self . _metainfo ) return cp
Return a new object with the same metainfo
20,452
def validated_url ( url ) : try : u = urlparse ( url ) u . port except Exception : raise error . URLError ( url ) else : if not u . scheme or not u . netloc : raise error . URLError ( url ) return url
Return url if valid raise URLError otherwise
20,453
def read_chunks ( filepath , chunk_size ) : try : with open ( filepath , 'rb' ) as f : while True : chunk = f . read ( chunk_size ) if chunk : yield chunk else : break except OSError as e : raise error . ReadError ( e . errno , filepath )
Generator that yields chunks from file
20,454
def calc_piece_size ( total_size , max_pieces , min_piece_size , max_piece_size ) : ps = 1 << max ( 0 , math . ceil ( math . log ( total_size / max_pieces , 2 ) ) ) if ps < min_piece_size : ps = min_piece_size if ps > max_piece_size : ps = max_piece_size return ps
Calculate piece size
20,455
def is_power_of_2 ( num ) : log = math . log2 ( num ) return int ( log ) == float ( log )
Return whether num is a power of two
20,456
def is_hidden ( path ) : for name in path . split ( os . sep ) : if name != '.' and name != '..' and name and name [ 0 ] == '.' : return True return False
Whether file or directory is hidden
20,457
def filepaths ( path , exclude = ( ) , hidden = True , empty = True ) : if not os . path . exists ( path ) : raise error . PathNotFoundError ( path ) elif not os . access ( path , os . R_OK , effective_ids = os . access in os . supports_effective_ids ) : raise error . ReadError ( errno . EACCES , path ) if os . path . ...
Return list of absolute sorted file paths
20,458
def assert_type ( lst_or_dct , keys , exp_types , must_exist = True , check = None ) : keys = list ( keys ) keychain = [ ] while len ( keys [ : - 1 ] ) > 0 : key = keys . pop ( 0 ) try : lst_or_dct = lst_or_dct [ key ] except ( KeyError , IndexError ) : break keychain . append ( key ) keychain_str = '' . join ( f'[{key...
Raise MetainfoError is not of a particular type
20,459
def error_message_and_exit ( message , error_result ) : if message : error_message ( message ) puts ( json . dumps ( error_result , indent = 2 ) ) sys . exit ( 1 )
Prints error messages in blue the failed task result and quits .
20,460
def print_prompt_values ( values , message = None , sub_attr = None ) : if message : prompt_message ( message ) for index , entry in enumerate ( values ) : if sub_attr : line = '{:2d}: {}' . format ( index , getattr ( utf8 ( entry ) , sub_attr ) ) else : line = '{:2d}: {}' . format ( index , utf8 ( entry ) ) with inden...
Prints prompt title and choices with a bit of formatting .
20,461
def prompt_for_input ( message , input_type = None ) : while True : output = prompt . query ( message ) if input_type : try : output = input_type ( output ) except ValueError : error_message ( 'Invalid input type' ) continue break return output
Prints prompt instruction and does basic input parsing .
20,462
def prompt_for_choice ( values , message , input_type = int , output_type = None ) : output = None while not output : index = prompt_for_input ( message , input_type = input_type ) try : output = utf8 ( values [ index ] ) except IndexError : error_message ( 'Selection out of range' ) continue if output_type : output = ...
Prints prompt with a list of choices to choose from .
20,463
def _retrieve_result ( endpoints , token_header ) : request_list = [ ( url , token_header ) for ( task_id , url ) in endpoints ] responses = concurrent_get ( request_list ) assert len ( endpoints ) == len ( responses ) responses_dic = { task_id : r . content for ( task_id , _ ) , r in zip ( endpoints , responses ) } re...
Prepare the request list and execute them concurrently .
20,464
def _build_endpoint ( self , endpoint_name ) : endpoint_relative = settings . get ( 'asmaster_endpoints' , endpoint_name ) return '%s%s' % ( self . host , endpoint_relative )
Generate an enpoint url from a setting name .
20,465
def _set_allowed_services_and_actions ( self , services ) : for service in services : self . services [ service [ 'name' ] ] = { } for action in service [ 'actions' ] : name = action . pop ( 'name' ) self . services [ service [ 'name' ] ] [ name ] = action
Expect services to be a list of service dictionaries each with name and actions keys .
20,466
def list_subscriptions ( self , service ) : data = { 'service' : service , } return self . _perform_post_request ( self . list_subscriptions_endpoint , data , self . token_header )
Asks for a list of all subscribed accounts and devices along with their statuses .
20,467
def subscribe_account ( self , username , password , service ) : data = { 'service' : service , 'username' : username , 'password' : password , } return self . _perform_post_request ( self . subscribe_account_endpoint , data , self . token_header )
Subscribe an account for a service .
20,468
def file_id_to_file_name ( file_id ) : if len ( file_id ) == 40 and re . match ( "^[a-f0-9]+$" , file_id ) : return file_id return "re_{}" . format ( hashlib . sha1 ( file_id ) . hexdigest ( ) )
Sometimes file ids are not the file names on the device but are instead generated by the API . These are not guaranteed to be valid file names so need hashing .
20,469
def sync ( func ) : sync_timeout = 3600 def wraps ( * args , ** kwargs ) : task = func ( * args , ** kwargs ) task . wait_for_result ( timeout = sync_timeout ) result = json . loads ( task . result ) return result return wraps
Decorator to make a task synchronous .
20,470
def fetch_data ( self ) : choices = self . available_data choices . insert ( 0 , 'All' ) selected_data_type = utils . select_item ( choices , 'Please select what data to fetch:' , 'Available data:' , ) if selected_data_type == 'All' : selected_data_type = ',' . join ( self . available_data ) utils . pending_message ( '...
Prompt for a data type choice and execute the fetch_data task . The results are saved to a file in json format .
20,471
def log_in ( self ) : if not self . password : self . password = getpass . getpass ( 'Password: ' ) utils . pending_message ( 'Performing login...' ) login_result = self . client . login ( account = self . account , password = self . password ) if 'error' in login_result : self . handle_failed_login ( login_result ) ut...
Perform the log_in task to setup the API session for future data requests .
20,472
def get_devices ( self ) : utils . pending_message ( 'Fetching device list...' ) get_devices_task = self . client . devices ( account = self . account ) get_devices_task . wait_for_result ( timeout = self . timeout ) get_devices_result = json . loads ( get_devices_task . result ) self . devices = get_devices_result [ '...
Execute the get_devices task and store the results in self . devices .
20,473
def download_files ( self , files ) : utils . pending_message ( "Downloading {nfiles} file{plural}..." . format ( nfiles = len ( files ) , plural = 's' if len ( files ) > 1 else '' ) ) for file in files : if 'file_id' not in file : continue def build_callback ( file ) : def file_callback ( task ) : device_name = self ....
This method uses the download_file task to retrieve binary files such as attachments images and videos .
20,474
def register_account ( self , username , service ) : data = { 'service' : service , 'username' : username , } return self . _perform_post_request ( self . register_account_endpoint , data , self . token_header )
Register an account against a service . The account that we re querying must be referenced during any future task requests - so we know which account to link the task too .
20,475
def perform_task ( self , service , task_name , account , payload , callback = None ) : data = { 'service' : service , 'action' : task_name , 'account' : account , } data . update ( payload ) response = self . _perform_post_request ( self . submit_endpoint , data , self . token_header ) task = Task ( uuid = response [ ...
Submit a task to the API . The task is executed asyncronously and a Task object is returned .
20,476
def task_status ( self , task_id ) : data = { 'task_ids' : task_id , } return self . _perform_post_request ( self . task_status_endpoint , data , self . token_header )
Find the status of a task .
20,477
def result_consumed ( self , task_id ) : logger . debug ( 'Sending result consumed message.' ) data = { 'task_ids' : task_id , } return self . _perform_post_request ( self . results_consumed_endpoint , data , self . token_header )
Report the result as successfully consumed .
20,478
def send_mails ( cls ) : if settings . CAS_NEW_VERSION_EMAIL_WARNING and settings . ADMINS : try : obj = cls . objects . get ( ) except cls . DoesNotExist : obj = NewVersionWarning . objects . create ( version = VERSION ) LAST_VERSION = utils . last_version ( ) if LAST_VERSION is not None and LAST_VERSION != obj . vers...
For each new django - cas - server version if the current instance is not up to date send one mail to settings . ADMINS .
20,479
def get_proxy_url ( self , pgt ) : params = urllib_parse . urlencode ( { 'pgt' : pgt , 'targetService' : self . service_url } ) return "%s/proxy?%s" % ( self . server_url , params )
Returns proxy url given the proxy granting ticket
20,480
def get_conn ( cls ) : conn = cls . _conn if conn is None or conn . closed : conn = ldap3 . Connection ( settings . CAS_LDAP_SERVER , settings . CAS_LDAP_USER , settings . CAS_LDAP_PASSWORD , client_strategy = "RESTARTABLE" , auto_bind = True ) cls . _conn = conn return conn
Return a connection object to the ldap database
20,481
def json_encode ( obj ) : try : return json_encode . encoder . encode ( obj ) except AttributeError : json_encode . encoder = DjangoJSONEncoder ( default = six . text_type ) return json_encode ( obj )
Encode a python object to json
20,482
def context ( params ) : params [ "settings" ] = settings params [ "message_levels" ] = DEFAULT_MESSAGE_LEVELS if settings . CAS_NEW_VERSION_HTML_WARNING : LAST_VERSION = last_version ( ) params [ "VERSION" ] = VERSION params [ "LAST_VERSION" ] = LAST_VERSION if LAST_VERSION is not None : params [ "upgrade_available" ]...
Function that add somes variable to the context before template rendering
20,483
def json_response ( request , data ) : data [ "messages" ] = [ ] for msg in messages . get_messages ( request ) : data [ "messages" ] . append ( { 'message' : msg . message , 'level' : msg . level_tag } ) return HttpResponse ( json . dumps ( data ) , content_type = "application/json" )
Wrapper dumping data to a json and sending it to the user with an HttpResponse
20,484
def import_attr ( path ) : if isinstance ( path , six . binary_type ) : path = path . decode ( "utf-8" ) if not isinstance ( path , six . text_type ) : return path if u"." not in path : ValueError ( "%r should be of the form `module.attr` and we just got `attr`" % path ) module , attr = path . rsplit ( u'.' , 1 ) try :...
transform a python dotted path to the attr
20,485
def redirect_params ( url_name , params = None ) : url = reverse ( url_name ) params = urlencode ( params if params else { } ) return HttpResponseRedirect ( url + "?%s" % params )
Redirect to url_name with params as querystring
20,486
def reverse_params ( url_name , params = None , ** kwargs ) : url = reverse ( url_name , ** kwargs ) params = urlencode ( params if params else { } ) if params : return u"%s?%s" % ( url , params ) else : return url
compute the reverse url of url_name and add to it parameters from params as querystring
20,487
def set_cookie ( response , key , value , max_age ) : expires = datetime . strftime ( datetime . utcnow ( ) + timedelta ( seconds = max_age ) , "%a, %d-%b-%Y %H:%M:%S GMT" ) response . set_cookie ( key , value , max_age = max_age , expires = expires , domain = settings . SESSION_COOKIE_DOMAIN , secure = settings . SESS...
Set the cookie key on response with value value valid for max_age secondes
20,488
def get_current_url ( request , ignore_params = None ) : if ignore_params is None : ignore_params = set ( ) protocol = u'https' if request . is_secure ( ) else u"http" service_url = u"%s://%s%s" % ( protocol , request . get_host ( ) , request . path ) if request . GET : params = copy_params ( request . GET , ignore_par...
Giving a django request return the current http url possibly ignoring some GET parameters
20,489
def update_url ( url , params ) : if not isinstance ( url , bytes ) : url = url . encode ( 'utf-8' ) for key , value in list ( params . items ( ) ) : if not isinstance ( key , bytes ) : del params [ key ] key = key . encode ( 'utf-8' ) if not isinstance ( value , bytes ) : value = value . encode ( 'utf-8' ) params [ ke...
update parameters using params in the url query string
20,490
def unpack_nested_exception ( error ) : i = 0 while True : if error . args [ i : ] : if isinstance ( error . args [ i ] , Exception ) : error = error . args [ i ] i = 0 else : i += 1 else : break return error
If exception are stacked return the first one
20,491
def _gen_ticket ( prefix = None , lg = settings . CAS_TICKET_LEN ) : random_part = u'' . join ( random . choice ( string . ascii_letters + string . digits ) for _ in range ( lg - len ( prefix or "" ) - 1 ) ) if prefix is not None : return u'%s-%s' % ( prefix , random_part ) else : return random_part
Generate a ticket with prefix prefix and length lg
20,492
def crypt_salt_is_valid ( salt ) : if len ( salt ) < 2 : return False else : if salt [ 0 ] == '$' : if salt [ 1 ] == '$' : return False else : if '$' not in salt [ 1 : ] : return False else : hashed = crypt . crypt ( "" , salt ) if not hashed or '$' not in hashed [ 1 : ] : return False else : return True else : return ...
Validate a salt as crypt salt
20,493
def check_password ( method , password , hashed_password , charset ) : if not isinstance ( password , six . binary_type ) : password = password . encode ( charset ) if not isinstance ( hashed_password , six . binary_type ) : hashed_password = hashed_password . encode ( charset ) if method == "plain" : return password =...
Check that password match hashed_password using method assuming the encoding is charset .
20,494
def last_version ( ) : try : last_update , version , success = last_version . _cache except AttributeError : last_update = 0 version = None success = False cache_delta = 24 * 3600 if success else 600 if ( time . time ( ) - last_update ) < cache_delta : return version else : try : req = requests . get ( settings . CAS_N...
Fetch the last version from pypi and return it . On successful fetch from pypi the response is cached 24h on error it is cached 10 min .
20,495
def regexpr_validator ( value ) : try : re . compile ( value ) except re . error : raise ValidationError ( _ ( '"%(value)s" is not a valid regular expression' ) , params = { 'value' : value } )
Test that value is a valid regular expression
20,496
def hash ( cls , scheme , password , salt = None , charset = "utf8" ) : scheme = scheme . upper ( ) cls . _test_scheme ( scheme ) if salt is None or salt == b"" : salt = b"" cls . _test_scheme_nosalt ( scheme ) else : cls . _test_scheme_salt ( scheme ) try : return scheme + base64 . b64encode ( cls . _schemes_to_hash [...
Hash password with scheme using salt . This three variable beeing encoded in charset .
20,497
def get_salt ( cls , hashed_passord ) : scheme = cls . get_scheme ( hashed_passord ) cls . _test_scheme ( scheme ) if scheme in cls . schemes_nosalt : return b"" elif scheme == b'{CRYPT}' : return b'$' . join ( hashed_passord . split ( b'$' , 3 ) [ : - 1 ] ) [ len ( scheme ) : ] else : try : hashed_passord = base64 . b...
Return the salt of hashed_passord possibly empty
20,498
def visit_snippet_latex ( self , node ) : code = node . rawsource . rstrip ( '\n' ) lang = self . hlsettingstack [ - 1 ] [ 0 ] linenos = code . count ( '\n' ) >= self . hlsettingstack [ - 1 ] [ 1 ] - 1 fname = node [ 'filename' ] highlight_args = node . get ( 'highlight_args' , { } ) if 'language' in node : lang = node...
Latex document generator visit handler
20,499
def logout ( self , all_session = False ) : session_nb = 0 username = self . request . session . get ( "username" ) if username : if all_session : logger . info ( "Logging out user %s from all sessions." % username ) else : logger . info ( "Logging out user %s." % username ) users = [ ] try : users . append ( models . ...
effectively destroy a CAS session