idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
10,500 | def similarity ( self , other : Trigram ) -> Tuple [ float , L ] : return max ( ( ( t % other , l ) for t , l in self . trigrams ) , key = lambda x : x [ 0 ] , ) | Returns the best matching score and the associated label . |
10,501 | def _exception_for ( self , code ) : if code in self . errors : return self . errors [ code ] elif 500 <= code < 599 : return exceptions . RemoteServerError else : return exceptions . UnknownError | Return the exception class suitable for the specified HTTP status code . |
10,502 | def setGroups ( self , * args , ** kwargs ) : requests = 0 groups = [ ] try : for gk in self [ 'groupKeys' ] : try : g = self . mambugroupclass ( entid = gk , * args , ** kwargs ) except AttributeError as ae : from . mambugroup import MambuGroup self . mambugroupclass = MambuGroup g = self . mambugroupclass ( entid = gk , * args , ** kwargs ) requests += 1 groups . append ( g ) except KeyError : pass self [ 'groups' ] = groups return requests | Adds the groups to which this client belongs . |
10,503 | def setBranch ( self , * args , ** kwargs ) : try : branch = self . mambubranchclass ( entid = self [ 'assignedBranchKey' ] , * args , ** kwargs ) except AttributeError as ae : from . mambubranch import MambuBranch self . mambubranchclass = MambuBranch branch = self . mambubranchclass ( entid = self [ 'assignedBranchKey' ] , * args , ** kwargs ) self [ 'assignedBranchName' ] = branch [ 'name' ] self [ 'assignedBranch' ] = branch return 1 | Adds the branch to which the client belongs . |
10,504 | def protected ( self , * tests , ** kwargs ) : _role = kwargs . pop ( 'role' , None ) _roles = kwargs . pop ( 'roles' , None ) or [ ] _csrf = kwargs . pop ( 'csrf' , None ) _url_sign_in = kwargs . pop ( 'url_sign_in' , None ) _request = kwargs . pop ( 'request' , None ) if _role : _roles . append ( _role ) _roles = [ to_unicode ( r ) for r in _roles ] _tests = tests _user_tests = kwargs def decorator ( f ) : @ functools . wraps ( f ) def wrapper ( * args , ** kwargs ) : logger = logging . getLogger ( __name__ ) request = _request or self . request or args and args [ 0 ] url_sign_in = self . _get_url_sign_in ( request , _url_sign_in ) user = self . get_user ( ) if not user : return self . _login_required ( request , url_sign_in ) if hasattr ( user , 'has_role' ) and _roles : if not user . has_role ( * _roles ) : logger . debug ( u'User `{0}`: has_role fail' . format ( user . login ) ) logger . debug ( u'User roles: {0}' . format ( [ r . name for r in user . roles ] ) ) return self . wsgi . raise_forbidden ( ) for test in _tests : test_pass = test ( user , * args , ** kwargs ) if not test_pass : logger . debug ( u'User `{0}`: test fail' . format ( user . login ) ) return self . wsgi . raise_forbidden ( ) for name , value in _user_tests . items ( ) : user_test = getattr ( user , name ) test_pass = user_test ( value , * args , ** kwargs ) if not test_pass : logger . debug ( u'User `{0}`: test fail' . format ( user . login ) ) return self . wsgi . raise_forbidden ( ) disable_csrf = _csrf == False if ( not self . wsgi . is_idempotent ( request ) and not disable_csrf ) or _csrf : if not self . csrf_token_is_valid ( request ) : logger . debug ( u'User `{0}`: invalid CSFR token' . format ( user . login ) ) return self . wsgi . raise_forbidden ( "CSFR token isn't valid" ) return f ( * args , ** kwargs ) return wrapper return decorator | Factory of decorators for limit the access to views . |
10,505 | def replace_flask_route ( self , bp , * args , ** kwargs ) : protected = self . protected def protected_route ( rule , ** options ) : def decorator ( f ) : endpoint = options . pop ( "endpoint" , f . __name__ ) protected_f = protected ( * args , ** kwargs ) ( f ) bp . add_url_rule ( rule , endpoint , protected_f , ** options ) return f return decorator bp . route = protected_route | Replace the Flask app . route or blueprint . route with a version that first apply the protected decorator to the view so all views are automatically protected . |
10,506 | def parse_query ( self , query ) : tree = pypeg2 . parse ( query , Main , whitespace = "" ) return tree . accept ( self . converter ) | Parse query string using given grammar |
10,507 | def decode_token ( token ) : if isinstance ( token , ( unicode , str ) ) : return _decode_token_compact ( token ) else : return _decode_token_json ( token ) | Top - level method to decode a JWT . Takes either a compact - encoded JWT with a single signature or a multi - sig JWT in the JSON - serialized format . |
10,508 | def _verify_multi ( self , token , verifying_keys , num_required = None ) : headers , payload , raw_signatures , signing_inputs = _unpack_token_json ( token ) if num_required is None : num_required = len ( raw_signatures ) if num_required > len ( verifying_keys ) : return False if len ( headers ) != len ( raw_signatures ) : raise DecodeError ( 'Header/signature mismatch' ) verifying_keys = [ load_verifying_key ( vk , self . crypto_backend ) for vk in verifying_keys ] for vk in verifying_keys : if vk . curve . name != verifying_keys [ 0 ] . curve . name : raise DecodeError ( "TODO: only support using keys from one curve per JWT" ) der_signatures = [ raw_to_der_signature ( rs , verifying_keys [ 0 ] . curve ) for rs in raw_signatures ] num_verified = 0 for ( signing_input , der_sig ) in zip ( signing_inputs , der_signatures ) : for vk in verifying_keys : verifier = self . _get_verifier ( vk , der_sig ) verifier . update ( signing_input ) try : verifier . verify ( ) num_verified += 1 verifying_keys . remove ( vk ) break except InvalidSignature : pass if num_verified >= num_required : break return ( num_verified >= num_required ) | Verify a JSON - formatted JWT signed by multiple keys is authentic . Optionally set a threshold of required valid signatures with num_required . Return True if valid Return False if not |
10,509 | def verify ( self , token , verifying_key_or_keys , num_required = None ) : if not isinstance ( verifying_key_or_keys , ( list , str , unicode ) ) : raise ValueError ( "Invalid verifying key(s): expected list or string" ) if isinstance ( verifying_key_or_keys , list ) : return self . _verify_multi ( token , verifying_key_or_keys , num_required = num_required ) else : return self . _verify_single ( token , str ( verifying_key_or_keys ) ) | Verify a compact - formated JWT or a JSON - formatted JWT signed by multiple keys . Return True if valid Return False if not valid |
10,510 | def activate_script ( self ) : self . _add_scope ( "script" ) self . scripts = { } self . script_files = [ "./scripts/script_*.txt" , "~/.cloudmesh/scripts/script_*.txt" ] self . _load_scripts ( self . script_files ) | activates the script command |
10,511 | def touch ( path ) : parentDirPath = os . path . dirname ( path ) PathOperations . safeMakeDirs ( parentDirPath ) with open ( path , "wb" ) : pass | Creates the given path as a file also creating intermediate directories if required . |
10,512 | def safeRmTree ( rootPath ) : shutil . rmtree ( rootPath , True ) return not os . path . exists ( rootPath ) | Deletes a tree and returns true if it was correctly deleted |
10,513 | def linearWalk ( rootPath , currentDirFilter = None ) : for dirTuple in os . walk ( rootPath ) : ( dirPath , dirNames , fileNames ) = dirTuple if currentDirFilter is not None and not currentDirFilter ( dirPath , dirNames , fileNames ) : continue for fileName in fileNames : yield LinearWalkItem ( dirPath , fileName ) | Returns a list of LinearWalkItem s one for each file in the tree whose root is rootPath . |
10,514 | def init_live_reload ( run ) : from asyncio import get_event_loop from . _live_reload import start_child loop = get_event_loop ( ) if run : loop . run_until_complete ( start_child ( ) ) else : get_event_loop ( ) . create_task ( start_child ( ) ) | Start the live reload task |
10,515 | def cmp_name ( first_node , second_node ) : if len ( first_node . children ) == len ( second_node . children ) : for first_child , second_child in zip ( first_node . children , second_node . children ) : for key in first_child . __dict__ . keys ( ) : if key . startswith ( '_' ) : continue if first_child . __dict__ [ key ] != second_child . __dict__ [ key ] : return 1 ret_val = cmp_name ( first_child , second_child ) if ret_val != 0 : return 1 else : return 1 return 0 | Compare two name recursively . |
10,516 | def parse_division ( l , c , line , root_node , last_section_node ) : name = line name = name . replace ( "." , "" ) tokens = [ t for t in name . split ( ' ' ) if t ] node = Name ( Name . Type . Division , l , c , '%s %s' % ( tokens [ 0 ] , tokens [ 1 ] ) ) root_node . add_child ( node ) last_div_node = node if last_section_node : last_section_node . end_line = l last_section_node = None return last_div_node , last_section_node | Extracts a division node from a line |
10,517 | def parse_section ( l , c , last_div_node , last_vars , line ) : name = line name = name . replace ( "." , "" ) node = Name ( Name . Type . Section , l , c , name ) last_div_node . add_child ( node ) last_section_node = node last_vars . clear ( ) return last_section_node | Extracts a section node from a line . |
10,518 | def parse_pic_field ( l , c , last_section_node , last_vars , line ) : parent_node = None raw_tokens = line . split ( " " ) tokens = [ ] for t in raw_tokens : if not t . isspace ( ) and t != "" : tokens . append ( t ) try : if tokens [ 0 ] . upper ( ) == "FD" : lvl = 1 else : lvl = int ( tokens [ 0 ] , 16 ) name = tokens [ 1 ] except ValueError : return None except IndexError : return None name = name . replace ( "." , "" ) if name in ALL_KEYWORDS or name in [ '-' , '/' ] : return None m = re . findall ( r'pic.*\.' , line , re . IGNORECASE ) if m : description = ' ' . join ( [ t for t in m [ 0 ] . split ( ' ' ) if t ] ) else : description = line try : index = description . lower ( ) . index ( 'value' ) except ValueError : description = description . replace ( '.' , '' ) else : description = description [ index : ] . replace ( 'value' , '' ) [ : 80 ] if lvl == int ( '78' , 16 ) : lvl = 1 if lvl == 1 : parent_node = last_section_node last_vars . clear ( ) else : levels = sorted ( last_vars . keys ( ) , reverse = True ) for lv in levels : if lv < lvl : parent_node = last_vars [ lv ] break if not parent_node : return None if not name or name . upper ( ) . strip ( ) == 'PIC' : name = 'FILLER' node = Name ( Name . Type . Variable , l , c , name , description ) parent_node . add_child ( node ) last_vars [ lvl ] = node levels = sorted ( last_vars . keys ( ) , reverse = True ) for l in levels : if l > lvl : last_vars . pop ( l ) return node | Parse a pic field line . Return A VariableNode or None in case of malformed code . |
10,519 | def parse_paragraph ( l , c , last_div_node , last_section_node , line ) : if not line . endswith ( '.' ) : return None name = line . replace ( "." , "" ) if name . strip ( ) == '' : return None if name . upper ( ) in ALL_KEYWORDS : return None parent_node = last_div_node if last_section_node is not None : parent_node = last_section_node node = Name ( Name . Type . Paragraph , l , c , name ) parent_node . add_child ( node ) return node | Extracts a paragraph node |
10,520 | def find ( self , name ) : for c in self . children : if c . name == name : return c result = c . find ( name ) if result : return result | Finds a possible child whose name match the name parameter . |
10,521 | def to_definition ( self ) : icon = { Name . Type . Root : icons . ICON_MIMETYPE , Name . Type . Division : icons . ICON_DIVISION , Name . Type . Section : icons . ICON_SECTION , Name . Type . Variable : icons . ICON_VAR , Name . Type . Paragraph : icons . ICON_FUNC } [ self . node_type ] d = Definition ( self . name , self . line , self . column , icon , self . description ) for ch in self . children : d . add_child ( ch . to_definition ( ) ) return d | Converts the name instance to a pyqode . core . share . Definition |
10,522 | def connectDb ( engine = dbeng , user = dbuser , password = dbpwd , host = dbhost , port = dbport , database = dbname , params = "?charset=utf8&use_unicode=1" , echoopt = False ) : return create_engine ( '%s://%s:%s@%s:%s/%s%s' % ( engine , user , password , host , port , database , params ) , echo = echoopt ) | Connect to database utility function . |
10,523 | def getbranchesurl ( idbranch , * args , ** kwargs ) : getparams = [ ] if kwargs : try : if kwargs [ "fullDetails" ] == True : getparams . append ( "fullDetails=true" ) else : getparams . append ( "fullDetails=false" ) except Exception as ex : pass try : getparams . append ( "offset=%s" % kwargs [ "offset" ] ) except Exception as ex : pass try : getparams . append ( "limit=%s" % kwargs [ "limit" ] ) except Exception as ex : pass branchidparam = "" if idbranch == "" else "/" + idbranch url = getmambuurl ( * args , ** kwargs ) + "branches" + branchidparam + ( "" if len ( getparams ) == 0 else "?" + "&" . join ( getparams ) ) return url | Request Branches URL . |
10,524 | def getcentresurl ( idcentre , * args , ** kwargs ) : getparams = [ ] if kwargs : try : if kwargs [ "fullDetails" ] == True : getparams . append ( "fullDetails=true" ) else : getparams . append ( "fullDetails=false" ) except Exception as ex : pass try : getparams . append ( "offset=%s" % kwargs [ "offset" ] ) except Exception as ex : pass try : getparams . append ( "limit=%s" % kwargs [ "limit" ] ) except Exception as ex : pass centreidparam = "" if idcentre == "" else "/" + idcentre url = getmambuurl ( * args , ** kwargs ) + "centres" + centreidparam + ( "" if len ( getparams ) == 0 else "?" + "&" . join ( getparams ) ) return url | Request Centres URL . |
10,525 | def getrepaymentsurl ( idcred , * args , ** kwargs ) : url = getmambuurl ( * args , ** kwargs ) + "loans/" + idcred + "/repayments" return url | Request loan Repayments URL . |
10,526 | def getloansurl ( idcred , * args , ** kwargs ) : getparams = [ ] if kwargs : try : if kwargs [ "fullDetails" ] == True : getparams . append ( "fullDetails=true" ) else : getparams . append ( "fullDetails=false" ) except Exception as ex : pass try : getparams . append ( "accountState=%s" % kwargs [ "accountState" ] ) except Exception as ex : pass try : getparams . append ( "branchId=%s" % kwargs [ "branchId" ] ) except Exception as ex : pass try : getparams . append ( "centreId=%s" % kwargs [ "centreId" ] ) except Exception as ex : pass try : getparams . append ( "creditOfficerUsername=%s" % kwargs [ "creditOfficerUsername" ] ) except Exception as ex : pass try : getparams . append ( "offset=%s" % kwargs [ "offset" ] ) except Exception as ex : pass try : getparams . append ( "limit=%s" % kwargs [ "limit" ] ) except Exception as ex : pass idcredparam = "" if idcred == "" else "/" + idcred url = getmambuurl ( * args , ** kwargs ) + "loans" + idcredparam + ( "" if len ( getparams ) == 0 else "?" + "&" . join ( getparams ) ) return url | Request Loans URL . |
10,527 | def getgroupurl ( idgroup , * args , ** kwargs ) : getparams = [ ] if kwargs : try : if kwargs [ "fullDetails" ] == True : getparams . append ( "fullDetails=true" ) else : getparams . append ( "fullDetails=false" ) except Exception as ex : pass try : getparams . append ( "creditOfficerUsername=%s" % kwargs [ "creditOfficerUsername" ] ) except Exception as ex : pass try : getparams . append ( "branchId=%s" % kwargs [ "branchId" ] ) except Exception as ex : pass try : getparams . append ( "centreId=%s" % kwargs [ "centreId" ] ) except Exception as ex : pass try : getparams . append ( "limit=%s" % kwargs [ "limit" ] ) except Exception as ex : pass try : getparams . append ( "offset=%s" % kwargs [ "offset" ] ) except Exception as ex : pass groupidparam = "" if idgroup == "" else "/" + idgroup url = getmambuurl ( * args , ** kwargs ) + "groups" + groupidparam + ( "" if len ( getparams ) == 0 else "?" + "&" . join ( getparams ) ) return url | Request Groups URL . |
10,528 | def getgrouploansurl ( idgroup , * args , ** kwargs ) : getparams = [ ] if kwargs : try : if kwargs [ "fullDetails" ] == True : getparams . append ( "fullDetails=true" ) else : getparams . append ( "fullDetails=false" ) except Exception as ex : pass try : getparams . append ( "accountState=%s" % kwargs [ "accountState" ] ) except Exception as ex : pass groupidparam = "/" + idgroup url = getmambuurl ( * args , ** kwargs ) + "groups" + groupidparam + "/loans" + ( "" if len ( getparams ) == 0 else "?" + "&" . join ( getparams ) ) return url | Request Group loans URL . |
10,529 | def getgroupcustominformationurl ( idgroup , customfield = "" , * args , ** kwargs ) : groupidparam = "/" + idgroup url = getmambuurl ( * args , ** kwargs ) + "groups" + groupidparam + "/custominformation" + ( ( "/" + customfield ) if customfield else "" ) return url | Request Group Custom Information URL . |
10,530 | def gettransactionsurl ( idcred , * args , ** kwargs ) : getparams = [ ] if kwargs : try : getparams . append ( "offset=%s" % kwargs [ "offset" ] ) except Exception as ex : pass try : getparams . append ( "limit=%s" % kwargs [ "limit" ] ) except Exception as ex : pass url = getmambuurl ( * args , ** kwargs ) + "loans/" + idcred + "/transactions" + ( "" if len ( getparams ) == 0 else "?" + "&" . join ( getparams ) ) return url | Request loan Transactions URL . |
10,531 | def getclienturl ( idclient , * args , ** kwargs ) : getparams = [ ] if kwargs : try : if kwargs [ "fullDetails" ] == True : getparams . append ( "fullDetails=true" ) else : getparams . append ( "fullDetails=false" ) except Exception as ex : pass try : getparams . append ( "firstName=%s" % kwargs [ "firstName" ] ) except Exception as ex : pass try : getparams . append ( "lastName=%s" % kwargs [ "lastName" ] ) except Exception as ex : pass try : getparams . append ( "idDocument=%s" % kwargs [ "idDocument" ] ) except Exception as ex : pass try : getparams . append ( "birthdate=%s" % kwargs [ "birthdate" ] ) except Exception as ex : pass try : getparams . append ( "state=%s" % kwargs [ "state" ] ) except Exception as ex : pass try : getparams . append ( "offset=%s" % kwargs [ "offset" ] ) except Exception as ex : pass try : getparams . append ( "limit=%s" % kwargs [ "limit" ] ) except Exception as ex : pass clientidparam = "" if idclient == "" else "/" + idclient url = getmambuurl ( * args , ** kwargs ) + "clients" + clientidparam + ( "" if len ( getparams ) == 0 else "?" + "&" . join ( getparams ) ) return url | Request Clients URL . |
10,532 | def getclientloansurl ( idclient , * args , ** kwargs ) : getparams = [ ] if kwargs : try : if kwargs [ "fullDetails" ] == True : getparams . append ( "fullDetails=true" ) else : getparams . append ( "fullDetails=false" ) except Exception as ex : pass try : getparams . append ( "accountState=%s" % kwargs [ "accountState" ] ) except Exception as ex : pass clientidparam = "/" + idclient url = getmambuurl ( * args , ** kwargs ) + "clients" + clientidparam + "/loans" + ( "" if len ( getparams ) == 0 else "?" + "&" . join ( getparams ) ) return url | Request Client loans URL . |
10,533 | def getclientcustominformationurl ( idclient , customfield = "" , * args , ** kwargs ) : clientidparam = "/" + idclient url = getmambuurl ( * args , ** kwargs ) + "clients" + clientidparam + "/custominformation" + ( ( "/" + customfield ) if customfield else "" ) return url | Request Client Custom Information URL . |
10,534 | def getuserurl ( iduser , * args , ** kwargs ) : getparams = [ ] if kwargs : try : if kwargs [ "fullDetails" ] == True : getparams . append ( "fullDetails=true" ) else : getparams . append ( "fullDetails=false" ) except Exception as ex : pass try : getparams . append ( "branchId=%s" % kwargs [ "branchId" ] ) except Exception as ex : pass try : getparams . append ( "offset=%s" % kwargs [ "offset" ] ) except Exception as ex : pass try : getparams . append ( "limit=%s" % kwargs [ "limit" ] ) except Exception as ex : pass useridparam = "" if iduser == "" else "/" + iduser url = getmambuurl ( * args , ** kwargs ) + "users" + useridparam + ( "" if len ( getparams ) == 0 else "?" + "&" . join ( getparams ) ) return url | Request Users URL . |
10,535 | def getproductsurl ( idproduct , * args , ** kwargs ) : productidparam = "" if idproduct == "" else "/" + idproduct url = getmambuurl ( * args , ** kwargs ) + "loanproducts" + productidparam return url | Request loan Products URL . |
10,536 | def gettasksurl ( dummyId = '' , * args , ** kwargs ) : getparams = [ ] if kwargs : try : getparams . append ( "username=%s" % kwargs [ "username" ] ) except Exception as ex : pass try : getparams . append ( "clientid=%s" % kwargs [ "clientId" ] ) except Exception as ex : pass try : getparams . append ( "groupid=%s" % kwargs [ "groupId" ] ) except Exception as ex : pass try : getparams . append ( "status=%s" % kwargs [ "status" ] ) except Exception as ex : getparams . append ( "status=OPEN" ) try : getparams . append ( "offset=%s" % kwargs [ "offset" ] ) except Exception as ex : pass try : getparams . append ( "limit=%s" % kwargs [ "limit" ] ) except Exception as ex : pass url = getmambuurl ( * args , ** kwargs ) + "tasks" + ( "" if len ( getparams ) == 0 else "?" + "&" . join ( getparams ) ) return url | Request Tasks URL . |
10,537 | def getactivitiesurl ( dummyId = '' , * args , ** kwargs ) : from datetime import datetime getparams = [ ] if kwargs : try : getparams . append ( "from=%s" % kwargs [ "fromDate" ] ) except Exception as ex : getparams . append ( "from=%s" % '1900-01-01' ) try : getparams . append ( "to=%s" % kwargs [ "toDate" ] ) except Exception as ex : hoy = datetime . now ( ) . strftime ( '%Y-%m-%d' ) getparams . append ( "to=%s" % hoy ) try : getparams . append ( "branchID=%s" % kwargs [ "branchId" ] ) except Exception as ex : pass try : getparams . append ( "clientID=%s" % kwargs [ "clientId" ] ) except Exception as ex : pass try : getparams . append ( "centreID=%s" % kwargs [ "centreId" ] ) except Exception as ex : pass try : getparams . append ( "userID=%s" % kwargs [ "userId" ] ) except Exception as ex : pass try : getparams . append ( "loanAccountID=%s" % kwargs [ "loanAccountId" ] ) except Exception as ex : pass try : getparams . append ( "groupID=%s" % kwargs [ "groupId" ] ) except Exception as ex : pass try : getparams . append ( "limit=%s" % kwargs [ "limit" ] ) except Exception as ex : pass url = getmambuurl ( * args , ** kwargs ) + "activities" + ( "" if len ( getparams ) == 0 else "?" + "&" . join ( getparams ) ) return url | Request Activities URL . |
10,538 | def getrolesurl ( idrole = '' , * args , ** kwargs ) : url = getmambuurl ( * args , ** kwargs ) + "userroles" + ( ( "/" + idrole ) if idrole else "" ) return url | Request Roles URL . |
10,539 | def strip_tags ( html ) : from html . parser import HTMLParser class MLStripper ( HTMLParser ) : def __init__ ( self ) : try : super ( ) . __init__ ( ) except TypeError as e : pass self . reset ( ) self . fed = [ ] def handle_data ( self , d ) : self . fed . append ( d ) def get_data ( self ) : return '' . join ( self . fed ) s = MLStripper ( ) s . feed ( html . replace ( " " , " " ) ) return s . get_data ( ) | Stripts HTML tags from text . |
10,540 | def strip_consecutive_repeated_char ( s , ch ) : sdest = "" for i , c in enumerate ( s ) : if i != 0 and s [ i ] == ch and s [ i ] == s [ i - 1 ] : continue sdest += s [ i ] return sdest | Strip characters in a string which are consecutively repeated . |
10,541 | def encoded_dict ( in_dict ) : out_dict = { } for k , v in in_dict . items ( ) : if isinstance ( v , unicode ) : if sys . version_info < ( 3 , 0 ) : v = v . encode ( 'utf8' ) elif isinstance ( v , str ) : if sys . version_info < ( 3 , 0 ) : v . decode ( 'utf8' ) out_dict [ k ] = v return out_dict | Encode every value of a dict to UTF - 8 . |
10,542 | def backup_db ( callback , bool_func , output_fname , * args , ** kwargs ) : from datetime import datetime try : verbose = kwargs [ 'verbose' ] except KeyError : verbose = False try : retries = kwargs [ 'retries' ] except KeyError : retries = - 1 try : force_download_latest = bool ( kwargs [ 'force_download_latest' ] ) except KeyError : force_download_latest = False if verbose : log = open ( '/tmp/log_mambu_backup' , 'a' ) log . write ( datetime . now ( ) . strftime ( '%Y-%m-%d %H:%M:%S' ) + " - Mambu DB Backup\n" ) log . flush ( ) user = kwargs . pop ( 'user' , apiuser ) pwd = kwargs . pop ( 'pwd' , apipwd ) data = { 'callback' : callback } try : posturl = iriToUri ( getmambuurl ( * args , ** kwargs ) + "database/backup" ) if verbose : log . write ( "open url: " + posturl + "\n" ) log . flush ( ) resp = requests . post ( posturl , data = data , headers = { 'content-type' : 'application/json' } , auth = ( apiuser , apipwd ) ) except Exception as ex : mess = "Error requesting backup: %s" % repr ( ex ) if verbose : log . write ( mess + "\n" ) log . close ( ) raise MambuError ( mess ) if resp . status_code != 200 : mess = "Error posting request for backup: %s" % resp . content if verbose : log . write ( mess + "\n" ) log . close ( ) raise MambuCommError ( mess ) data [ 'latest' ] = True while retries and not bool_func ( ) : if verbose : log . write ( "waiting...\n" ) log . flush ( ) sleep ( 10 ) retries -= 1 if retries < 0 : retries = - 1 if not retries : mess = "Tired of waiting, giving up..." if verbose : log . write ( mess + "\n" ) log . flush ( ) if not force_download_latest : if verbose : log . close ( ) raise MambuError ( mess ) else : data [ 'latest' ] = False sleep ( 30 ) geturl = iriToUri ( getmambuurl ( * args , ** kwargs ) + "database/backup/LATEST" ) if verbose : log . write ( "open url: " + geturl + "\n" ) log . flush ( ) resp = requests . get ( geturl , auth = ( apiuser , apipwd ) ) if resp . status_code != 200 : mess = "Error getting database backup: %s" % resp . content if verbose : log . write ( mess + "\n" ) log . close ( ) raise MambuCommError ( mess ) if verbose : log . write ( "saving...\n" ) log . flush ( ) with open ( output_fname , "w" ) as fw : fw . write ( resp . content ) if verbose : log . write ( "DONE!\n" ) log . close ( ) return data | Backup Mambu Database via REST API . |
10,543 | def memoize ( func ) : cache_name = '__CACHED_{}' . format ( func . __name__ ) def wrapper ( self , * args ) : cache = getattr ( self , cache_name , None ) if cache is None : cache = { } setattr ( self , cache_name , cache ) if args not in cache : cache [ args ] = func ( self , * args ) return cache [ args ] return wrapper | Provides memoization for methods on a specific instance . Results are cached for given parameter list . |
10,544 | def _pathway_side_information ( pathway_positive_series , pathway_negative_series , index ) : positive_series_label = pd . Series ( [ "pos" ] * len ( pathway_positive_series ) ) negative_series_label = pd . Series ( [ "neg" ] * len ( pathway_negative_series ) ) side_information = positive_series_label . append ( negative_series_label ) side_information . index = index side_information . name = "side" return side_information | Create the pandas . Series containing the side labels that correspond to each pathway based on the user - specified gene signature definition . |
10,545 | def _significant_pathways_dataframe ( pvalue_information , side_information , alpha ) : significant_pathways = pd . concat ( [ pvalue_information , side_information ] , axis = 1 ) below_alpha , qvalues , _ , _ = multipletests ( significant_pathways [ "p-value" ] , alpha = alpha , method = "fdr_bh" ) below_alpha = pd . Series ( below_alpha , index = pvalue_information . index , name = "pass" ) qvalues = pd . Series ( qvalues , index = pvalue_information . index , name = "q-value" ) significant_pathways = pd . concat ( [ significant_pathways , below_alpha , qvalues ] , axis = 1 ) significant_pathways = significant_pathways [ significant_pathways [ "pass" ] ] significant_pathways . drop ( "pass" , axis = 1 , inplace = True ) significant_pathways . loc [ : , "pathway" ] = significant_pathways . index return significant_pathways | Create the significant pathways pandas . DataFrame . Given the p - values corresponding to each pathway in a feature apply the FDR correction for multiple testing and remove those that do not have a q - value of less than alpha . |
10,546 | async def flush ( self , request : Request , stacks : List [ Stack ] ) : ns = await self . expand_stacks ( request , stacks ) ns = self . split_stacks ( ns ) ns = self . clean_stacks ( ns ) await self . next ( request , [ Stack ( x ) for x in ns ] ) | For all stacks to be sent append a pause after each text layer . |
10,547 | def split_stacks ( self , stacks : List [ List [ BaseLayer ] ] ) -> List [ List [ BaseLayer ] ] : ns : List [ List [ BaseLayer ] ] = [ ] for stack in stacks : cur : List [ BaseLayer ] = [ ] for layer in stack : if cur and isinstance ( layer , lyr . RawText ) : ns . append ( cur ) cur = [ ] cur . append ( layer ) if cur : ns . append ( cur ) return ns | First step of the stacks cleanup process . We consider that if inside a stack there s a text layer showing up then it s the beginning of a new stack and split upon that . |
10,548 | async def expand ( self , request : Request , layer : BaseLayer ) : if isinstance ( layer , lyr . RawText ) : t = self . reading_time ( layer . text ) yield layer yield lyr . Sleep ( t ) elif isinstance ( layer , lyr . MultiText ) : texts = await render ( layer . text , request , True ) for text in texts : t = self . reading_time ( text ) yield lyr . RawText ( text ) yield lyr . Sleep ( t ) elif isinstance ( layer , lyr . Text ) : text = await render ( layer . text , request ) t = self . reading_time ( text ) yield lyr . RawText ( text ) yield lyr . Sleep ( t ) else : yield layer | Expand a layer into a list of layers including the pauses . |
10,549 | def reading_time ( self , text : TextT ) : wc = re . findall ( r'\w+' , text ) period = 60.0 / settings . USERS_READING_SPEED return float ( len ( wc ) ) * period + settings . USERS_READING_BUBBLE_START | Computes the time in seconds that the user will need to read a bubble containing the text passed as parameter . |
10,550 | async def flush ( self , request : Request , stacks : List [ Stack ] ) : ns : List [ Stack ] = [ ] for stack in stacks : ns . extend ( self . typify ( stack ) ) if len ( ns ) > 1 and ns [ - 1 ] == Stack ( [ lyr . Typing ( ) ] ) : ns [ - 1 ] . get_layer ( lyr . Typing ) . active = False await self . next ( request , ns ) | Add a typing stack after each stack . |
10,551 | async def pre_handle ( self , request : Request , responder : 'Responder' ) : responder . send ( [ lyr . Typing ( ) ] ) await responder . flush ( request ) responder . clear ( ) await self . next ( request , responder ) | Start typing right when the message is received . |
10,552 | async def get_friendly_name ( self ) -> Text : if 'first_name' not in self . _user : user = await self . _get_full_user ( ) else : user = self . _user return user . get ( 'first_name' ) | Let s use the first name of the user as friendly name . In some cases the user object is incomplete and in those cases the full user is fetched . |
10,553 | def _get_chat ( self ) -> Dict : if 'callback_query' in self . _update : query = self . _update [ 'callback_query' ] if 'message' in query : return query [ 'message' ] [ 'chat' ] else : return { 'id' : query [ 'chat_instance' ] } elif 'inline_query' in self . _update : return patch_dict ( self . _update [ 'inline_query' ] [ 'from' ] , is_inline_query = True , ) elif 'message' in self . _update : return self . _update [ 'message' ] [ 'chat' ] | As Telegram changes where the chat object is located in the response this method tries to be smart about finding it in the right place . |
10,554 | def send ( self , stack : Layers ) : if not isinstance ( stack , Stack ) : stack = Stack ( stack ) if 'callback_query' in self . _update and stack . has_layer ( Update ) : layer = stack . get_layer ( Update ) try : msg = self . _update [ 'callback_query' ] [ 'message' ] except KeyError : layer . inline_message_id = self . _update [ 'callback_query' ] [ 'inline_message_id' ] else : layer . chat_id = msg [ 'chat' ] [ 'id' ] layer . message_id = msg [ 'message_id' ] if stack . has_layer ( AnswerCallbackQuery ) : self . _acq = stack . get_layer ( AnswerCallbackQuery ) stack = Stack ( [ l for l in stack . layers if not isinstance ( l , AnswerCallbackQuery ) ] ) if stack . has_layer ( Reply ) : layer = stack . get_layer ( Reply ) if 'message' in self . _update : layer . message = self . _update [ 'message' ] elif 'callback_query' in self . _update : layer . message = self . _update [ 'callback_query' ] [ 'message' ] if 'inline_query' in self . _update and stack . has_layer ( AnswerInlineQuery ) : a = stack . get_layer ( AnswerInlineQuery ) a . inline_query_id = self . _update [ 'inline_query' ] [ 'id' ] if stack . layers : return super ( TelegramResponder , self ) . send ( stack ) | Intercept any potential AnswerCallbackQuery before adding the stack to the output buffer . |
10,555 | async def flush ( self , request : BernardRequest ) : if self . _acq and 'callback_query' in self . _update : try : cbq_id = self . _update [ 'callback_query' ] [ 'id' ] except KeyError : pass else : await self . platform . call ( 'answerCallbackQuery' , ** ( await self . _acq . serialize ( cbq_id ) ) ) return await super ( TelegramResponder , self ) . flush ( request ) | If there s a AnswerCallbackQuery scheduled for reply place the call before actually flushing the buffer . |
10,556 | async def receive_updates ( self , request : Request ) : body = await request . read ( ) try : content = ujson . loads ( body ) except ValueError : return json_response ( { 'error' : True , 'message' : 'Cannot decode body' , } , status = 400 ) logger . debug ( 'Received from Telegram: %s' , content ) message = TelegramMessage ( content , self ) responder = TelegramResponder ( content , self ) await self . _notify ( message , responder ) return json_response ( { 'error' : False , } ) | Handle updates from Telegram |
10,557 | def make_url ( self , method ) : token = self . settings ( ) [ 'token' ] return TELEGRAM_URL . format ( token = quote ( token ) , method = quote ( method ) , ) | Generate a Telegram URL for this bot . |
10,558 | async def call ( self , method : Text , _ignore : Set [ Text ] = None , ** params : Any ) : logger . debug ( 'Calling Telegram %s(%s)' , method , params ) url = self . make_url ( method ) headers = { 'content-type' : 'application/json' , } post = self . session . post ( url , data = ujson . dumps ( params ) , headers = headers , ) async with post as r : out = await self . _handle_telegram_response ( r , _ignore ) logger . debug ( 'Telegram replied: %s' , out ) return out | Call a telegram method |
10,559 | async def _handle_telegram_response ( self , response , ignore = None ) : if ignore is None : ignore = set ( ) ok = response . status == 200 try : data = await response . json ( ) if not ok : desc = data [ 'description' ] if desc in ignore : return raise PlatformOperationError ( 'Telegram replied with an error: {}' . format ( desc ) ) except ( ValueError , TypeError , KeyError ) : raise PlatformOperationError ( 'An unknown Telegram error occurred' ) return data | Parse a response from Telegram . If there s an error an exception will be raised with an explicative message . |
10,560 | def make_hook_path ( self ) : token = self . settings ( ) [ 'token' ] h = sha256 ( ) h . update ( token . encode ( ) ) key = str ( h . hexdigest ( ) ) return f'/hooks/telegram/{key}' | Compute the path to the hook URL |
10,561 | async def _deferred_init ( self ) : hook_path = self . make_hook_path ( ) url = urljoin ( settings . BERNARD_BASE_URL , hook_path ) await self . call ( 'setWebhook' , url = url ) logger . info ( 'Setting Telegram webhook to "%s"' , url ) | Register the web hook onto which Telegram should send its messages . |
10,562 | async def _send_text ( self , request : Request , stack : Stack , parse_mode : Optional [ Text ] = None ) : parts = [ ] chat_id = request . message . get_chat_id ( ) for layer in stack . layers : if isinstance ( layer , ( lyr . Text , lyr . RawText , lyr . Markdown ) ) : text = await render ( layer . text , request ) parts . append ( text ) for part in parts [ : - 1 ] : await self . call ( 'sendMessage' , text = part , chat_id = chat_id , ) msg = { 'text' : parts [ - 1 ] , 'chat_id' : chat_id , } if parse_mode is not None : msg [ 'parse_mode' ] = parse_mode await set_reply_markup ( msg , request , stack ) if stack . has_layer ( Reply ) : reply = stack . get_layer ( Reply ) if reply . message : msg [ 'reply_to_message_id' ] = reply . message [ 'message_id' ] if stack . has_layer ( Update ) : update = stack . get_layer ( Update ) if update . inline_message_id : msg [ 'inline_message_id' ] = update . inline_message_id del msg [ 'chat_id' ] else : msg [ 'message_id' ] = update . message_id await self . call ( 'editMessageText' , { 'Bad Request: message is not modified' } , ** msg ) else : await self . call ( 'sendMessage' , ** msg ) | Base function for sending text |
10,563 | async def _send_sleep ( self , request : Request , stack : Stack ) : duration = stack . get_layer ( lyr . Sleep ) . duration await sleep ( duration ) | Sleep for the amount of time specified in the Sleep layer |
10,564 | async def _send_typing ( self , request : Request , stack : Stack ) : t = stack . get_layer ( lyr . Typing ) if t . active : await self . call ( 'sendChatAction' , chat_id = request . message . get_chat_id ( ) , action = 'typing' , ) | In telegram the typing stops when the message is received . Thus there is no typing stops messages to send . The API is only called when typing must start . |
10,565 | def create_app ( metadata , processors = None , pipes = None ) : instance = Application ( metadata ) import_processors . process ( instance , [ ] , imports = [ "archive = holocron.processors.archive:process" , "commonmark = holocron.processors.commonmark:process" , "feed = holocron.processors.feed:process" , "frontmatter = holocron.processors.frontmatter:process" , "import-processors = holocron.processors.import_processors:process" , "jinja2 = holocron.processors.jinja2:process" , "markdown = holocron.processors.markdown:process" , "metadata = holocron.processors.metadata:process" , "pipe = holocron.processors.pipe:process" , "prettyuri = holocron.processors.prettyuri:process" , "restructuredtext = holocron.processors.restructuredtext:process" , "save = holocron.processors.save:process" , "sitemap = holocron.processors.sitemap:process" , "source = holocron.processors.source:process" , "todatetime = holocron.processors.todatetime:process" , "when = holocron.processors.when:process" , ] ) for name , processor in ( processors or { } ) . items ( ) : instance . add_processor ( name , processor ) for name , pipeline in ( pipes or { } ) . items ( ) : instance . add_pipe ( name , pipeline ) return instance | Return an application instance with processors & pipes setup . |
10,566 | async def page_view ( self , url : str , title : str , user_id : str , user_lang : str = '' ) -> None : ga_url = 'https://www.google-analytics.com/collect' args = { 'v' : '1' , 'ds' : 'web' , 'de' : 'UTF-8' , 'tid' : self . ga_id , 'cid' : self . hash_user_id ( user_id ) , 't' : 'pageview' , 'dh' : self . ga_domain , 'dp' : url , 'dt' : title , } if user_lang : args [ 'ul' ] = user_lang logger . debug ( 'GA settings = %s' , urlencode ( args ) ) async with self . session . post ( ga_url , data = args ) as r : if r . status == 200 : logger . debug ( f'Sent to GA {url} ({title}) for user {user_id}' ) else : logger . warning ( f'Could not contact GA' ) | Log a page view . |
10,567 | def get ( self , username = None , password = None , headers = { } ) : if all ( ( username , password , ) ) : return BasicAuth ( username , password , headers ) elif not any ( ( username , password , ) ) : return AnonymousAuth ( headers ) else : if username is None : data = ( "username" , username , ) else : data = ( "Password" , password , ) msg = "%s must have a value (instead of '%s')" % ( data [ 0 ] , data [ 1 ] ) raise ValueError ( msg ) | Factory method to get the correct AuthInfo object . |
10,568 | def populate_request_data ( self , request_args ) : request_args [ 'auth' ] = HTTPBasicAuth ( self . _username , self . _password ) return request_args | Add the authentication info to the supplied dictionary . |
10,569 | def register_workflow ( self , name , workflow ) : assert name not in self . workflows self . workflows [ name ] = workflow | Register an workflow to be showed in the workflows list . |
10,570 | def add_header ( self , name , value ) : self . _headers . setdefault ( _hkey ( name ) , [ ] ) . append ( _hval ( value ) ) | Add an additional response header not removing duplicates . |
10,571 | def load_module ( self , path , squash = True ) : config_obj = load ( path ) obj = { key : getattr ( config_obj , key ) for key in dir ( config_obj ) if key . isupper ( ) } if squash : self . load_dict ( obj ) else : self . update ( obj ) return self | Load values from a Python module . |
10,572 | def _set_virtual ( self , key , value ) : if key in self and key not in self . _virtual_keys : return self . _virtual_keys . add ( key ) if key in self and self [ key ] is not value : self . _on_change ( key , value ) dict . __setitem__ ( self , key , value ) for overlay in self . _iter_overlays ( ) : overlay . _set_virtual ( key , value ) | Recursively set or update virtual keys . Do nothing if non - virtual value is present . |
10,573 | def _delete_virtual ( self , key ) : if key not in self . _virtual_keys : return if key in self : self . _on_change ( key , None ) dict . __delitem__ ( self , key ) self . _virtual_keys . discard ( key ) for overlay in self . _iter_overlays ( ) : overlay . _delete_virtual ( key ) | Recursively delete virtual entry . Do nothing if key is not virtual . |
10,574 | def meta_set ( self , key , metafield , value ) : self . _meta . setdefault ( key , { } ) [ metafield ] = value | Set the meta field for a key to a new value . |
10,575 | def filename ( self ) : fname = self . raw_filename if not isinstance ( fname , unicode ) : fname = fname . decode ( 'utf8' , 'ignore' ) fname = normalize ( 'NFKD' , fname ) fname = fname . encode ( 'ASCII' , 'ignore' ) . decode ( 'ASCII' ) fname = os . path . basename ( fname . replace ( '\\' , os . path . sep ) ) fname = re . sub ( r'[^a-zA-Z0-9-_.\s]' , '' , fname ) . strip ( ) fname = re . sub ( r'[-\s]+' , '-' , fname ) . strip ( '.-' ) return fname [ : 255 ] or 'empty' | Name of the file on the client file system but normalized to ensure file system compatibility . An empty filename is returned as empty . |
10,576 | async def render ( text : TransText , request : Optional [ 'Request' ] , multi_line = False ) -> Union [ Text , List [ Text ] ] : if isinstance ( text , str ) : out = [ text ] elif isinstance ( text , StringToTranslate ) : out = await text . render_list ( request ) else : raise TypeError ( 'Provided text cannot be rendered' ) if multi_line : return out else : return ' ' . join ( out ) | Render either a normal string either a string to translate into an actual string for the specified request . |
10,577 | def score ( self , flags : Flags ) -> int : score = 0 for k , v in flags . items ( ) : if self . flags . get ( k ) == v : score += 1 return score | Counts how many of the flags can be matched |
10,578 | def best_for_flags ( self , flags : Flags ) -> List [ TransItem ] : best_score : int = 0 best_list : List [ TransItem ] = [ ] for item in self . items : score = item . score ( flags ) if score == best_score : best_list . append ( item ) elif score > best_score : best_list = [ item ] best_score = score return best_list | Given flags find all items of this sentence that have an equal matching score and put them in a list . |
10,579 | def render ( self , flags : Flags ) -> Text : return random . choice ( self . best_for_flags ( flags ) ) . value | Chooses a random sentence from the list and returns it . |
10,580 | def update ( self , new : 'Sentence' , flags : Flags ) : items = [ i for i in self . items if i . flags != flags ] items . extend ( new . items ) self . items = items | Erase items with the specified flags and insert the new items from the other sentence instead . |
10,581 | def render ( self , flags : Flags ) -> List [ Text ] : return [ x . render ( flags ) for x in self . sentences ] | Returns a list of randomly chosen outcomes for each sentence of the list . |
10,582 | def append ( self , item : TransItem ) : if not ( 1 <= item . index <= settings . I18N_MAX_SENTENCES_PER_GROUP ) : return if len ( self . sentences ) < item . index : for _ in range ( len ( self . sentences ) , item . index ) : self . sentences . append ( Sentence ( ) ) self . sentences [ item . index - 1 ] . append ( item ) | Append an item to the list . If there is not enough sentences in the list then the list is extended as needed . |
10,583 | def update ( self , group : 'SentenceGroup' , flags : Flags ) -> None : to_append = [ ] for old , new in zip_longest ( self . sentences , group . sentences ) : if old is None : old = Sentence ( ) to_append . append ( old ) if new is None : new = Sentence ( ) old . update ( new , flags ) self . sentences . extend ( to_append ) | This object is considered to be a global sentence group while the other one is flags - specific . All data related to the specified flags will be overwritten by the content of the specified group . |
10,584 | def extract ( self ) : out = { } for key , group in self . data . items ( ) : out [ key ] = group return out | Extract only the valid sentence groups into a dictionary . |
10,585 | def append ( self , item : TransItem ) : self . data [ item . key ] . append ( item ) | Append an item to the internal dictionary . |
10,586 | def _init_loaders ( self ) -> None : for loader in settings . I18N_TRANSLATION_LOADERS : loader_class = import_class ( loader [ 'loader' ] ) instance = loader_class ( ) instance . on_update ( self . update ) run ( instance . load ( ** loader [ 'params' ] ) ) | This creates the loaders instances and subscribes to their updates . |
10,587 | def update_lang ( self , lang : Optional [ Text ] , data : List [ Tuple [ Text , Text ] ] , flags : Flags ) : sd = SortingDict ( ) for item in ( self . parse_item ( x [ 0 ] , x [ 1 ] , flags ) for x in data ) : if item : sd . append ( item ) if lang not in self . dict : self . dict [ lang ] = { } d = self . dict [ lang ] for k , v in sd . extract ( ) . items ( ) : if k not in d : d [ k ] = SentenceGroup ( ) d [ k ] . update ( v , flags ) | Update translations for one specific lang |
10,588 | def update ( self , data : TransDict , flags : Flags ) : for lang , lang_data in data . items ( ) : self . update_lang ( lang , lang_data , flags ) | Update all langs at once |
10,589 | def get ( self , key : Text , count : Optional [ int ] = None , formatter : Formatter = None , locale : Text = None , params : Optional [ Dict [ Text , Any ] ] = None , flags : Optional [ Flags ] = None ) -> List [ Text ] : if params is None : params = { } if count is not None : raise TranslationError ( 'Count parameter is not supported yet' ) locale = self . choose_locale ( locale ) try : group : SentenceGroup = self . dict [ locale ] [ key ] except KeyError : raise MissingTranslationError ( 'Translation "{}" does not exist' . format ( key ) ) try : trans = group . render ( flags or { } ) out = [ ] for line in trans : if not formatter : out . append ( line . format ( ** params ) ) else : out . append ( formatter . format ( line , ** params ) ) except KeyError as e : raise MissingParamError ( 'Parameter "{}" missing to translate "{}"' . format ( e . args [ 0 ] , key ) ) else : return out | Get the appropriate translation given the specified parameters . |
10,590 | async def _resolve_params ( self , params : Dict [ Text , Any ] , request : Optional [ 'Request' ] ) : out = { } for k , v in params . items ( ) : if isinstance ( v , StringToTranslate ) : out [ k ] = await render ( v , request ) else : out [ k ] = v return out | If any StringToTranslate was passed as parameter then it is rendered at this moment . |
10,591 | async def render_list ( self , request = None ) -> List [ Text ] : from bernard . middleware import MiddlewareManager if request : tz = await request . user . get_timezone ( ) locale = await request . get_locale ( ) flags = await request . get_trans_flags ( ) else : tz = None locale = self . wd . list_locales ( ) [ 0 ] flags = { } rp = MiddlewareManager . instance ( ) . get ( 'resolve_trans_params' , self . _resolve_params ) resolved_params = await rp ( self . params , request ) f = I18nFormatter ( self . wd . choose_locale ( locale ) , tz ) return self . wd . get ( self . key , self . count , f , locale , resolved_params , flags , ) | Render the translation as a list if there is multiple strings for this single key . |
10,592 | def send ( self , stack : Layers ) : if not isinstance ( stack , Stack ) : stack = Stack ( stack ) if not self . platform . accept ( stack ) : raise UnacceptableStack ( 'The platform does not allow "{}"' . format ( stack . describe ( ) ) ) self . _stacks . append ( stack ) | Add a message stack to the send list . |
10,593 | async def flush ( self , request : 'Request' ) : from bernard . middleware import MiddlewareManager for stack in self . _stacks : await stack . convert_media ( self . platform ) func = MiddlewareManager . instance ( ) . get ( 'flush' , self . _flush ) await func ( request , self . _stacks ) | Send all queued messages . |
10,594 | async def make_transition_register ( self , request : 'Request' ) : register = { } for stack in self . _stacks : register = await stack . patch_register ( register , request ) return register | Use all underlying stacks to generate the next transition register . |
10,595 | def preloop ( self ) : lines = textwrap . dedent ( self . banner ) . split ( "\n" ) for line in lines : Console . _print ( "BLUE" , "" , line ) | adds the banner to the preloop |
10,596 | def getDebt ( self ) : debt = float ( self [ 'principalBalance' ] ) + float ( self [ 'interestBalance' ] ) debt += float ( self [ 'feesBalance' ] ) + float ( self [ 'penaltyBalance' ] ) return debt | Sums up all the balances of the account and returns them . |
10,597 | def setRepayments ( self , * args , ** kwargs ) : def duedate ( repayment ) : try : return repayment [ 'dueDate' ] except KeyError as kerr : return datetime . now ( ) try : reps = self . mamburepaymentsclass ( entid = self [ 'id' ] , * args , ** kwargs ) except AttributeError as ae : from . mamburepayment import MambuRepayments self . mamburepaymentsclass = MambuRepayments reps = self . mamburepaymentsclass ( entid = self [ 'id' ] , * args , ** kwargs ) reps . attrs = sorted ( reps . attrs , key = duedate ) self [ 'repayments' ] = reps return 1 | Adds the repayments for this loan to a repayments field . |
10,598 | def setTransactions ( self , * args , ** kwargs ) : def transactionid ( transaction ) : try : return transaction [ 'transactionId' ] except KeyError as kerr : return None try : trans = self . mambutransactionsclass ( entid = self [ 'id' ] , * args , ** kwargs ) except AttributeError as ae : from . mambutransaction import MambuTransactions self . mambutransactionsclass = MambuTransactions trans = self . mambutransactionsclass ( entid = self [ 'id' ] , * args , ** kwargs ) trans . attrs = sorted ( trans . attrs , key = transactionid ) self [ 'transactions' ] = trans return 1 | Adds the transactions for this loan to a transactions field . |
10,599 | def setCentre ( self , * args , ** kwargs ) : try : centre = self . mambucentreclass ( entid = self [ 'assignedCentreKey' ] , * args , ** kwargs ) except AttributeError as ae : from . mambucentre import MambuCentre self . mambucentreclass = MambuCentre centre = self . mambucentreclass ( entid = self [ 'assignedCentreKey' ] , * args , ** kwargs ) self [ 'assignedCentreName' ] = centre [ 'name' ] self [ 'assignedCentre' ] = centre return 1 | Adds the centre for this loan to a assignedCentre field . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.