signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def smart_generic_inlineformset_factory ( model , request , form = ModelForm , formset = BaseGenericInlineFormSet , ct_field = 'content_type' , fk_field = 'object_id' , fields = None , exclude = None , extra = 3 , can_order = False , can_delete = True , min_num = None , max_num = None , formfield_callback = None , widg...
opts = model . _meta # if there is no field called ` ct _ field ` let the exception propagate ct_field = opts . get_field ( ct_field ) if not isinstance ( ct_field , models . ForeignKey ) or ct_field . related_model != ContentType : raise Exception ( "fk_name '%s' is not a ForeignKey to ContentType" % ct_field ) fk...
def verify ( address , plaintext , scriptSigb64 ) : """Verify that a given plaintext is signed by the given scriptSig , given the address"""
assert isinstance ( address , str ) assert isinstance ( scriptSigb64 , str ) scriptSig = base64 . b64decode ( scriptSigb64 ) hash_hex = hashlib . sha256 ( plaintext ) . hexdigest ( ) vb = keylib . b58check . b58check_version_byte ( address ) if vb == bitcoin_blockchain . version_byte : return verify_singlesig ( add...
def etau_madau ( wave , z , ** kwargs ) : """Madau 1995 extinction for a galaxy at given redshift . This is the Lyman - alpha prescription from the photo - z code BPZ . The Lyman - alpha forest approximately has an effective " throughput " which is a function of redshift and rest - frame wavelength . One ...
if not isinstance ( z , numbers . Real ) : raise exceptions . SynphotError ( 'Redshift must be a real scalar number.' ) if np . isscalar ( wave ) or len ( wave ) <= 1 : raise exceptions . SynphotError ( 'Wavelength has too few data points' ) wave = units . validate_quantity ( wave , u . AA , ** kwargs ) . value...
def show ( self , item , variant ) : """Show a variant . : param item : Item object or id : param variant : Variant object or id : return :"""
url = self . _build_url ( self . endpoint . show ( item , variant ) ) return self . _get ( url )
def get_memes_gallery ( self , sort = 'viral' , window = 'week' , limit = None ) : """Return a list of gallery albums / images submitted to the memes gallery The url for the memes gallery is : http : / / imgur . com / g / memes : param sort : viral | time | top - defaults to viral : param window : Change the ...
url = ( self . _base_url + "/3/gallery/g/memes/{0}/{1}/{2}" . format ( sort , window , '{}' ) ) resp = self . _send_request ( url , limit = limit ) return [ _get_album_or_image ( thing , self ) for thing in resp ]
def search ( self ) : """Handle the search request ."""
search = self . document_class ( ) . search ( ) # pylint : disable = not - callable search = self . custom_filter ( search ) search = self . filter_search ( search ) search = self . order_search ( search ) search = self . filter_permissions ( search ) if search . count ( ) > ELASTICSEARCH_SIZE : limit = self . pagi...
def _do_identity_role_list ( args ) : """Lists the current on - chain configuration values ."""
rest_client = RestClient ( args . url ) state = rest_client . list_state ( subtree = IDENTITY_NAMESPACE + _ROLE_PREFIX ) head = state [ 'head' ] state_values = state [ 'data' ] printable_roles = [ ] for state_value in state_values : role_list = RoleList ( ) decoded = b64decode ( state_value [ 'data' ] ) rol...
def _create_mel_filter_bank ( self ) : """Create the Mel filter bank , and store it in ` ` self . filters ` ` . Note that it is a function of the audio sample rate , so it cannot be created in the class initializer , but only later in : func : ` aeneas . mfcc . MFCC . compute _ from _ data ` ."""
self . filters = numpy . zeros ( ( 1 + ( self . fft_order // 2 ) , self . filter_bank_size ) , 'd' ) dfreq = float ( self . sample_rate ) / self . fft_order nyquist_frequency = self . sample_rate / 2 if self . upper_frequency > nyquist_frequency : self . log_exc ( u"Upper frequency %f exceeds Nyquist frequency %f" ...
def commits ( self , user , options ) : """List commits for given user ."""
# Prepare the command command = "git log --all --author={0}" . format ( user . login ) . split ( ) command . append ( "--format=format:%h - %s" ) command . append ( "--since='{0} 00:00:00'" . format ( options . since ) ) command . append ( "--until='{0} 00:00:00'" . format ( options . until ) ) if options . verbose : ...
def plan_first_phase ( N1 , N2 ) : """Create a plan for the first stage of the pruned FFT operation . ( Alex to provide a write up with more details . ) Parameters N1 : int Number of rows . N2 : int Number of columns . Returns plan : FFTWF plan The plan for performing the first phase FFT ."""
N = N1 * N2 vin = pycbc . types . zeros ( N , dtype = numpy . complex64 ) vout = pycbc . types . zeros ( N , dtype = numpy . complex64 ) f = float_lib . fftwf_plan_many_dft f . argtypes = [ ctypes . c_int , ctypes . c_void_p , ctypes . c_int , ctypes . c_void_p , ctypes . c_void_p , ctypes . c_int , ctypes . c_int , ct...
def _trim ( cls , s ) : """Remove trailing colons from the URI back to the first non - colon . : param string s : input URI string : returns : URI string with trailing colons removed : rtype : string TEST : trailing colons necessary > > > s = ' 1:2 : : : : ' > > > CPE . _ trim ( s ) '1:2' TEST : tra...
reverse = s [ : : - 1 ] idx = 0 for i in range ( 0 , len ( reverse ) ) : if reverse [ i ] == ":" : idx += 1 else : break # Return the substring after all trailing colons , # reversed back to its original character order . new_s = reverse [ idx : len ( reverse ) ] return new_s [ : : - 1 ]
async def async_get ( self , url ) : """Get an arbitrary page . This resets the iterator and then fully consumes it to return the specific page * * only * * . : param str url : URL to arbitrary page results ."""
self . reset ( ) self . next_link = url return await self . async_advance_page ( )
def WriteBlobs ( self , blob_id_data_map ) : """Creates or overwrites blobs ."""
urns = { self . _BlobUrn ( blob_id ) : blob_id for blob_id in blob_id_data_map } mutation_pool = data_store . DB . GetMutationPool ( ) existing = aff4 . FACTORY . MultiOpen ( urns , aff4_type = aff4 . AFF4MemoryStreamBase , mode = "r" ) for blob_urn , blob_id in iteritems ( urns ) : if blob_urn in existing : ...
def parse_date ( string_date ) : """Parse the given date as one of the following * Git internal format : timestamp offset * RFC 2822 : Thu , 07 Apr 2005 22:13:13 + 0200. * ISO 8601 2005-04-07T22:13:13 The T can be a space as well : return : Tuple ( int ( timestamp _ UTC ) , int ( offset ) ) , both in seco...
# git time try : if string_date . count ( ' ' ) == 1 and string_date . rfind ( ':' ) == - 1 : timestamp , offset = string_date . split ( ) timestamp = int ( timestamp ) return timestamp , utctz_to_altz ( verify_utctz ( offset ) ) else : offset = "+0000" # local time by de...
def print_help_page ( bot , file = sys . stdout ) : """print help page"""
def p ( text ) : print ( text , file = file ) plugin = bot . get_plugin ( Commands ) title = "Available Commands for {nick} at {host}" . format ( ** bot . config ) p ( "=" * len ( title ) ) p ( title ) p ( "=" * len ( title ) ) p ( '' ) p ( '.. contents::' ) p ( '' ) modules = { } for name , ( predicates , callback...
def pick ( self , req_authn_context = None ) : """Given the authentication context find zero or more places where the user could be sent next . Ordered according to security level . : param req _ authn _ context : The requested context as an RequestedAuthnContext instance : return : An URL"""
if req_authn_context is None : return self . _pick_by_class_ref ( UNSPECIFIED , "minimum" ) if req_authn_context . authn_context_class_ref : if req_authn_context . comparison : _cmp = req_authn_context . comparison else : _cmp = "exact" if _cmp == 'exact' : res = [ ] for ...
def _parse_queue_list ( list_output ) : '''Parse the queue to get a dict of name - > URL'''
queues = dict ( ( q . split ( '/' ) [ - 1 ] , q ) for q in list_output [ 'stdout' ] ) return queues
def extract_pdfminer ( self , filename , ** kwargs ) : """Extract text from pdfs using pdfminer ."""
stdout , _ = self . run ( [ 'pdf2txt.py' , filename ] ) return stdout
def as_dict ( self ) : """Returns : dict"""
dict_fw = { 'id' : self . id , 'name' : self . name , 'description' : self . description , 'rules_direction' : self . rules_direction , 'rules_ip_protocol' : self . rules_ip_protocol , 'rules_from_port' : self . rules_from_port , 'rules_to_port' : self . rules_to_port , 'rules_grants_group_id' : self . rules_grants_gro...
def GetResources ( filename , types = None , names = None , languages = None ) : """Get resources from dll / exe file . types = a list of resource types to search for ( None = all ) names = a list of resource names to search for ( None = all ) languages = a list of resource languages to search for ( None = al...
hsrc = win32api . LoadLibraryEx ( filename , 0 , LOAD_LIBRARY_AS_DATAFILE ) res = _GetResources ( hsrc , types , names , languages ) win32api . FreeLibrary ( hsrc ) return res
def OPTIONS_preflight ( self , path_info ) : """Give back CORS preflight check headers"""
self . send_response ( 200 ) self . send_header ( 'Access-Control-Allow-Origin' , '*' ) # CORS self . send_header ( 'Access-Control-Allow-Methods' , 'GET, PUT, POST, DELETE' ) self . send_header ( 'Access-Control-Allow-Headers' , 'content-type, authorization, range' ) self . send_header ( 'Access-Control-Expose-Headers...
def index_ontology ( self , ont ) : """Adds an ontology to the index This iterates through all labels and synonyms in the ontology , creating an index"""
self . merged_ontology . merge ( [ ont ] ) syns = ont . all_synonyms ( include_label = True ) include_id = self . _is_meaningful_ids ( ) logging . info ( "Include IDs as synonyms: {}" . format ( include_id ) ) if include_id : for n in ont . nodes ( ) : v = n # Get fragment if v . startswith ...
def _nix_env ( ) : '''nix - env with quiet option . By default , nix is extremely verbose and prints the build log of every package to stderr . This tells nix to only show changes .'''
nixhome = os . path . join ( os . path . expanduser ( '~{0}' . format ( __opts__ [ 'user' ] ) ) , '.nix-profile/bin/' ) return [ os . path . join ( nixhome , 'nix-env' ) ]
def from_moy ( cls , moy , leap_year = False ) : """Create Ladybug Datetime from a minute of the year . Args : moy : An integer value 0 < = and < 525600"""
if not leap_year : num_of_minutes_until_month = ( 0 , 44640 , 84960 , 129600 , 172800 , 217440 , 260640 , 305280 , 349920 , 393120 , 437760 , 480960 , 525600 ) else : num_of_minutes_until_month = ( 0 , 44640 , 84960 + 1440 , 129600 + 1440 , 172800 + 1440 , 217440 + 1440 , 260640 + 1440 , 305280 + 1440 , 349920 ...
def drawQuad ( self , img = None , quad = None , thickness = 30 ) : '''Draw the quad into given img'''
if img is None : img = self . img if quad is None : quad = self . quad q = np . int32 ( quad ) c = int ( img . max ( ) ) cv2 . line ( img , tuple ( q [ 0 ] ) , tuple ( q [ 1 ] ) , c , thickness ) cv2 . line ( img , tuple ( q [ 1 ] ) , tuple ( q [ 2 ] ) , c , thickness ) cv2 . line ( img , tuple ( q [ 2 ] ) , tu...
def parse_expression ( self ) : """Parse a template expression starting at ` ` pos ` ` . Resulting components ( Unicode strings , Symbols , and Calls ) are added to the ` ` parts ` ` field , a list . The ` ` pos ` ` field is updated to be the next character after the expression ."""
# Append comma ( ARG _ SEP ) to the list of special characters only when # parsing function arguments . extra_special_chars = ( ) special_char_re = self . special_char_re if self . in_argument : extra_special_chars = ( ARG_SEP , ) special_char_re = re . compile ( r'[%s]|\Z' % u'' . join ( re . escape ( c ) for ...
def norm2 ( self ) : """Squared norm of the vector"""
return self . x * self . x + self . y * self . y + self . z * self . z
def fast_sync_import ( working_dir , import_url , public_keys = config . FAST_SYNC_PUBLIC_KEYS , num_required = len ( config . FAST_SYNC_PUBLIC_KEYS ) , verbose = False ) : """Fast sync import . Verify the given fast - sync file from @ import _ path using @ public _ key , and then uncompress it into @ working _...
def logmsg ( s ) : if verbose : print s else : log . debug ( s ) def logerr ( s ) : if verbose : print >> sys . stderr , s else : log . error ( s ) if working_dir is None or not os . path . exists ( working_dir ) : logerr ( "No such directory {}" . format ( working_di...
def percentage_distance ( cls , highmark , current ) : """Percentage of distance the current offset is behind the highmark ."""
highmark = int ( highmark ) current = int ( current ) if highmark > 0 : return round ( ( highmark - current ) * 100.0 / highmark , 2 , ) else : return 0.0
def getWordAtOffset ( self , offset ) : """Returns a C { WORD } from a given offset . @ type offset : int @ param offset : The offset to get the C { WORD } from . @ rtype : L { WORD } @ return : The L { WORD } obtained at the given offset ."""
return datatypes . WORD . parse ( utils . ReadData ( self . getDataAtOffset ( offset , 2 ) ) )
def parse_author ( cls , marc ) : """Parse author from ` marc ` data . Args : marc ( obj ) : : class : ` . MARCXMLRecord ` instance . See module : mod : ` . marcxml _ parser ` for details . Returns : obj : : class : ` Author ` ."""
name = None code = None linked_forms = None is_corporation = None record = None # parse informations from the record if marc [ "100a" ] : # persons name = _first_or_none ( marc [ "100a" ] ) code = _first_or_none ( marc [ "1007" ] ) is_corporation = False record = marc . datafields [ "100" ] [ 0 ] # ...
def get_for_update ( self , key ) : """Locks the key and then gets and returns the value to which the specified key is mapped . Lock will be released at the end of the transaction ( either commit or rollback ) . : param key : ( object ) , the specified key . : return : ( object ) , the value for the specified...
check_not_none ( key , "key can't be none" ) return self . _encode_invoke ( transactional_map_get_for_update_codec , key = self . _to_data ( key ) )
def default_qai ( qareport ) : """QAI = 2 * ( TP * ( PT / PNC ) * COV ) / ( 1 + exp ( MSE / tau ) ) Where : TP : If all tests passes is 1 , 0 otherwise . PT : Processors and commands tested . PCN : The number number of processors ( Loader , Steps and Alerts ) and commands . COV : The code coverage ( bet...
TP = 1. if qareport . is_test_sucess else 0. PCN = qareport . processors_number + qareport . commands_number PT_div_PCN = float ( qareport . pc_tested_number ) / PCN COV = qareport . coverage_line_rate tau = get_tau ( ) total_tau = float ( tau ) * len ( qareport . project_modules ) style = 1 + math . exp ( qareport . s...
def get_books ( self ) : """Gets the book list resulting from a search . return : ( osid . commenting . BookList ) - the book list raise : IllegalState - list has already been retrieved * compliance : mandatory - - This method must be implemented . *"""
if self . retrieved : raise errors . IllegalState ( 'List has already been retrieved.' ) self . retrieved = True return objects . BookList ( self . _results , runtime = self . _runtime )
def select_molecules ( name ) : '''Select all the molecules corresponding to the formulas .'''
mol_formula = current_system ( ) . get_derived_molecule_array ( 'formula' ) mask = mol_formula == name ind = current_system ( ) . mol_to_atom_indices ( mask . nonzero ( ) [ 0 ] ) selection = { 'atoms' : Selection ( ind , current_system ( ) . n_atoms ) } # Need to find the bonds between the atoms b = current_system ( ) ...
def expected_duration ( self , expected_duration ) : """Sets the expected _ duration of this ModelBreak . Format : RFC - 3339 P [ n ] Y [ n ] M [ n ] DT [ n ] H [ n ] M [ n ] S . The expected length of the break . : param expected _ duration : The expected _ duration of this ModelBreak . : type : str"""
if expected_duration is None : raise ValueError ( "Invalid value for `expected_duration`, must not be `None`" ) if len ( expected_duration ) < 1 : raise ValueError ( "Invalid value for `expected_duration`, length must be greater than or equal to `1`" ) self . _expected_duration = expected_duration
def multiply ( self , a , b ) : """: type A : List [ List [ int ] ] : type B : List [ List [ int ] ] : rtype : List [ List [ int ] ]"""
if a is None or b is None : return None m , n , l = len ( a ) , len ( b [ 0 ] ) , len ( b [ 0 ] ) if len ( b ) != n : raise Exception ( "A's column number must be equal to B's row number." ) c = [ [ 0 for _ in range ( l ) ] for _ in range ( m ) ] for i , row in enumerate ( a ) : for k , eleA in enumerate ( ...
def make_required_folders ( self ) : """Makes all folders declared in the config if they do not exist ."""
for folder in [ self . pending_folder , self . usb_incoming_folder , self . outgoing_folder , self . incoming_folder , self . archive_folder , self . tmp_folder , self . log_folder , ] : if not os . path . exists ( folder ) : os . makedirs ( folder )
def read_creds ( profile_name , csv_file = None , mfa_serial_arg = None , mfa_code = None , force_init = False , role_session_name = 'opinel' ) : """Read credentials from anywhere ( CSV , Environment , Instance metadata , config / credentials ) : param profile _ name : : param csv _ file : : param mfa _ seria...
first_sts_session = False source_profile = None role_mfa_serial = None expiration = None credentials = init_creds ( ) role_arn , external_id = read_profile_from_environment_variables ( ) if csv_file : # Read credentials from a CSV file that was provided credentials [ 'AccessKeyId' ] , credentials [ 'SecretAccessKey...
def list_experiments ( project_path , sort , output , filter_op , columns ) : """Lists experiments in the directory subtree ."""
if columns : columns = columns . split ( "," ) commands . list_experiments ( project_path , sort , output , filter_op , columns )
def circle_fit ( edge , ret_dev = False ) : """Fit a circle to a boolean edge image Parameters edge : 2d boolean ndarray Edge image ret _ dev : bool Return the average deviation of the distance from contour to center of the fitted circle . Returns center : tuple of ( float , float ) Coordinates of...
sx , sy = edge . shape x = np . linspace ( 0 , sx , sx , endpoint = False ) . reshape ( - 1 , 1 ) y = np . linspace ( 0 , sy , sy , endpoint = False ) . reshape ( 1 , - 1 ) params = lmfit . Parameters ( ) # initial parameters sum_edge = np . sum ( edge ) params . add ( "cx" , np . sum ( x * edge ) / sum_edge ) params ....
def frames ( self , flush = True ) : """Returns the latest color image from the stream Raises : Exception if opencv sensor gives ret _ val of 0"""
self . flush ( ) ret_val , frame = self . _sensor . read ( ) if not ret_val : raise Exception ( "Unable to retrieve frame from OpenCVCameraSensor for id {0}" . format ( self . _device_id ) ) frame = cv2 . cvtColor ( frame , cv2 . COLOR_BGR2RGB ) if self . _upside_down : frame = np . flipud ( frame ) . astype ( ...
def readSheet ( self , sheet ) : """Reads a sheet in the sheet dictionary Stores each sheet as an array ( rows ) of arrays ( columns )"""
name = sheet . getAttribute ( "name" ) rows = sheet . getElementsByType ( TableRow ) arrRows = [ ] # for each row for row in rows : row_comment = "" arrCells = GrowingList ( ) cells = row . getElementsByType ( TableCell ) # for each cell count = 0 for cell in cells : # repeated value ? r...
def parse_angle ( input_dir ) : """Calculate the meteorological angle from directional text . Works for abbrieviations or whole words ( E - > 90 | South - > 180) and also is able to parse 22.5 degreee angles such as ESE / East South East Parameters input _ dir : string or array - like strings Directional ...
if isinstance ( input_dir , str ) : # abb _ dirs = abbrieviated directions abb_dirs = [ _abbrieviate_direction ( input_dir ) ] elif isinstance ( input_dir , list ) : input_dir_str = ',' . join ( input_dir ) abb_dir_str = _abbrieviate_direction ( input_dir_str ) abb_dirs = abb_dir_str . split ( ',' ) ret...
def compute_usage_requirements ( self , subvariant ) : """Given the set of generated targets , and refined build properties , determines and sets appripriate usage requirements on those targets ."""
assert isinstance ( subvariant , virtual_target . Subvariant ) rproperties = subvariant . build_properties ( ) xusage_requirements = self . evaluate_requirements ( self . usage_requirements_ , rproperties , "added" ) # We generate all dependency properties and add them , # as well as their usage requirements , to resul...
def check_api_response ( self , response ) : """Check API response and raise exceptions if needed . : param requests . models . Response response : request response to check"""
# check response if response . status_code == 200 : return True elif response . status_code >= 400 : logging . error ( "{}: {} - {} - URL: {}" . format ( response . status_code , response . reason , response . json ( ) . get ( "error" ) , response . request . url , ) ) return False , response . status_code
def _update_index ( self ) : """Update the reference to the index within the table"""
d = self . declaration self . index = self . view . model . index ( d . row , d . column ) if self . delegate : self . _refresh_count += 1 timed_call ( self . _loading_interval , self . _update_delegate )
def round_edge_screen ( alpha , Re , angle = 0 ) : r'''Returns the loss coefficient for a round edged wire screen or bar screen , as shown in [ 1 ] _ . Angle of inclination may be specified as well . Parameters alpha : float Fraction of screen open to flow [ - ] Re : float Reynolds number of flow throug...
beta = interp ( Re , round_Res , round_betas ) alpha2 = alpha * alpha K = beta * ( 1.0 - alpha2 ) / alpha2 if angle : if angle <= 45 : K *= cos ( radians ( angle ) ) ** 2 else : K *= interp ( angle , round_thetas , round_gammas ) return K
def prepare ( self ) : """Performs basic checks and then properly invokes - prepare _ inventory - prepare _ env - prepare _ command It ' s also responsible for wrapping the command with the proper ssh agent invocation and setting early ANSIBLE _ environment variables ."""
# ansible _ path = find _ executable ( ' ansible ' ) # if ansible _ path is None or not os . access ( ansible _ path , os . X _ OK ) : # raise ConfigurationError ( " Ansible not found . Make sure that it is installed . " ) if self . private_data_dir is None : raise ConfigurationError ( "Runner Base Directory is not...
def hash_dir ( path ) : """Write directory at path to Git index , return its SHA1 as a string ."""
dir_hash = { } for root , dirs , files in os . walk ( path , topdown = False ) : f_hash = ( ( f , hash_file ( join ( root , f ) ) ) for f in files ) d_hash = ( ( d , dir_hash [ join ( root , d ) ] ) for d in dirs ) # split + join normalizes paths on Windows ( note the imports ) dir_hash [ join ( * split...
def build_image_in_privileged_container ( build_image , source , image , parent_registry = None , target_registries = None , push_buildroot_to = None , parent_registry_insecure = False , target_registries_insecure = False , dont_pull_base_image = False , ** kwargs ) : """build image from provided dockerfile ( speci...
build_json = _prepare_build_json ( image , source , parent_registry , target_registries , parent_registry_insecure , target_registries_insecure , dont_pull_base_image , ** kwargs ) m = PrivilegedBuildManager ( build_image , build_json ) build_response = m . build ( ) if push_buildroot_to : m . commit_buildroot ( ) ...
def _registerExtension ( self , extension , rtiRegItem ) : """Links an file name extension to a repository tree item ."""
check_is_a_string ( extension ) check_class ( rtiRegItem , RtiRegItem ) logger . debug ( " Registering extension {!r} for {}" . format ( extension , rtiRegItem ) ) # TODO : type checking if extension in self . _extensionMap : logger . info ( "Overriding extension {!r}: old={}, new={}" . format ( extension , self ....
def init_from_database ( self , conn , database , table_name ) : """initialize heading from a database table . The table must exist already ."""
info = conn . query ( 'SHOW TABLE STATUS FROM `{database}` WHERE name="{table_name}"' . format ( table_name = table_name , database = database ) , as_dict = True ) . fetchone ( ) if info is None : if table_name == '~log' : logger . warning ( 'Could not create the ~log table' ) return else : ...
def run ( self ) : """Function to Run the server . Server runs on host : 127.0.0.1 and port : 2000 by default . Debug is also set to false by default Can be overriden by using the config . ini file"""
define ( "port" , default = self . port , help = "Run on given port" , type = int ) define ( "host" , default = self . host , help = "Run on given host" , type = str ) define ( "debug" , default = self . debug , help = "True for development" , type = bool ) parse_command_line ( ) print ( Fore . GREEN + "Starting Bast S...
def discussion_is_still_open ( self , discussion_type , auto_close_after ) : """Checks if a type of discussion is still open are a certain number of days ."""
discussion_enabled = getattr ( self , discussion_type ) if ( discussion_enabled and isinstance ( auto_close_after , int ) and auto_close_after >= 0 ) : return ( timezone . now ( ) - ( self . start_publication or self . publication_date ) ) . days < auto_close_after return discussion_enabled
def move_id_ahead ( element_id , reference_id , idstr_list ) : """Moves element _ id ahead of reference _ id in the list"""
if element_id == reference_id : return idstr_list idstr_list . remove ( str ( element_id ) ) reference_index = idstr_list . index ( str ( reference_id ) ) idstr_list . insert ( reference_index , str ( element_id ) ) return idstr_list
def login ( request , user ) : """Persist a user id and a backend in the request . This way a user doesn ' t have to reauthenticate on every request . Note that data set during the anonymous session is retained when the user logs in ."""
session_auth_hash = '' if user is None : user = request . user if hasattr ( user , 'get_session_auth_hash' ) : session_auth_hash = user . get_session_auth_hash ( ) if SESSION_KEY in request . session : session_key = request . session [ SESSION_KEY ] if session_key != user . pk or ( session_auth_hash and...
def build_values ( name , values_mods ) : """Update name / values . yaml with modifications"""
values_file = os . path . join ( name , 'values.yaml' ) with open ( values_file ) as f : values = yaml . load ( f ) for key , value in values_mods . items ( ) : parts = key . split ( '.' ) mod_obj = values for p in parts : mod_obj = mod_obj [ p ] print ( f"Updating {values_file}: {key}: {val...
def MarkForTermination ( cls , flow_urn , reason = None , mutation_pool = None ) : """Mark the flow for termination as soon as any of its states are called ."""
# Doing a blind write here using low - level data store API . Accessing # the flow via AFF4 is not really possible here , because it forces a state # to be written in Close ( ) method . if mutation_pool is None : raise ValueError ( "Mutation pool can't be none." ) mutation_pool . Set ( flow_urn , cls . SchemaCls . ...
def kippenhahn_CO ( self , num_frame , xax , t0_model = 0 , title = 'Kippenhahn diagram' , tp_agb = 0. , ylim_CO = [ 0 , 0 ] ) : """Kippenhahn plot as a function of time or model with CO ratio Parameters num _ frame : integer Number of frame to plot this plot into . xax : string Either model or time to in...
pyl . figure ( num_frame ) if xax == 'time' : xaxisarray = self . get ( 'star_age' ) elif xax == 'model' : xaxisarray = self . get ( 'model_number' ) else : print ( 'kippenhahn_error: invalid string for x-axis selction.' + ' needs to be "time" or "model"' ) t0_mod = xaxisarray [ t0_model ] plot_bounds = Tru...
def getSearch ( self ) : """Returns the search capability ."""
return Search ( self . getColumns ( ) , Sitools2Abstract . getBaseUrl ( self ) + self . getUri ( ) )
def update_frame ( self , key , ranges = None , plot = None ) : """Updates an existing plot with data corresponding to the key ."""
element = self . _get_frame ( key ) text , _ , _ = self . get_data ( element , ranges , { } ) self . handles [ 'plot' ] . text = text
def postprocess ( self , content ) : """Perform final processing of the resulting data structure as follows : - Mixed values ( children and text ) will have a result of the I { content . node } . - Simi - simple values ( attributes , no - children and text ) will have a result of a property object . - Simpl...
node = content . node if len ( node . children ) and node . hasText ( ) : return node attributes = AttrList ( node . attributes ) if attributes . rlen ( ) and not len ( node . children ) and node . hasText ( ) : p = Factory . property ( node . name , node . getText ( ) ) return merge ( content . data , p ) ...
def load_config ( configfile ) : """Return a dict with configuration from the supplied yaml file"""
try : with open ( configfile , 'r' ) as ymlfile : try : config = yaml . load ( ymlfile ) return config except yaml . parser . ParserError : raise PyYAMLConfigError ( 'Could not parse config file: {}' . format ( configfile ) , ) except IOError : raise PyYAMLCon...
def add_locals ( self , locals ) : '''If locals are provided , create a copy of self containing those locals in addition to what is already in this variable proxy .'''
if locals is None : return self return _jinja2_vars ( self . basedir , self . vars , self . globals , locals , * self . extras )
def get_public_key ( key_info , ctx ) : """Get the public key if its defined in X509Certificate node . Otherwise , take self . public _ key element : param sign : Signature node : type sign : lxml . etree . Element : return : Public key to use"""
key = key_info . find ( 'ds:KeyInfo/ds:KeyValue/ds:RSAKeyValue' , namespaces = NS_MAP ) if key is not None : n = os2ip ( b64decode ( key . find ( 'ds:Modulus' , namespaces = NS_MAP ) . text ) ) e = os2ip ( b64decode ( key . find ( 'ds:Exponent' , namespaces = NS_MAP ) . text ) ) return rsa . RSAPublicNumber...
def html_report ( self , file_path ) : """Generate and save HTML report ."""
self . logger . debug ( 'Generating HTML report' ) report = self . zap . core . htmlreport ( ) self . _write_report ( report , file_path )
def _handle_tag_definesprite ( self ) : """Handle the DefineSprite tag ."""
obj = _make_object ( "DefineSprite" ) obj . CharacterID = unpack_ui16 ( self . _src ) obj . FrameCount = unpack_ui16 ( self . _src ) tags = self . _process_tags ( ) obj . ControlTags = tags return obj
def hash_coloured_escapes ( text ) : """Return the ANSI hash colour prefix and suffix for a given text"""
ansi_code = int ( sha256 ( text . encode ( 'utf-8' ) ) . hexdigest ( ) , 16 ) % 230 prefix , suffix = colored ( 'SPLIT' , ansi_code = ansi_code ) . split ( 'SPLIT' ) return prefix , suffix
def run ( self , call , num_alts ) : """Check ` ` FORMAT ` ` of a record . Call Currently , only checks for consistent counts are implemented"""
for key , value in call . data . items ( ) : self . _check_count ( call , key , value , num_alts )
def enrich ( self , column ) : """This method helps to identify flags in the message log . As some communities may use the log message for the code authorship , specifig flags / tags are used to determine some actions by the authors or reviewers such who is the author or the reviewer is . The list of supp...
if column not in self . data . columns : return self . data flags_list = [ ] values_list = [ ] # Assuming the index of the dataframe is an integer for i in list ( range ( len ( self . data ) ) ) : flags , values = self . __parse_flags ( self . data [ column ] [ i ] ) flags_list . append ( flags ) values...
def _handle_login ( opt , action , bz ) : """Handle all login related bits"""
is_login_command = ( action == 'login' ) do_interactive_login = ( is_login_command or opt . login or opt . username or opt . password ) username = getattr ( opt , "pos_username" , None ) or opt . username password = getattr ( opt , "pos_password" , None ) or opt . password try : if do_interactive_login : if...
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'intent' ) and self . intent is not None : _dict [ 'intent' ] = self . intent if hasattr ( self , 'confidence' ) and self . confidence is not None : _dict [ 'confidence' ] = self . confidence if hasattr ( self , '_additionalProperties' ) : for _key in self . _additionalProper...
def position ( self , pos = None ) : """Get current and / or set history cursor position : param pos : if value is not None , then current position is set to pos and new value is returned : return : int or None ( if position have never been changed )"""
if pos is not None : if pos >= len ( self . __history ) : raise IndexError ( 'History position is out of bound' ) self . __history_position = pos return self . __history_position
def runner ( coro ) : """Function execution decorator ."""
@ wraps ( coro ) def inner ( self , * args , ** kwargs ) : if self . mode == 'async' : return coro ( self , * args , ** kwargs ) return self . _loop . run_until_complete ( coro ( self , * args , ** kwargs ) ) return inner
def sync_modules ( saltenv = None , refresh = True , extmod_whitelist = None , extmod_blacklist = None ) : '''. . versionadded : : 0.10.0 Sync execution modules from ` ` salt : / / _ modules ` ` to the minion saltenv The fileserver environment from which to sync . To sync from more than one environment , pa...
ret = _sync ( 'modules' , saltenv , extmod_whitelist , extmod_blacklist ) if refresh : refresh_modules ( ) return ret
def add_decorate ( orig , fill_value = None , ** decorate ) : """Decorate an image with text and / or logos / images . This call adds text / logos in order as given in the input to keep the alignment features available in pydecorate . An example of the decorate config : : decorate = { ' decorate ' : [ {...
LOG . info ( "Decorate image." ) # Need to create this here to possible keep the alignment # when adding text and / or logo with pydecorate if hasattr ( orig , 'convert' ) : # image must be in RGB space to work with pycoast / pydecorate orig = orig . convert ( 'RGBA' if orig . mode . endswith ( 'A' ) else 'RGB' ) e...
def score_n3 ( matrix , matrix_size ) : """Implements the penalty score feature 3. ISO / IEC 18004:2015 ( E ) - - 7.8.3 Evaluation of data masking results - Table 11 ( page 54) Feature Evaluation condition Points 1 : 1 : 3 : 1 : 1 ratio Existence of the pattern N3 ( dark : light : dark : light : dark ) patt...
def is_match ( seq , start , end ) : start = max ( start , 0 ) end = min ( end , matrix_size ) for i in range ( start , end ) : if seq [ i ] == 0x1 : return False return True def find_occurrences ( seq ) : count = 0 idx = seq . find ( _N3_PATTERN ) while idx != - 1 : ...
def correctwords ( self , originalwords , newwords , ** kwargs ) : """Generic correction method for words . You most likely want to use the helper functions : meth : ` Sentence . splitword ` , : meth : ` Sentence . mergewords ` , : meth : ` deleteword ` , : meth : ` insertword ` instead"""
for w in originalwords : if not isinstance ( w , Word ) : raise Exception ( "Original word is not a Word instance: " + str ( type ( w ) ) ) elif w . sentence ( ) != self : raise Exception ( "Original not found as member of sentence!" ) for w in newwords : if not isinstance ( w , Word ) : ...
def set_is_playable ( self , is_playable ) : '''Sets the listitem ' s playable flag'''
value = 'false' if is_playable : value = 'true' self . set_property ( 'isPlayable' , value ) self . is_folder = not is_playable
def restore ( cls , metadata_checkpoint_dir , search_alg = None , scheduler = None , trial_executor = None ) : """Restores all checkpointed trials from previous run . Requires user to manually re - register their objects . Also stops all ongoing trials . Args : metadata _ checkpoint _ dir ( str ) : Path to ...
newest_ckpt_path = _find_newest_ckpt ( metadata_checkpoint_dir ) with open ( newest_ckpt_path , "r" ) as f : runner_state = json . load ( f , cls = _TuneFunctionDecoder ) logger . warning ( "" . join ( [ "Attempting to resume experiment from {}. " . format ( metadata_checkpoint_dir ) , "This feature is experimental...
def setup_data ( ) : """Import sample data ( from gisdata package ) into GeoNode"""
import gisdata ctype = options . get ( 'type' , None ) data_dir = gisdata . GOOD_DATA if ctype in [ 'vector' , 'raster' , 'time' ] : data_dir = os . path . join ( gisdata . GOOD_DATA , ctype ) sh ( "python manage.py importlayers %s -v2" % data_dir )
async def serialize_properties ( inputs : 'Inputs' , property_deps : Dict [ str , List [ 'Resource' ] ] , input_transformer : Optional [ Callable [ [ str ] , str ] ] = None ) -> struct_pb2 . Struct : """Serializes an arbitrary Input bag into a Protobuf structure , keeping track of the list of dependent resources ...
struct = struct_pb2 . Struct ( ) for k , v in inputs . items ( ) : deps = [ ] result = await serialize_property ( v , deps , input_transformer ) # We treat properties that serialize to None as if they don ' t exist . if result is not None : # While serializing to a pb struct , we must " translate " all ...
def is_fundamental ( type_ ) : """returns True , if type represents C + + fundamental type"""
return does_match_definition ( type_ , cpptypes . fundamental_t , ( cpptypes . const_t , cpptypes . volatile_t ) ) or does_match_definition ( type_ , cpptypes . fundamental_t , ( cpptypes . volatile_t , cpptypes . const_t ) )
def get_sos_step_steps ( stmt ) : '''Extract sos _ step ( x ) from statement'''
opt_values = get_param_of_function ( 'sos_step' , stmt , extra_dict = env . sos_dict . dict ( ) ) for value in opt_values : if len ( value ) != 1 : raise ValueError ( 'sos_step only accept one and only one parameter' ) return [ x [ 0 ] for x in opt_values ]
def read_tred_tsv ( tsvfile ) : """Read the TRED table into a dataframe ."""
df = pd . read_csv ( tsvfile , sep = "\t" , index_col = 0 , dtype = { "SampleKey" : str } ) return df
def dt_to_int ( value , time_unit = 'us' ) : """Converts a datetime type to an integer with the supplied time unit ."""
if pd : if isinstance ( value , pd . Period ) : value = value . to_timestamp ( ) if isinstance ( value , pd . Timestamp ) : try : value = value . to_datetime64 ( ) except : value = np . datetime64 ( value . to_pydatetime ( ) ) elif isinstance ( value , cftime_type...
def timeslot_options ( interval = swingtime_settings . TIMESLOT_INTERVAL , start_time = swingtime_settings . TIMESLOT_START_TIME , end_delta = swingtime_settings . TIMESLOT_END_TIME_DURATION , fmt = swingtime_settings . TIMESLOT_TIME_FORMAT ) : '''Create a list of time slot options for use in swingtime forms . Th...
dt = datetime . combine ( date . today ( ) , time ( 0 ) ) dtstart = datetime . combine ( dt . date ( ) , start_time ) dtend = dtstart + end_delta options = [ ] while dtstart <= dtend : options . append ( ( str ( dtstart . time ( ) ) , dtstart . strftime ( fmt ) ) ) dtstart += interval return options
def do_use ( self , args ) : """Use another instance , provided as argument ."""
self . instance = args self . prompt = self . instance + '> ' archive = self . _client . get_archive ( self . instance ) self . streams = [ s . name for s in archive . list_streams ( ) ] self . tables = [ t . name for t in archive . list_tables ( ) ]
def cooccurrence ( quantized_image , labels , scale_i = 3 , scale_j = 0 ) : """Calculates co - occurrence matrices for all the objects in the image . Return an array P of shape ( nobjects , nlevels , nlevels ) such that P [ o , : , : ] is the cooccurence matrix for object o . quantized _ image - - a numpy arr...
labels = labels . astype ( int ) nlevels = quantized_image . max ( ) + 1 nobjects = labels . max ( ) if scale_i < 0 : scale_i = - scale_i scale_j = - scale_j if scale_i == 0 and scale_j > 0 : image_a = quantized_image [ : , : - scale_j ] image_b = quantized_image [ : , scale_j : ] labels_ab = labels...
def run_azure ( target , jobs , n = 1 , nproc = None , path = '.' , delete = True , config = None , ** kwargs ) : """Evaluate the given function with each set of arguments , and return a list of results . This function does in parallel with Microsoft Azure Batch . This function is the work in progress . The a...
import ecell4 . extra . azure_batch as azure_batch return azure_batch . run_azure ( target , jobs , n , path , delete , config )
def _reindex_axes ( self , axes , level , limit , tolerance , method , fill_value , copy ) : """Perform the reindex for all the axes ."""
obj = self for a in self . _AXIS_ORDERS : labels = axes [ a ] if labels is None : continue ax = self . _get_axis ( a ) new_index , indexer = ax . reindex ( labels , level = level , limit = limit , tolerance = tolerance , method = method ) axis = self . _get_axis_number ( a ) obj = obj . ...
def spread ( ctx , market , side , min , max , num , total , order_expiration , account ) : """Place multiple orders : param str market : Market pair quote : base ( e . g . USD : BTS ) : param str side : ` ` buy ` ` or ` ` sell ` ` quote : param float min : minimum price to place order at : param float max ...
from tqdm import tqdm from numpy import linspace market = Market ( market ) ctx . bitshares . bundle = True if min < max : space = linspace ( min , max , num ) else : space = linspace ( max , min , num ) func = getattr ( market , side ) for p in tqdm ( space ) : func ( p , total / float ( num ) , account = ...
def issubset ( self , other ) : """Report whether another set contains this RangeSet ."""
self . _binary_sanity_check ( other ) return set . issubset ( self , other )
def add ( entry_point , all_entry_points , auto_write , scripts_path ) : '''Add Scrim scripts for a python project'''
click . echo ( ) if not entry_point and not all_entry_points : raise click . UsageError ( 'Missing required option: --entry_point or --all_entry_points' ) if not os . path . exists ( 'setup.py' ) : raise click . UsageError ( 'No setup.py found.' ) setup_data = parse_setup ( 'setup.py' ) console_scripts = get_co...
def create_device_from_category ( self , plm , addr , cat , subcat , product_key = 0x00 ) : """Create a new device from the cat , subcat and product _ key data ."""
saved_device = self . _saved_devices . get ( Address ( addr ) . id , { } ) cat = saved_device . get ( 'cat' , cat ) subcat = saved_device . get ( 'subcat' , subcat ) product_key = saved_device . get ( 'product_key' , product_key ) device_override = self . _overrides . get ( Address ( addr ) . id , { } ) cat = device_ov...
def dump_header ( iterable , allow_token = True ) : """Dump an HTTP header again . This is the reversal of : func : ` parse _ list _ header ` , : func : ` parse _ set _ header ` and : func : ` parse _ dict _ header ` . This also quotes strings that include an equals sign unless you pass it as dict of key , va...
if isinstance ( iterable , dict ) : items = [ ] for key , value in iteritems ( iterable ) : if value is None : items . append ( key ) else : items . append ( "%s=%s" % ( key , quote_header_value ( value , allow_token = allow_token ) ) ) else : items = [ quote_header_v...
def get_select_options ( self ) : """Provide the value , string , and help _ text for the template to render . help _ text is returned if applicable ."""
if self . filter_choices : return [ choice [ : 4 ] for choice in self . filter_choices # Display it If the fifth element is True or does not exist if len ( choice ) < 5 or choice [ 4 ] ]
def execute ( self , conn , daoinput , transaction = False ) : """daoinput keys : migration _ status , migration _ block _ id , migration _ request _ id"""
# print daoinput [ ' migration _ block _ id ' ] if not conn : dbsExceptionHandler ( "dbsException-failed-connect2host" , "Oracle/MigrationBlock/Update. Expects db connection from upper layer." , self . logger . exception ) if daoinput [ 'migration_status' ] == 1 : sql = self . sql + " (MIGRATION_STATUS = 0 or...
def _deserialize_list ( cls , type_item , list_ ) : """: type type _ item : T | type : type list _ : list : rtype : list [ T ]"""
list_deserialized = [ ] for item in list_ : item_deserialized = cls . deserialize ( type_item , item ) list_deserialized . append ( item_deserialized ) return list_deserialized