idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
239,100
def send_contact ( self , phone_number , first_name , ** options ) : return self . bot . api_call ( "sendContact" , chat_id = self . id , phone_number = phone_number , first_name = first_name , ** options )
Send phone contacts .
239,101
def send_chat_action ( self , action ) : return self . bot . api_call ( "sendChatAction" , chat_id = self . id , action = action )
Send a chat action to tell the user that something is happening on the bot s side .
239,102
def send_media_group ( self , media : str , disable_notification : bool = False , reply_to_message_id : int = None , ** options ) : return self . bot . api_call ( "sendMediaGroup" , chat_id = str ( self . id ) , media = media , disable_notification = disable_notification , reply_to_message_id = reply_to_message_id , **...
Send a group of photos or videos as an album
239,103
def forward_message ( self , from_chat_id , message_id ) : return self . bot . api_call ( "forwardMessage" , chat_id = self . id , from_chat_id = from_chat_id , message_id = message_id , )
Forward a message from another chat to this chat .
239,104
def kick_chat_member ( self , user_id ) : return self . bot . api_call ( "kickChatMember" , chat_id = self . id , user_id = user_id )
Use this method to kick a user from a group or a supergroup . The bot must be an administrator in the group for this to work .
239,105
def unban_chat_member ( self , user_id ) : return self . bot . api_call ( "unbanChatMember" , chat_id = self . id , user_id = user_id )
Use this method to unban a previously kicked user in a supergroup . The bot must be an administrator in the group for this to work .
239,106
def delete_message ( self , message_id ) : return self . bot . api_call ( "deleteMessage" , chat_id = self . id , message_id = message_id )
Delete message from this chat
239,107
def from_message ( bot , message ) : chat = message [ "chat" ] return Chat ( bot , chat [ "id" ] , chat [ "type" ] , message )
Create a Chat object from a message .
239,108
def run ( self , timeout = POD_RUN_WAIT_TIMEOUT_SECONDS ) : if not isinstance ( timeout , int ) : raise SyntaxError ( "K8sCronJob.run() timeout: [ {} ] is invalid." ) if len ( self . active ) : raise CronJobAlreadyRunningException ( "K8sCronJob.run() failed: CronJob: [ {} ] " "has [ {} ] active Jobs currently." . forma...
Forces a K8sCronJob to run immediately .
239,109
def scale ( config = None , name = None , replicas = None ) : rc = K8sReplicationController ( config = config , name = name ) . get ( ) rc . desired_replicas = replicas rc . update ( ) rc . _wait_for_desired_replicas ( ) return rc
Scales the number of pods in the specified K8sReplicationController to the desired replica count .
239,110
def rolling_update ( config = None , name = None , image = None , container_name = None , rc_new = None ) : if name is None : raise SyntaxError ( 'K8sReplicationController: name: [ {0} ] cannot be None.' . format ( name ) ) if image is None and rc_new is None : raise SyntaxError ( "K8sReplicationController: please spec...
Performs a simple rolling update of a ReplicationController .
239,111
def restart ( self ) : rc_new = copy . deepcopy ( self ) return K8sReplicationController . rolling_update ( config = self . config , name = self . name , rc_new = rc_new )
Restart will force a rolling update of the current ReplicationController to the current revision . This essentially spawns a fresh copy of the RC and its pods . Useful when something is misbehaving .
239,112
def _has_local_storage ( self , pod = None ) : for vol in pod . volumes : if vol . emptyDir is not None : return True return False
Determines if a K8sPod has any local storage susceptible to be lost .
239,113
def rollback ( self , revision = None , annotations = None ) : rollback = DeploymentRollback ( ) rollback . name = self . name rollback_config = RollbackConfig ( ) if revision is not None : rollback_config . revision = revision else : current_revision = int ( self . get_annotation ( self . REVISION_ANNOTATION ) ) rev =...
Performs a rollback of the Deployment .
239,114
def roll_dice ( ) : sums = 0 while True : roll = random . randint ( 1 , 6 ) sums += roll if ( input ( "Enter y or n to continue: " ) . upper ( ) ) == 'N' : print ( sums ) break
Roll a die .
239,115
def get_raw_file ( ) : with open ( "{0}/dividers.txt" . format ( os . path . abspath ( os . path . dirname ( __file__ ) ) ) , mode = "r" ) as file_handler : lines = file_handler . readlines ( ) lines [ 35 ] = str ( random . randint ( 0 , 999999999999 ) ) return lines
Get the raw divider file in a string array .
239,116
def reduce_to_unit ( divider ) : for unit_size in range ( 1 , len ( divider ) // 2 + 1 ) : length = len ( divider ) unit = divider [ : unit_size ] divider_item = divider [ : unit_size * ( length // unit_size ) ] if unit * ( length // unit_size ) == divider_item : return unit return divider
Reduce a repeating divider to the smallest repeating unit possible .
239,117
def splitter ( div , * args ) : retstr = "" if type ( div ) is int : div = theArray ( ) [ div ] if len ( args ) == 1 : return args [ 0 ] for s in args : retstr += s retstr += "\n" retstr += div retstr += "\n" return retstr
Split text with dividers easily .
239,118
def area4info ( ) : name = "area4" author = "https://github.com/RDIL" author_email = rdillib . get_email ( ) description = "Dividers in Python, the easy way!" return "{0}: {1}\n{2}: {3}\n{4}: {5}\n{6}: {7}" . format ( "Name:" , name , "Author:" , author , "Author Email:" , author_email , "Description:" , description )
Get some info about the package .
239,119
def make_div ( unit , length = 24 , start = '' , end = '' , literal_unit = False ) : if not literal_unit : unit = utils . reduce_to_unit ( unit ) repeats = ( length - len ( start + end ) ) // len ( unit ) return ( start + unit * repeats + end ) [ 0 : length ]
Generate and return a custom divider .
239,120
def localpath ( * args ) : plist = [ ROOT ] + list ( args ) return os . path . abspath ( pjoin ( * plist ) )
construct an absolute path from a list relative to the root pycapnp directory
239,121
def fetch_libcapnp ( savedir , url = None ) : is_preconfigured = False if url is None : url = libcapnp_url is_preconfigured = True dest = pjoin ( savedir , 'capnproto-c++' ) if os . path . exists ( dest ) : info ( "already have %s" % dest ) return fname = fetch_archive ( savedir , url , libcapnp ) tf = tarfile . open (...
download and extract libcapnp
239,122
def stage_platform_hpp ( capnproot ) : platform_hpp = pjoin ( capnproot , 'src' , 'platform.hpp' ) if os . path . exists ( platform_hpp ) : info ( "already have platform.hpp" ) return if os . name == 'nt' : platform_dir = pjoin ( capnproot , 'builds' , 'msvc' ) else : info ( "attempting ./configure to generate platform...
stage platform . hpp into libcapnp sources
239,123
def _find_library ( lib , path ) : for d in path [ : : - 1 ] : real_lib = os . path . join ( d , lib ) if os . path . exists ( real_lib ) : return real_lib
Find a library
239,124
def get_output_error ( cmd ) : if not isinstance ( cmd , list ) : cmd = [ cmd ] logging . debug ( "Running: %s" , ' ' . join ( map ( quote , cmd ) ) ) try : result = Popen ( cmd , stdout = PIPE , stderr = PIPE ) except IOError as e : return - 1 , u ( '' ) , u ( 'Failed to run %r: %r' % ( cmd , e ) ) so , se = result . ...
Return the exit status stdout stderr of a command
239,125
def load_config ( name , base = 'conf' ) : fname = pjoin ( base , name + '.json' ) if not os . path . exists ( fname ) : return { } try : with open ( fname ) as f : cfg = json . load ( f ) except Exception as e : warn ( "Couldn't load %s: %s" % ( fname , e ) ) cfg = { } return cfg
Load config dict from JSON
239,126
def save_config ( name , data , base = 'conf' ) : if not os . path . exists ( base ) : os . mkdir ( base ) fname = pjoin ( base , name + '.json' ) with open ( fname , 'w' ) as f : json . dump ( data , f , indent = 2 )
Save config dict to JSON
239,127
def get_eargs ( ) : settings = { } zmq = os . environ . get ( "ZMQ_PREFIX" , None ) if zmq is not None : debug ( "Found environ var ZMQ_PREFIX=%s" % zmq ) settings [ 'zmq_prefix' ] = zmq return settings
Look for options in environment vars
239,128
def cfg2dict ( cfg ) : d = { } for section in cfg . sections ( ) : d [ section ] = dict ( cfg . items ( section ) ) return d
turn a ConfigParser into a nested dict because ConfigParser objects are dumb .
239,129
def get_cfg_args ( ) : if not os . path . exists ( 'setup.cfg' ) : return { } cfg = ConfigParser ( ) cfg . read ( 'setup.cfg' ) cfg = cfg2dict ( cfg ) g = cfg . setdefault ( 'global' , { } ) for key in [ 'libzmq_extension' , 'bundle_libzmq_dylib' , 'no_libzmq_extension' , 'have_sys_un_h' , 'skip_check_zmq' , ] : if key...
Look for options in setup . cfg
239,130
def config_from_prefix ( prefix ) : settings = { } if prefix . lower ( ) in ( 'default' , 'auto' , '' ) : settings [ 'zmq_prefix' ] = '' settings [ 'libzmq_extension' ] = False settings [ 'no_libzmq_extension' ] = False elif prefix . lower ( ) in ( 'bundled' , 'extension' ) : settings [ 'zmq_prefix' ] = '' settings [ '...
Get config from zmq prefix
239,131
def merge ( into , d ) : if isinstance ( into , dict ) : for key in d . keys ( ) : if key not in into : into [ key ] = d [ key ] else : into [ key ] = merge ( into [ key ] , d [ key ] ) return into elif isinstance ( into , list ) : return into + d else : return d
merge two containers into is updated d has priority
239,132
def discover_settings ( conf_base = None ) : settings = { 'zmq_prefix' : '' , 'libzmq_extension' : False , 'no_libzmq_extension' : False , 'skip_check_zmq' : False , 'build_ext' : { } , 'bdist_egg' : { } , } if sys . platform . startswith ( 'win' ) : settings [ 'have_sys_un_h' ] = False if conf_base : merge ( settings ...
Discover custom settings for ZMQ path
239,133
def call ( self , params , _context , ** kwargs ) : assert len ( params ) == self . paramCount return evaluate_impl ( self . body , params ) . then ( lambda value : setattr ( _context . results , 'value' , value ) )
Note that we re returning a Promise object here and bypassing the helper functionality that normally sets the results struct from the returned object . Instead we set _context . results directly inside of another promise
239,134
def detect_version ( basedir , compiler = None , ** compiler_attrs ) : if compiler is None : compiler = get_default_compiler ( ) cfile = pjoin ( basedir , 'vers.cpp' ) shutil . copy ( pjoin ( os . path . dirname ( __file__ ) , 'vers.cpp' ) , cfile ) if sys . platform . startswith ( 'linux' ) : cc = ccompiler . new_comp...
Compile link & execute a test program in empty directory basedir .
239,135
def generate_file ( fname , ns_func , dest_dir = "." ) : with open ( pjoin ( root , 'buildutils' , 'templates' , '%s' % fname ) , 'r' ) as f : tpl = f . read ( ) out = tpl . format ( ** ns_func ( ) ) dest = pjoin ( dest_dir , fname ) info ( "generating %s from template" % dest ) with open ( dest , 'w' ) as f : f . writ...
generate a constants file from its template
239,136
def render_constants ( ) : generate_file ( "constant_enums.pxi" , cython_enums , pjoin ( root , 'zmq' , 'backend' , 'cython' ) ) generate_file ( "constants.pxi" , constants_pyx , pjoin ( root , 'zmq' , 'backend' , 'cython' ) ) generate_file ( "zmq_constants.h" , ifndefs , pjoin ( root , 'zmq' , 'utils' ) )
render generated constant files from templates
239,137
def from_time ( cls , source ) : return cls ( hours = source . hour , minutes = source . minute , seconds = source . second , milliseconds = source . microsecond // 1000 )
datetime . time - > SubRipTime corresponding to time object
239,138
def to_time ( self ) : return time ( self . hours , self . minutes , self . seconds , self . milliseconds * 1000 )
Convert SubRipTime instance into a pure datetime . time object
239,139
def export_pages ( root_page , export_unpublished = False ) : pages = Page . objects . descendant_of ( root_page , inclusive = True ) . order_by ( 'path' ) . specific ( ) if not export_unpublished : pages = pages . filter ( live = True ) page_data = [ ] exported_paths = set ( ) for ( i , page ) in enumerate ( pages ) :...
Create a JSON defintion of part of a site s page tree starting from root_page and descending into its descendants
239,140
def import_from_api ( request ) : if request . method == 'POST' : form = ImportFromAPIForm ( request . POST ) if form . is_valid ( ) : base_url = re . sub ( r'\/$' , '' , form . cleaned_data [ 'source_site_base_url' ] ) import_url = ( base_url + reverse ( 'wagtailimportexport:export' , args = [ form . cleaned_data [ 's...
Import a part of a source site s page tree via a direct API request from this Wagtail Admin to the source site
239,141
def import_from_file ( request ) : if request . method == 'POST' : form = ImportFromFileForm ( request . POST , request . FILES ) if form . is_valid ( ) : import_data = json . loads ( form . cleaned_data [ 'file' ] . read ( ) . decode ( 'utf-8-sig' ) ) parent_page = form . cleaned_data [ 'parent_page' ] try : page_coun...
Import a part of a source site s page tree via an import of a JSON file exported to a user s filesystem from the source site s Wagtail Admin
239,142
def export_to_file ( request ) : if request . method == 'POST' : form = ExportForm ( request . POST ) if form . is_valid ( ) : payload = export_pages ( form . cleaned_data [ 'root_page' ] , export_unpublished = True ) response = JsonResponse ( payload ) response [ 'Content-Disposition' ] = 'attachment; filename="export...
Export a part of this source site s page tree to a JSON file on this user s filesystem for subsequent import in a destination site s Wagtail Admin
239,143
def export ( request , page_id , export_unpublished = False ) : try : if export_unpublished : root_page = Page . objects . get ( id = page_id ) else : root_page = Page . objects . get ( id = page_id , live = True ) except Page . DoesNotExist : return JsonResponse ( { 'error' : _ ( 'page not found' ) } ) payload = expor...
API endpoint of this source site to export a part of the page tree rooted at page_id
239,144
def import_pages ( import_data , parent_page ) : pages_by_original_path = { } pages_by_original_id = { } page_content_type = ContentType . objects . get_for_model ( Page ) for ( i , page_record ) in enumerate ( import_data [ 'pages' ] ) : page = Page . from_serializable_data ( page_record [ 'content' ] ) original_path ...
Take a JSON export of part of a source site s page tree and create those pages under the parent page
239,145
def remove_all_filters ( self ) : self . attitude_filter = self . source_filter = None self . question_filter = self . link_filter = False
Removes all filters
239,146
def set_source_filter ( self , source ) : if isinstance ( source , str if py3k else basestring ) and len ( source ) >= 2 : self . source_filter = source else : raise TwitterSearchException ( 1009 )
Only search for tweets entered via given source
239,147
def add_keyword ( self , word , or_operator = False ) : if isinstance ( word , str if py3k else basestring ) and len ( word ) >= 2 : self . searchterms . append ( word if " " not in word else '"%s"' % word ) elif isinstance ( word , ( tuple , list ) ) : word = [ ( i if " " not in i else '"%s"' % i ) for i in word ] sel...
Adds a given string or list to the current keyword list
239,148
def set_keywords ( self , words , or_operator = False ) : if not isinstance ( words , ( tuple , list ) ) : raise TwitterSearchException ( 1001 ) words = [ ( i if " " not in i else '"%s"' % i ) for i in words ] self . searchterms = [ " OR " . join ( words ) ] if or_operator else words
Sets a given list as the new keyword list
239,149
def set_language ( self , lang ) : if lang in self . iso_6391 : self . arguments . update ( { 'lang' : '%s' % lang } ) else : raise TwitterSearchException ( 1002 )
Sets lang parameter used to only fetch tweets within \ a certain language
239,150
def set_callback ( self , func ) : if isinstance ( func , str if py3k else basestring ) and func : self . arguments . update ( { 'callback' : '%s' % func } ) else : raise TwitterSearchException ( 1006 )
Sets callback parameter . If supplied the response \ will use the JSONP format with a callback of the given name
239,151
def set_until ( self , date ) : if isinstance ( date , datetime . date ) and date <= datetime . date . today ( ) : self . arguments . update ( { 'until' : '%s' % date . strftime ( '%Y-%m-%d' ) } ) else : raise TwitterSearchException ( 1007 )
Sets until parameter used to return \ only tweets generated before the given date
239,152
def set_proxy ( self , proxy ) : if isinstance ( proxy , str if py3k else basestring ) : self . __proxy = proxy else : raise TwitterSearchException ( 1009 )
Sets a HTTPS proxy to query the Twitter API
239,153
def get_minimal_id ( self ) : if not self . __response : raise TwitterSearchException ( 1013 ) return min ( self . __response [ 'content' ] [ 'statuses' ] if self . __order_is_search else self . __response [ 'content' ] , key = lambda i : i [ 'id' ] ) [ 'id' ] - 1
Returns the minimal tweet ID of the current response
239,154
def get_amount_of_tweets ( self ) : if not self . __response : raise TwitterSearchException ( 1013 ) return ( len ( self . __response [ 'content' ] [ 'statuses' ] ) if self . __order_is_search else len ( self . __response [ 'content' ] ) )
Returns current amount of tweets available within this instance
239,155
def set_count ( self , cnt ) : if isinstance ( cnt , int ) and cnt > 0 and cnt <= 100 : self . arguments . update ( { 'count' : '%s' % cnt } ) else : raise TwitterSearchException ( 1004 )
Sets count parameter used to define the number of \ tweets to return per page . Maximum and default value is 100
239,156
def set_include_entities ( self , include ) : if not isinstance ( include , bool ) : raise TwitterSearchException ( 1008 ) self . arguments . update ( { 'include_entities' : 'true' if include else 'false' } )
Sets include entities parameter to either \ include or exclude the entities node within the results
239,157
def set_trim_user ( self , trim ) : if not isinstance ( trim , bool ) : raise TwitterSearchException ( 1008 ) self . arguments . update ( { 'trim_user' : 'true' if trim else 'false' } )
Sets trim_user parameter . When set to True \ each tweet returned in a timeline will include a \ user object including only the status authors numerical ID
239,158
def set_include_rts ( self , rts ) : if not isinstance ( rts , bool ) : raise TwitterSearchException ( 1008 ) self . arguments . update ( { 'include_rts' : 'true' if rts else 'false' } )
Sets include_rts parameter . When set to False \ the timeline will strip any native retweets from the returned timeline
239,159
def set_exclude_replies ( self , exclude ) : if not isinstance ( exclude , bool ) : raise TwitterSearchException ( 1008 ) self . arguments . update ( { 'exclude_replies' : 'true' if exclude else 'false' } )
Sets exclude_replies parameter used to \ prevent replies from appearing in the returned timeline
239,160
def set_contributor_details ( self , contdetails ) : if not isinstance ( contdetails , bool ) : raise TwitterSearchException ( 1008 ) self . arguments . update ( { 'contributor_details' : 'true' if contdetails else 'false' } )
Sets contributor_details parameter used to enhance the \ contributors element of the status response to include \ the screen_name of the contributor . By default only \ the user_id of the contributor is included
239,161
def url ( context , view , subdomain = UNSET , * args , ** kwargs ) : if subdomain is UNSET : request = context . get ( 'request' ) if request is not None : subdomain = getattr ( request , 'subdomain' , None ) else : subdomain = None elif subdomain is '' : subdomain = None return reverse ( view , subdomain = subdomain ...
Resolves a URL in a template using subdomain - based URL resolution .
239,162
def urljoin ( domain , path = None , scheme = None ) : if scheme is None : scheme = getattr ( settings , 'DEFAULT_URL_SCHEME' , 'http' ) return urlunparse ( ( scheme , domain , path or '' , None , None , None ) )
Joins a domain path and scheme part together returning a full URL .
239,163
def process_request ( self , request ) : domain , host = map ( lower , ( self . get_domain_for_request ( request ) , request . get_host ( ) ) ) pattern = r'^(?:(?P<subdomain>.*?)\.)?%s(?::.*)?$' % re . escape ( domain ) matches = re . match ( pattern , host ) if matches : request . subdomain = matches . group ( 'subdom...
Adds a subdomain attribute to the request parameter .
239,164
def process_request ( self , request ) : super ( SubdomainURLRoutingMiddleware , self ) . process_request ( request ) subdomain = getattr ( request , 'subdomain' , UNSET ) if subdomain is not UNSET : urlconf = settings . SUBDOMAIN_URLCONFS . get ( subdomain ) if urlconf is not None : logger . debug ( "Using urlconf %s ...
Sets the current request s urlconf attribute to the urlconf associated with the subdomain if it is listed in settings . SUBDOMAIN_URLCONFS .
239,165
def process_response ( self , request , response ) : if getattr ( settings , 'FORCE_VARY_ON_HOST' , True ) : patch_vary_headers ( response , ( 'Host' , ) ) return response
Forces the HTTP Vary header onto requests to avoid having responses cached across subdomains .
239,166
def process_docstring ( app , what , name , obj , options , lines ) : result = [ re . sub ( r'U\{([^}]*)\}' , r'\1' , re . sub ( r'(L|C)\{([^}]*)\}' , r':py:obj:`\2`' , re . sub ( r'@(' + '|' . join ( FIELDS ) + r')' , r':\1' , l ) ) ) for l in lines ] lines [ : ] = result [ : ]
Process the docstring for a given python object . Note that the list lines is changed in this function . Sphinx uses the altered content of the list .
239,167
def doArc8 ( arcs , domains , assignments ) : check = dict . fromkeys ( domains , True ) while check : variable , _ = check . popitem ( ) if variable not in arcs or variable in assignments : continue domain = domains [ variable ] arcsvariable = arcs [ variable ] for othervariable in arcsvariable : arcconstraints = arcs...
Perform the ARC - 8 arc checking algorithm and prune domains
239,168
def addVariables ( self , variables , domain ) : for variable in variables : self . addVariable ( variable , domain )
Add one or more variables to the problem
239,169
def addConstraint ( self , constraint , variables = None ) : if not isinstance ( constraint , Constraint ) : if callable ( constraint ) : constraint = FunctionConstraint ( constraint ) else : msg = "Constraints must be instances of subclasses " "of the Constraint class" raise ValueError ( msg ) self . _constraints . ap...
Add a constraint to the problem
239,170
def getSolution ( self ) : domains , constraints , vconstraints = self . _getArgs ( ) if not domains : return None return self . _solver . getSolution ( domains , constraints , vconstraints )
Find and return a solution to the problem
239,171
def getSolutions ( self ) : domains , constraints , vconstraints = self . _getArgs ( ) if not domains : return [ ] return self . _solver . getSolutions ( domains , constraints , vconstraints )
Find and return all solutions to the problem
239,172
def getSolutionIter ( self ) : domains , constraints , vconstraints = self . _getArgs ( ) if not domains : return iter ( ( ) ) return self . _solver . getSolutionIter ( domains , constraints , vconstraints )
Return an iterator to the solutions of the problem
239,173
def getSolution ( self , domains , constraints , vconstraints ) : msg = "%s is an abstract class" % self . __class__ . __name__ raise NotImplementedError ( msg )
Return one solution for the given problem
239,174
def resetState ( self ) : self . extend ( self . _hidden ) del self . _hidden [ : ] del self . _states [ : ]
Reset to the original domain state including all possible values
239,175
def popState ( self ) : diff = self . _states . pop ( ) - len ( self ) if diff : self . extend ( self . _hidden [ - diff : ] ) del self . _hidden [ - diff : ]
Restore domain state from the top of the stack
239,176
def hideValue ( self , value ) : list . remove ( self , value ) self . _hidden . append ( value )
Hide the given value from the domain
239,177
def preProcess ( self , variables , domains , constraints , vconstraints ) : if len ( variables ) == 1 : variable = variables [ 0 ] domain = domains [ variable ] for value in domain [ : ] : if not self ( variables , domains , { variable : value } ) : domain . remove ( value ) constraints . remove ( ( self , variables )...
Preprocess variable domains
239,178
def forwardCheck ( self , variables , domains , assignments , _unassigned = Unassigned ) : unassignedvariable = _unassigned for variable in variables : if variable not in assignments : if unassignedvariable is _unassigned : unassignedvariable = variable else : break else : if unassignedvariable is not _unassigned : dom...
Helper method for generic forward checking
239,179
def block_view ( request ) : blocked_ip_list = get_blocked_ips ( ) blocked_username_list = get_blocked_usernames ( ) context = { 'blocked_ip_list' : blocked_ip_list , 'blocked_username_list' : blocked_username_list } return render ( request , 'defender/admin/blocks.html' , context )
List the blocked IP and Usernames
239,180
def get_ip ( request ) : if config . BEHIND_REVERSE_PROXY : ip_address = request . META . get ( config . REVERSE_PROXY_HEADER , '' ) ip_address = ip_address . split ( "," , 1 ) [ 0 ] . strip ( ) if ip_address == '' : ip_address = get_ip_address_from_request ( request ) else : ip_address = get_ip_address_from_request ( ...
get the ip address from the request
239,181
def get_blocked_ips ( ) : if config . DISABLE_IP_LOCKOUT : return [ ] key = get_ip_blocked_cache_key ( "*" ) key_list = [ redis_key . decode ( 'utf-8' ) for redis_key in REDIS_SERVER . keys ( key ) ] return strip_keys ( key_list )
get a list of blocked ips from redis
239,182
def get_blocked_usernames ( ) : if config . DISABLE_USERNAME_LOCKOUT : return [ ] key = get_username_blocked_cache_key ( "*" ) key_list = [ redis_key . decode ( 'utf-8' ) for redis_key in REDIS_SERVER . keys ( key ) ] return strip_keys ( key_list )
get a list of blocked usernames from redis
239,183
def increment_key ( key ) : pipe = REDIS_SERVER . pipeline ( ) pipe . incr ( key , 1 ) if config . COOLOFF_TIME : pipe . expire ( key , config . COOLOFF_TIME ) new_value = pipe . execute ( ) [ 0 ] return new_value
given a key increment the value
239,184
def username_from_request ( request ) : if config . USERNAME_FORM_FIELD in request . POST : return request . POST [ config . USERNAME_FORM_FIELD ] [ : 255 ] return None
unloads username from default POST request
239,185
def get_user_attempts ( request , get_username = get_username_from_request , username = None ) : ip_address = get_ip ( request ) username = lower_username ( username or get_username ( request ) ) ip_count = REDIS_SERVER . get ( get_ip_attempt_cache_key ( ip_address ) ) if not ip_count : ip_count = 0 ip_count = int ( ip...
Returns number of access attempts for this ip username
239,186
def block_ip ( ip_address ) : if not ip_address : return if config . DISABLE_IP_LOCKOUT : return key = get_ip_blocked_cache_key ( ip_address ) if config . COOLOFF_TIME : REDIS_SERVER . set ( key , 'blocked' , config . COOLOFF_TIME ) else : REDIS_SERVER . set ( key , 'blocked' ) send_ip_block_signal ( ip_address )
given the ip block it
239,187
def block_username ( username ) : if not username : return if config . DISABLE_USERNAME_LOCKOUT : return key = get_username_blocked_cache_key ( username ) if config . COOLOFF_TIME : REDIS_SERVER . set ( key , 'blocked' , config . COOLOFF_TIME ) else : REDIS_SERVER . set ( key , 'blocked' ) send_username_block_signal ( ...
given the username block it .
239,188
def record_failed_attempt ( ip_address , username ) : ip_block = False if not config . DISABLE_IP_LOCKOUT : ip_count = increment_key ( get_ip_attempt_cache_key ( ip_address ) ) if ip_count > config . IP_FAILURE_LIMIT : block_ip ( ip_address ) ip_block = True user_block = False if username and not config . DISABLE_USERN...
record the failed login attempt if over limit return False if not over limit return True
239,189
def unblock_ip ( ip_address , pipe = None ) : do_commit = False if not pipe : pipe = REDIS_SERVER . pipeline ( ) do_commit = True if ip_address : pipe . delete ( get_ip_attempt_cache_key ( ip_address ) ) pipe . delete ( get_ip_blocked_cache_key ( ip_address ) ) if do_commit : pipe . execute ( )
unblock the given IP
239,190
def unblock_username ( username , pipe = None ) : do_commit = False if not pipe : pipe = REDIS_SERVER . pipeline ( ) do_commit = True if username : pipe . delete ( get_username_attempt_cache_key ( username ) ) pipe . delete ( get_username_blocked_cache_key ( username ) ) if do_commit : pipe . execute ( )
unblock the given Username
239,191
def reset_failed_attempts ( ip_address = None , username = None ) : pipe = REDIS_SERVER . pipeline ( ) unblock_ip ( ip_address , pipe = pipe ) unblock_username ( username , pipe = pipe ) pipe . execute ( )
reset the failed attempts for these ip s and usernames
239,192
def lockout_response ( request ) : if config . LOCKOUT_TEMPLATE : context = { 'cooloff_time_seconds' : config . COOLOFF_TIME , 'cooloff_time_minutes' : config . COOLOFF_TIME / 60 , 'failure_limit' : config . FAILURE_LIMIT , } return render ( request , config . LOCKOUT_TEMPLATE , context ) if config . LOCKOUT_URL : retu...
if we are locked out here is the response
239,193
def is_user_already_locked ( username ) : if username is None : return False if config . DISABLE_USERNAME_LOCKOUT : return False return REDIS_SERVER . get ( get_username_blocked_cache_key ( username ) )
Is this username already locked?
239,194
def is_source_ip_already_locked ( ip_address ) : if ip_address is None : return False if config . DISABLE_IP_LOCKOUT : return False return REDIS_SERVER . get ( get_ip_blocked_cache_key ( ip_address ) )
Is this IP already locked?
239,195
def is_already_locked ( request , get_username = get_username_from_request , username = None ) : user_blocked = is_user_already_locked ( username or get_username ( request ) ) ip_blocked = is_source_ip_already_locked ( get_ip ( request ) ) if config . LOCKOUT_BY_IP_USERNAME : return ip_blocked and user_blocked return i...
Parse the username & IP from the request and see if it s already locked .
239,196
def check_request ( request , login_unsuccessful , get_username = get_username_from_request , username = None ) : ip_address = get_ip ( request ) username = username or get_username ( request ) if not login_unsuccessful : reset_failed_attempts ( ip_address = ip_address , username = username ) return True else : return ...
check the request and process results
239,197
def add_login_attempt_to_db ( request , login_valid , get_username = get_username_from_request , username = None ) : if not config . STORE_ACCESS_ATTEMPTS : return username = username or get_username ( request ) user_agent = request . META . get ( 'HTTP_USER_AGENT' , '<unknown>' ) [ : 255 ] ip_address = get_ip ( reques...
Create a record for the login attempt If using celery call celery task if not call the method normally
239,198
def add_login_attempt_task ( user_agent , ip_address , username , http_accept , path_info , login_valid ) : store_login_attempt ( user_agent , ip_address , username , http_accept , path_info , login_valid )
Create a record for the login attempt
239,199
def store_login_attempt ( user_agent , ip_address , username , http_accept , path_info , login_valid ) : AccessAttempt . objects . create ( user_agent = user_agent , ip_address = ip_address , username = username , http_accept = http_accept , path_info = path_info , login_valid = login_valid , )
Store the login attempt to the db .