signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def convex_comb_dis_log ( model , a , b ) : """convex _ comb _ dis _ log - - add piecewise relation with a logarithmic number of binary variables using the convex combination formulation . Parameters : - model : a model where to include the piecewise linear relation - a [ k ] : x - coordinate of the k - th ...
K = len ( a ) - 1 G = int ( math . ceil ( ( math . log ( K ) / math . log ( 2 ) ) ) ) # number of required bits N = 1 << G # number of required variables # print ( " K , G , N : " , K , G , N wL , wR , z = { } , { } , { } for k in range ( N ) : wL [ k ] = model . addVar ( lb = 0 , ub = 1 , vtype = "C" ) wR [ k ...
def summarise ( self ) : """extrapolate a human readable summary of the contexts"""
res = '' if self . user == 'Developer' : if self . host == 'Home PC' : res += 'At Home' else : res += 'Away from PC' elif self . user == 'User' and self . host == 'Home PC' : res += 'Remote desktop into home PC' res += '\n' res += self . transport return res
def write ( self , ontol , ** args ) : """Write a ` ontology ` object"""
s = self . render ( ontol , ** args ) if self . outfile is None : print ( s ) else : f = open ( self . outfile , 'w' ) f . write ( s ) f . close ( )
def to_jd2 ( year , month , day ) : '''Gregorian to Julian Day Count for years between 1801-2099'''
# http : / / quasar . as . utexas . edu / BillInfo / JulianDatesG . html legal_date ( year , month , day ) if month <= 2 : year = year - 1 month = month + 12 a = floor ( year / 100 ) b = floor ( a / 4 ) c = 2 - a + b e = floor ( 365.25 * ( year + 4716 ) ) f = floor ( 30.6001 * ( month + 1 ) ) return c + day + e...
def fit_interval_censoring ( self , lower_bound , upper_bound , event_observed = None , timeline = None , label = None , alpha = None , ci_labels = None , show_progress = False , entry = None , weights = None , ) : # pylint : disable = too - many - arguments """Fit the model to an interval censored dataset . Para...
check_nans_or_infs ( lower_bound ) check_positivity ( upper_bound ) self . upper_bound = np . asarray ( pass_for_numeric_dtypes_or_raise_array ( upper_bound ) ) self . lower_bound = np . asarray ( pass_for_numeric_dtypes_or_raise_array ( lower_bound ) ) if ( self . upper_bound < self . lower_bound ) . any ( ) : rai...
def diff_to_new_interesting_lines ( unified_diff_lines : List [ str ] ) -> Dict [ int , str ] : """Extracts a set of ' interesting ' lines out of a GNU unified diff format . Format : gnu . org / software / diffutils / manual / html _ node / Detailed - Unified . html @ @ from - line - numbers to - line - numbe...
interesting_lines = dict ( ) for diff_line in unified_diff_lines : # Parse the ' new file ' range parts of the unified diff . if not diff_line . startswith ( '@@ ' ) : continue change = diff_line [ 3 : diff_line . index ( ' @@' , 3 ) ] new = change . split ( ' ' ) [ 1 ] start = int ( new . split...
def after_batch ( self , stream_name : str , batch_data : Batch ) -> None : """Display the progress and ETA for the current stream in the epoch . If the stream size ( total batch count ) is unknown ( 1st epoch ) , print only the number of processed batches ."""
if self . _current_stream_name is None or self . _current_stream_name != stream_name : self . _current_stream_name = stream_name self . _current_stream_start = None erase_line ( ) self . _current_batch_count [ stream_name ] += 1 current_batch = self . _current_batch_count [ stream_name ] # total batch count is ...
def _names_mce ( method , wrap_number = None ) : """Returns triplet of names : Method , it ' s Class and wrap ' s Enabled attr name . If enabled attr name does not exist ( that is , there is no wrap wrap _ number on the method ) , AspectsException is raised ."""
methods_name = method . __name__ methods_class = method . im_class if wrap_number != None : enabled_attr_name = "__wrap_enabled" + str ( wrap_number ) + methods_name if not hasattr ( methods_class , enabled_attr_name ) : raise AspectsException ( "Method %s does not have wrap with number %s" % ( methods_...
def write_tables_to_fits ( filepath , tablelist , clobber = False , namelist = None , cardslist = None , hdu_list = None ) : """Write some astropy . table . Table objects to a single fits file"""
outhdulist = [ fits . PrimaryHDU ( ) ] rmlist = [ ] for i , table in enumerate ( tablelist ) : ft_name = "%s._%i" % ( filepath , i ) rmlist . append ( ft_name ) try : os . unlink ( ft_name ) except : pass table . write ( ft_name , format = "fits" ) ft_in = fits . open ( ft_name )...
def get_qpimage ( self , idx ) : """Return background - corrected QPImage of data at index ` idx `"""
# raw data qpi = self . get_qpimage_raw ( idx ) if "identifier" not in qpi : msg = "`get_qpimage_raw` does not set 'identifier' " + "in class '{}'!" . format ( self . __class__ ) raise KeyError ( msg ) # bg data if self . _bgdata : if len ( self . _bgdata ) == 1 : # One background for all bgidx = 0 ...
def calcsize ( values , sizerange = ( 2 , 70 ) , inds = None , plaw = 3 ) : """Use set of values to calculate symbol size . values is a list of floats for candidate significance . inds is an optional list of indexes to use to calculate symbol size . Scaling of symbol size min max set by sizerange tuple ( min ...
if inds : smax = max ( [ abs ( values [ i ] ) for i in inds ] ) smin = min ( [ abs ( values [ i ] ) for i in inds ] ) else : smax = max ( [ abs ( val ) for val in values ] ) smin = min ( [ abs ( val ) for val in values ] ) return [ sizerange [ 0 ] + sizerange [ 1 ] * ( ( abs ( val ) - smin ) / ( smax - ...
def module_to_package_data ( name : str , entry , path_prefixes : list = None ) -> typing . Union [ dict , None ] : """Converts a module entry into a package data dictionary with information about the module . including version and location on disk : param name : : param entry : : param path _ prefixes : ...
if name . find ( '.' ) > - 1 : # Not interested in sub - packages , only root ones return None version = getattr ( entry , '__version__' , None ) version = version if not hasattr ( version , 'version' ) else version . version location = getattr ( entry , '__file__' , sys . exec_prefix ) if version is None or locati...
def send_file ( self , key , fp , headers , cb = None , num_cb = 10 ) : """Upload a file to a key into a bucket on GS , using GS resumable upload protocol . : type key : : class : ` boto . s3 . key . Key ` or subclass : param key : The Key object to which data is to be uploaded : type fp : file - like objec...
if not headers : headers = { } fp . seek ( 0 , os . SEEK_END ) file_length = fp . tell ( ) fp . seek ( 0 ) debug = key . bucket . connection . debug # Use num - retries from constructor if one was provided ; else check # for a value specified in the boto config file ; else default to 5. if self . num_retries is Non...
def media_artist ( self ) : """Artist of current playing media ( Music track only ) ."""
try : artists = self . session [ 'NowPlayingItem' ] [ 'Artists' ] if len ( artists ) > 1 : return artists [ 0 ] else : return artists except KeyError : return None
def err_exit ( message = '' , code = None , expected_exceptions = default_expected_exceptions , arg_parser = None , ignore_sigpipe = True , exception = None ) : '''Exits the program , printing information about the last exception ( if any ) and an optional error message . Uses * exception * instead if provided . ...
if arg_parser is not None : message = arg_parser . prog + ": " + message exc = exception if exception is not None else sys . exc_info ( ) [ 1 ] if isinstance ( exc , SystemExit ) : raise exc elif isinstance ( exc , expected_exceptions ) : exit_with_exc_info ( EXPECTED_ERR_EXIT_STATUS , message , print_tb = ...
def define_density_matrix ( Ne , explicitly_hermitian = False , normalized = False , variables = None ) : r"""Return a symbolic density matrix . The arguments are Ne ( integer ) : The number of atomic states . explicitly _ hermitian ( boolean ) : Whether to make $ \ rho _ { ij } = \ bar { \ rho } _ { ij }...
if Ne > 9 : comma = "," name = r"\rho" open_brace = "_{" close_brace = "}" else : comma = "" name = "rho" open_brace = "" close_brace = "" rho = [ ] for i in range ( Ne ) : row_rho = [ ] for j in range ( Ne ) : if i == j : row_rho += [ define_symbol ( name , o...
def start_time ( self ) : """getter and setter the measurement start timestamp Returns timestamp : datetime . datetime start timestamp"""
timestamp = self . abs_time / 10 ** 9 if self . time_flags & v4c . FLAG_HD_LOCAL_TIME : timestamp = datetime . fromtimestamp ( timestamp ) else : timestamp = datetime . fromtimestamp ( timestamp , timezone . utc ) return timestamp
def validateTagAttributes ( self , attribs , element ) : """docstring for validateTagAttributes"""
out = { } if element not in _whitelist : return out whitelist = _whitelist [ element ] for attribute in attribs : value = attribs [ attribute ] if attribute not in whitelist : continue # Strip javascript " expression " from stylesheets . # http : / / msdn . microsoft . com / workshop / autho...
def _encode ( cls , value ) : """Encode the given value , taking care of ' % ' and ' / ' ."""
value = json . dumps ( value ) return cls . _ENC_RE . sub ( lambda x : '%%%2x' % ord ( x . group ( 0 ) ) , value )
def rational_limit ( f , g , t0 ) : """Computes the limit of the rational function ( f / g ) ( t ) as t approaches t0."""
assert isinstance ( f , np . poly1d ) and isinstance ( g , np . poly1d ) assert g != np . poly1d ( [ 0 ] ) if g ( t0 ) != 0 : return f ( t0 ) / g ( t0 ) elif f ( t0 ) == 0 : return rational_limit ( f . deriv ( ) , g . deriv ( ) , t0 ) else : raise ValueError ( "Limit does not exist." )
def __components_instantiation_callback ( self , profile ) : """Defines a callback for Components instantiation . : param profile : Component Profile . : type profile : Profile"""
self . __splashscreen and self . __splashscreen . show_message ( "{0} - {1} | Instantiating {2} Component." . format ( self . __class__ . __name__ , Constants . version , profile . name ) )
def transform ( self , numerical_feature_list , categorical_feature_list ) : """Args : numerical _ feature _ list : list of numerical features categorical _ feature _ list : list of categorical features Returns : Dictionary with following keys : features : DataFrame with concatenated features feature _ ...
features = numerical_feature_list + categorical_feature_list for feature in features : feature = self . _format_target ( feature ) feature . set_index ( self . id_column , drop = True , inplace = True ) features = pd . concat ( features , axis = 1 ) . astype ( np . float32 ) . reset_index ( ) outputs = dict ( )...
def _validate_other_mul_div ( other ) : """Conditions for other to satisfy before mul / div ."""
if not isinstance ( other , ( u . Quantity , numbers . Number , BaseUnitlessSpectrum , SourceSpectrum ) ) : raise exceptions . IncompatibleSources ( 'Can only operate on scalar number/Quantity or spectrum' ) elif ( isinstance ( other , u . Quantity ) and ( other . unit . decompose ( ) != u . dimensionless_unscaled ...
def conv ( arg , default = None , func = None ) : '''essentially , the generalization of arg if arg else default or func ( arg ) if arg else default'''
if func : return func ( arg ) if arg else default ; else : return arg if arg else default ;
def _set_dst_port ( self , v , load = False ) : """Setter method for dst _ port , mapped from YANG variable / overlay / access _ list / type / vxlan / extended / ext _ seq / dst _ port ( uint32) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ dst _ port is considered as...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = RestrictedClassType ( base_type = long , restriction_dict = { 'range' : [ '0..4294967295' ] } , int_size = 32 ) , is_leaf = True , yang_name = "dst-port" , rest_name = "dst-port" , parent = self , choice = ( u'choice-dst-port...
def create_backends_from_settings ( self ) : """Expects the Django setting " EVENT _ TRACKING _ BACKENDS " to be defined and point to a dictionary of backend engine configurations . Example : : EVENT _ TRACKING _ BACKENDS = { ' default ' : { ' ENGINE ' : ' some . arbitrary . Backend ' , ' OPTIONS ' : { ...
config = getattr ( settings , DJANGO_BACKEND_SETTING_NAME , { } ) backends = self . instantiate_objects ( config ) return backends
def constraint_matches ( self , c , m ) : """Return dict noting the substitution values ( or False for no match )"""
if isinstance ( m , tuple ) : d = { } if isinstance ( c , Operator ) and c . _op_name == m [ 0 ] : for c1 , m1 in zip ( c . _args , m [ 1 : ] ) : r = self . constraint_matches ( c1 , m1 ) if r is False : return r d . update ( r ) return d r...
def get_version ( brain_or_object ) : """Get the version of the current object : param brain _ or _ object : A single catalog brain or content object : type brain _ or _ object : ATContentType / DexterityContentType / CatalogBrain : returns : The current version of the object , or None if not available : rt...
obj = get_object ( brain_or_object ) if not is_versionable ( obj ) : return None return getattr ( aq_base ( obj ) , "version_id" , 0 )
def set_scaled_font ( self , scaled_font ) : """Replaces the current font face , font matrix , and font options with those of : obj : ` scaled _ font ` . Except for some translation , the current CTM of the context should be the same as that of the : obj : ` scaled _ font ` , which can be accessed using : m...
cairo . cairo_set_scaled_font ( self . _pointer , scaled_font . _pointer ) self . _check_status ( )
def play_Bar ( self , bar , channel = 1 , bpm = 120 ) : """Play a Bar object . Return a dictionary with the bpm lemma set on success , an empty dict on some kind of failure . The tempo can be changed by setting the bpm attribute on a NoteContainer ."""
self . notify_listeners ( self . MSG_PLAY_BAR , { 'bar' : bar , 'channel' : channel , 'bpm' : bpm } ) # length of a quarter note qn_length = 60.0 / bpm for nc in bar : if not self . play_NoteContainer ( nc [ 2 ] , channel , 100 ) : return { } # Change the quarter note length if the NoteContainer has a b...
def parse_source_file ( file_name ) : """Parses the AST of Python file for lines containing references to the argparse module . returns the collection of ast objects found . Example client code : 1 . parser = ArgumentParser ( desc = " My help Message " ) 2 . parser . add _ argument ( ' filename ' , help =...
with open ( file_name , 'r' ) as f : s = f . read ( ) nodes = ast . parse ( s ) module_imports = get_nodes_by_instance_type ( nodes , _ast . Import ) specific_imports = get_nodes_by_instance_type ( nodes , _ast . ImportFrom ) assignment_objs = get_nodes_by_instance_type ( nodes , _ast . Assign ) call_objects = get_...
def special_typechecking ( value , msg ) : """Special Typechecking not available via protocol itself : param value : < dict > : param msg : < proto object > : return : < bool >"""
result = True if msg . DESCRIPTOR . name == TARGET : result &= special_target_typecheck ( value ) elif msg . DESCRIPTOR . name == PLUGIN : result &= special_plugin_checking ( value ) return result
def fcoe_fcoe_fabric_map_fcoe_fcf_map_fcf_map_fif_rbid_fcf_map_fif_rbid_add ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) fcoe = ET . SubElement ( config , "fcoe" , xmlns = "urn:brocade.com:mgmt:brocade-fcoe" ) fcoe_fabric_map = ET . SubElement ( fcoe , "fcoe-fabric-map" ) fcoe_fabric_map_name_key = ET . SubElement ( fcoe_fabric_map , "fcoe-fabric-map-name" ) fcoe_fabric_map_name_key . text = kwargs . po...
def _index_document ( self , document , force = False ) : """Adds dataset document to the index ."""
query = text ( """ INSERT INTO dataset_index(vid, title, keywords, doc) VALUES(:vid, :title, string_to_array(:keywords, ' '), to_tsvector('english', :doc)); """ ) self . execute ( query , ** document )
def authenticate_user ( self ) : """Confirm user authentication Make sure the user has provided all of the authentication info we need ."""
cloud_config = os_client_config . OpenStackConfig ( ) . get_one_cloud ( cloud = self . options . os_cloud , argparse = self . options , network_api_version = self . api_version , verify = not self . options . insecure ) verify , cert = cloud_config . get_requests_verify_args ( ) # TODO ( singhj ) : Remove dependancy on...
def _get_formatted_val ( self , obj , attribute , column ) : """Return the formatted value of the attribute " attribute " of the obj " obj " regarding the column ' s description : param obj obj : The instance we manage : param str attribute : The string defining the path to access the end attribute we want ...
attr_path = attribute . split ( '.' ) val = None tmp_val = obj for attr in attr_path : tmp_val = getattr ( tmp_val , attr , None ) if tmp_val is None : break if tmp_val is not None : val = tmp_val value = format_value ( column , val , self . config_key ) return format_py3o_val ( value )
def exec_command ( self , cmd , tmp_path , sudo_user , sudoable = False , executable = '/bin/sh' ) : '''run a command on the remote host'''
vvv ( "EXEC COMMAND %s" % cmd ) if self . runner . sudo and sudoable : raise errors . AnsibleError ( "fireball does not use sudo, but runs as whoever it was initiated as. (That itself is where to use sudo)." ) data = dict ( mode = 'command' , cmd = cmd , tmp_path = tmp_path , executable = executable , ) data = uti...
def collect_snmp ( self , device , host , port , community ) : """Collect Netscaler SNMP stats from device"""
# Log self . log . info ( "Collecting Netscaler statistics from: %s" , device ) # Set timestamp timestamp = time . time ( ) # Collect Netscaler System OIDs for k , v in self . NETSCALER_SYSTEM_GUAGES . items ( ) : # Get Metric Name and Value metricName = '.' . join ( [ k ] ) metricValue = int ( self . get ( v ,...
def regexp_replace ( str , pattern , replacement ) : r"""Replace all substrings of the specified string value that match regexp with rep . > > > df = spark . createDataFrame ( [ ( ' 100-200 ' , ) ] , [ ' str ' ] ) > > > df . select ( regexp _ replace ( ' str ' , r ' ( \ d + ) ' , ' - - ' ) . alias ( ' d ' ) ) ....
sc = SparkContext . _active_spark_context jc = sc . _jvm . functions . regexp_replace ( _to_java_column ( str ) , pattern , replacement ) return Column ( jc )
def process_base_field ( cls , field , key ) : """Preprocess field instances . : param field : Field object : param key : Key where field was found"""
if not field . name : field . name = key elif key != field . name : if not isinstance ( field . alias , list ) : field . alias = [ key ] else : field . alias . insert ( 0 , key ) setattr ( cls , field . name , field ) cls . prepare_field ( field ) if field . alias : for alias_name in...
def multiple_signatures ( self , statement , to_sign , key = None , key_file = None , sign_alg = None , digest_alg = None ) : """Sign multiple parts of a statement : param statement : The statement that should be sign , this is XML text : param to _ sign : A list of ( items , id , id attribute name ) tuples tha...
for ( item , sid , id_attr ) in to_sign : if not sid : if not item . id : sid = item . id = sid ( ) else : sid = item . id if not item . signature : item . signature = pre_signature_part ( sid , self . cert_file , sign_alg = sign_alg , digest_alg = digest_alg ) ...
def negate_gate ( wordlen , input = 'x' , output = '~x' ) : """Implements two ' s complement negation ."""
neg = bitwise_negate ( wordlen , input , "tmp" ) inc = inc_gate ( wordlen , "tmp" , output ) return neg >> inc
def get_driver_whitelist ( driver ) : # noqa : E501 """Retrieve the whitelist in the driver Retrieve the whitelist in the driver # noqa : E501 : param driver : The driver to use for the request . ie . github : type driver : str : rtype : Response"""
response = errorIfUnauthorized ( role = 'admin' ) if response : return response else : response = ApitaxResponse ( ) driver : Driver = LoadedDrivers . getDriver ( driver ) response . body . add ( { 'whitelist' : driver . getDriverWhitelist ( ) } ) return Response ( status = 200 , body = response . getResponseBo...
def cssify ( css_dict ) : """Function to get CartoCSS from Python dicts"""
css = '' for key , value in dict_items ( css_dict ) : css += '{key} {{ ' . format ( key = key ) for field , field_value in dict_items ( value ) : css += ' {field}: {field_value};' . format ( field = field , field_value = field_value ) css += '} ' return css . strip ( )
def holiday_description ( self ) : """Return the holiday description . In case none exists will return None ."""
entry = self . _holiday_entry ( ) desc = entry . description return desc . hebrew . long if self . hebrew else desc . english
def _to_numpy ( Z ) : """Converts a None , list , np . ndarray , or torch . Tensor to np . ndarray ; also handles converting sparse input to dense ."""
if Z is None : return Z elif issparse ( Z ) : return Z . toarray ( ) elif isinstance ( Z , np . ndarray ) : return Z elif isinstance ( Z , list ) : return np . array ( Z ) elif isinstance ( Z , torch . Tensor ) : return Z . cpu ( ) . numpy ( ) else : msg = ( f"Expected None, list, numpy.ndarray ...
def process_response ( self , request , response ) : """Send broken link emails for relevant 404 NOT FOUND responses ."""
if response . status_code == 404 and not settings . DEBUG : domain = request . get_host ( ) path = request . get_full_path ( ) referer = force_text ( request . META . get ( 'HTTP_REFERER' , '' ) , errors = 'replace' ) if not self . is_ignorable_request ( request , path , domain , referer ) : ua ...
def delay_host_notification ( self , host , notification_time ) : """Modify host first notification delay Format of the line that triggers function call : : DELAY _ HOST _ NOTIFICATION ; < host _ name > ; < notification _ time > : param host : host to edit : type host : alignak . objects . host . Host : p...
host . first_notification_delay = notification_time self . send_an_element ( host . get_update_status_brok ( ) )
def cmd ( send , msg , args ) : """Throw something . Syntax : { command } < object > [ at < target > ]"""
users = get_users ( args ) if " into " in msg and msg != "into" : match = re . match ( '(.*) into (.*)' , msg ) if match : msg = 'throws %s into %s' % ( match . group ( 1 ) , match . group ( 2 ) ) send ( msg , 'action' ) else : return elif " at " in msg and msg != "at" : match = ...
def parse_arguments ( ) : """Parse command line arguments"""
parser = argparse . ArgumentParser ( prog = sys . argv [ 0 ] , description = 'Send Webhooks Channel events to IFTTT' , epilog = 'Visit https://ifttt.com/channels/maker_webhooks for more information' ) parser . add_argument ( '--version' , action = 'version' , version = pyfttt . __version__ ) sgroup = parser . add_argum...
def _key_values ( self , sn : "SequenceNode" ) -> Union [ EntryKeys , EntryValue ] : """Parse leaf - list value or list keys ."""
try : keys = self . up_to ( "/" ) except EndOfInput : keys = self . remaining ( ) if not keys : raise UnexpectedInput ( self , "entry value or keys" ) if isinstance ( sn , LeafListNode ) : return EntryValue ( unquote ( keys ) ) ks = keys . split ( "," ) try : if len ( ks ) != len ( sn . keys ) : ...
def retrieve_all_pages ( api_endpoint , ** kwargs ) : """Some MTP apis are paginated using Django Rest Framework ' s LimitOffsetPagination paginator , this method loads all pages into a single results list : param api _ endpoint : slumber callable , e . g . ` [ api _ client ] . cashbook . transactions . locked ...
page_size = getattr ( settings , 'REQUEST_PAGE_SIZE' , 20 ) loaded_results = [ ] offset = 0 while True : response = api_endpoint ( limit = page_size , offset = offset , ** kwargs ) count = response . get ( 'count' , 0 ) loaded_results += response . get ( 'results' , [ ] ) if len ( loaded_results ) >= co...
def get_issue_by_ref ( self , ref ) : """Get a : class : ` Issue ` by ref . : param ref : : class : ` Issue ` reference"""
response = self . requester . get ( '/{endpoint}/by_ref?ref={us_ref}&project={project_id}' , endpoint = Issue . endpoint , us_ref = ref , project_id = self . id ) return Issue . parse ( self . requester , response . json ( ) )
def _check_subject_identifier_matches_requested ( self , authentication_request , sub ) : # type ( oic . message . AuthorizationRequest , str ) - > None """Verifies the subject identifier against any requested subject identifier using the claims request parameter . : param authentication _ request : authenticatio...
if 'claims' in authentication_request : requested_id_token_sub = authentication_request [ 'claims' ] . get ( 'id_token' , { } ) . get ( 'sub' ) requested_userinfo_sub = authentication_request [ 'claims' ] . get ( 'userinfo' , { } ) . get ( 'sub' ) if requested_id_token_sub and requested_userinfo_sub and req...
def anneal ( self ) : """Minimizes the energy of a system by simulated annealing . Parameters state : an initial arrangement of the system Returns ( state , energy ) : the best state and energy found ."""
step = 0 self . start = time . time ( ) # Precompute factor for exponential cooling from Tmax to Tmin if self . Tmin <= 0.0 : raise Exception ( 'Exponential cooling requires a minimum "\ "temperature greater than zero.' ) Tfactor = - math . log ( self . Tmax / self . Tmin ) # Note initial state T = ...
def checkup_git_repos_legacy ( repos , base_dir = '~/repos' , verbose = False , prefix = '' , postfix = '' ) : '''Checkout or update git repos . repos must be a list of dicts each with an url and optional with a name value .'''
run ( flo ( 'mkdir -p {base_dir}' ) ) for repo in repos : cur_base_dir = repo . get ( 'base_dir' , base_dir ) checkup_git_repo_legacy ( url = repo [ 'url' ] , name = repo . get ( 'name' , None ) , base_dir = cur_base_dir , verbose = verbose , prefix = prefix , postfix = postfix )
def is_valid ( self , tol : float = DISTANCE_TOLERANCE ) -> bool : """True if SiteCollection does not contain atoms that are too close together . Note that the distance definition is based on type of SiteCollection . Cartesian distances are used for non - periodic Molecules , while PBC is taken into account f...
if len ( self . sites ) == 1 : return True all_dists = self . distance_matrix [ np . triu_indices ( len ( self ) , 1 ) ] return bool ( np . min ( all_dists ) > tol )
def makeblastdb ( self ) : """Makes blast database files from targets as necessary"""
while True : # while daemon fastapath = self . dqueue . get ( ) # grabs fastapath from dqueue # remove the path and the file extension for easier future globbing db = fastapath . split ( '.' ) [ 0 ] nhr = '{}.nhr' . format ( db ) # add nhr for searching if not os . path . isfile ( str ( nhr ...
def execute_policy ( self , scaling_group , policy ) : """Executes the specified policy for the scaling group ."""
return self . _manager . execute_policy ( scaling_group = scaling_group , policy = policy )
def is_shape ( df , shape ) : """Asserts that the DataFrame is of a known shape . Parameters df : DataFrame shape : tuple ( n _ rows , n _ columns ) . Use None or - 1 if you don ' t care about a dimension . Returns df : DataFrame"""
try : check = np . all ( np . equal ( df . shape , shape ) | ( np . equal ( shape , [ - 1 , - 1 ] ) | np . equal ( shape , [ None , None ] ) ) ) assert check except AssertionError as e : msg = ( "Expected shape: {}\n" "\t\tActual shape: {}" . format ( shape , df . shape ) ) e . args = ( msg , ) ra...
def send_to_help ( self , name , signature , force = False ) : """qstr1 : obj _ text , qstr2 : argpspec , qstr3 : note , qstr4 : doc _ text"""
if not force and not self . help_enabled : return if self . help is not None and ( force or self . help . dockwidget . isVisible ( ) ) : signature = to_text_string ( signature ) signature = unicodedata . normalize ( "NFKD" , signature ) parts = signature . split ( '\n\n' ) definition = parts [ 0 ] ...
def input ( self ) : """Return a list of all the aesthetics covered by the scales ."""
lst = [ s . aesthetics for s in self ] return list ( itertools . chain ( * lst ) )
def merge_list_members ( self , list_ , record_data , merge_rule ) : """Responsys . mergeListMembers call Accepts : InteractObject list _ RecordData record _ data ListMergeRule merge _ rule Returns a MergeResult"""
list_ = list_ . get_soap_object ( self . client ) record_data = record_data . get_soap_object ( self . client ) merge_rule = merge_rule . get_soap_object ( self . client ) return MergeResult ( self . call ( 'mergeListMembers' , list_ , record_data , merge_rule ) )
def equal ( x , y ) : """Return True if x = = y and False otherwise . This function returns False whenever x and / or y is a NaN ."""
x = BigFloat . _implicit_convert ( x ) y = BigFloat . _implicit_convert ( y ) return mpfr . mpfr_equal_p ( x , y )
def GetIpForwardTable ( ) : """Return all Windows routes ( IPv4 only ) from iphlpapi"""
# We get the size first size = ULONG ( ) res = _GetIpForwardTable ( None , byref ( size ) , False ) if res != 0x7a : # ERROR _ INSUFFICIENT _ BUFFER - > populate size raise RuntimeError ( "Error getting structure length (%d)" % res ) # Now let ' s build our buffer pointer_type = PMIB_IPFORWARDTABLE buffer = create_...
def apseudo ( Ss , ipar , sigma ) : """draw a bootstrap sample of Ss"""
Is = random . randint ( 0 , len ( Ss ) - 1 , size = len ( Ss ) ) # draw N random integers # Ss = np . array ( Ss ) if not ipar : # ipar = = 0: BSs = Ss [ Is ] else : # need to recreate measurement - then do the parametric stuffr A , B = design ( 6 ) # get the design matrix for 6 measurementsa K , BSs = ...
def _safe_rmtree ( dir_ : str ) : """Wrap ` ` shutil . rmtree ` ` to inform user about ( un ) success ."""
try : rmtree ( dir_ ) except OSError : logging . warning ( '\t\t Skipping %s due to OSError' , dir_ ) else : logging . debug ( '\t\t Deleted %s' , dir_ )
def attribute ( element , attribute , default = None ) : """Returns the value of an attribute , or a default if it ' s not defined : param element : The XML Element object : type element : etree . _ Element : param attribute : The name of the attribute to evaluate : type attribute : basestring : param def...
attribute_value = element . get ( attribute ) return attribute_value if attribute_value is not None else default
def get_id_type_map ( id_list : Iterable [ str ] ) -> Dict [ str , List [ str ] ] : """Given a list of ids return their types : param id _ list : list of ids : return : dictionary where the id is the key and the value is a list of types"""
type_map = { } filter_out_types = [ 'cliqueLeader' , 'Class' , 'Node' , 'Individual' , 'quality' , 'sequence feature' ] for node in get_scigraph_nodes ( id_list ) : type_map [ node [ 'id' ] ] = [ typ . lower ( ) for typ in node [ 'meta' ] [ 'types' ] if typ not in filter_out_types ] return type_map
def site_config_dir ( self ) : """Return ` ` site _ config _ dir ` ` ."""
directory = appdirs . site_config_dir ( self . appname , self . appauthor , version = self . version , multipath = self . multipath ) if self . create : self . _ensure_directory_exists ( directory ) return directory
def put ( self , url , data ) : """Make a PUT request to save data . data should be a dictionary ."""
response = self . _run_method ( 'PUT' , url , data = data ) log . debug ( "OUTPUT: %s" % response . content ) return self . _handle_response ( url , response )
def ndarray_shm ( shape , dtype , location , readonly = False , order = 'F' , ** kwargs ) : """Create a shared memory numpy array . Requires / dev / shm to exist ."""
nbytes = Vec ( * shape ) . rectVolume ( ) * np . dtype ( dtype ) . itemsize available = psutil . virtual_memory ( ) . available preexisting = 0 # This might only work on Ubuntu shmloc = os . path . join ( SHM_DIRECTORY , location ) if os . path . exists ( shmloc ) : preexisting = os . path . getsize ( shmloc ) elif...
def _environment_variables ( ) -> Dict [ str , str ] : """Wraps ` os . environ ` to filter out non - encodable values ."""
return { key : value for key , value in os . environ . items ( ) if _is_encodable ( value ) }
def decrypt ( self , text , app_id ) : """对密文进行解密 : param text : 需要解密的密文 : param app _ id : 微信公众平台的 AppID : return : 解密后的字符串"""
text = to_binary ( text ) decryptor = self . cipher . decryptor ( ) plain_text = decryptor . update ( base64 . b64decode ( text ) ) + decryptor . finalize ( ) padding = byte2int ( plain_text , - 1 ) content = plain_text [ 16 : - padding ] xml_len = socket . ntohl ( struct . unpack ( "I" , content [ : 4 ] ) [ 0 ] ) xml_...
def get_sngl_bank_chisqs ( self , instruments = None ) : """Get the single - detector \ chi ^ 2 for each row in the table ."""
if len ( self ) and instruments is None : instruments = map ( str , instrument_set_from_ifos ( self [ 0 ] . ifos ) ) elif instruments is None : instruments = [ ] return dict ( ( ifo , self . get_sngl_bank_chisq ( ifo ) ) for ifo in instruments )
def update ( self , validate = False ) : """Update the data associated with this snapshot by querying EC2. : type validate : bool : param validate : By default , if EC2 returns no data about the snapshot the update method returns quietly . If the validate param is True , however , it will raise a ValueErr...
rs = self . connection . get_all_snapshots ( [ self . id ] ) if len ( rs ) > 0 : self . _update ( rs [ 0 ] ) elif validate : raise ValueError ( '%s is not a valid Snapshot ID' % self . id ) return self . progress
def _generate_examples ( self , file_paths ) : """Generate QuickDraw bitmap examples . Given a list of file paths with data for each class label , generate examples in a random order . Args : file _ paths : ( dict of { str : str } ) the paths to files containing the data , indexed by label . Yields : ...
for label , path in sorted ( file_paths . items ( ) , key = lambda x : x [ 0 ] ) : with tf . io . gfile . GFile ( path , "rb" ) as f : class_images = np . load ( f ) for np_image in class_images : yield { "image" : np_image . reshape ( _QUICKDRAW_IMAGE_SHAPE ) , "label" : label , }
def send_file ( self , fp , headers = None , cb = None , num_cb = 10 , query_args = None , chunked_transfer = False , callback = None ) : """Upload a file to a key into a bucket on S3. : type fp : file : param fp : The file pointer to upload : type headers : dict : param headers : The headers to pass along ...
provider = self . bucket . connection . provider def sender ( http_conn , method , path , data , headers , sendback = None ) : http_conn . putrequest ( method , path ) for key in headers : http_conn . putheader ( key , headers [ key ] ) http_conn . endheaders ( ) if chunked_transfer : # MD5 for ...
def tokenize ( self , text , include_punc = True , nested = False ) : """Return a list of word tokens . : param text : string of text . : param include _ punc : ( optional ) whether to include punctuation as separate tokens . Default to True . : param nested : ( optional ) whether to return tokens as nested...
self . tokens = [ w for w in ( self . word_tokenize ( s , include_punc ) for s in self . sent_tokenize ( text ) ) ] if nested : return self . tokens else : return list ( chain . from_iterable ( self . tokens ) )
def pem_managed ( name , text , backup = False , ** kwargs ) : '''Manage the contents of a PEM file directly with the content in text , ensuring correct formatting . name : The path to the file to manage text : The PEM formatted text to write . kwargs : Any arguments supported by : py : func : ` file . ...
file_args , kwargs = _get_file_args ( name , ** kwargs ) file_args [ 'contents' ] = salt . utils . stringutils . to_str ( __salt__ [ 'x509.get_pem_entry' ] ( text = text ) ) return __states__ [ 'file.managed' ] ( ** file_args )
def modify_classes ( ) : """Auto - discover INSTALLED _ APPS class _ modifiers . py modules and fail silently when not present . This forces an import on them to modify any classes they may want ."""
import copy from django . conf import settings from django . contrib . admin . sites import site from django . utils . importlib import import_module from django . utils . module_loading import module_has_submodule for app in settings . INSTALLED_APPS : mod = import_module ( app ) # Attempt to import the app ' ...
def _get_bios_mappings_resource ( self , data ) : """Get the Mappings resource . : param data : Existing Bios settings of the server . : returns : mappings settings . : raises : IloCommandNotSupportedError , if resource is not found . : raises : IloError , on an error from iLO ."""
try : map_uri = data [ 'links' ] [ 'Mappings' ] [ 'href' ] except KeyError : msg = ( 'Mappings resource not found.' ) raise exception . IloCommandNotSupportedError ( msg ) status , headers , map_settings = self . _rest_get ( map_uri ) if status != 200 : msg = self . _get_extended_error ( map_settings ) ...
def clean_process_meta ( self ) : """Remove all process and build metadata"""
ds = self . dataset ds . config . build . clean ( ) ds . config . process . clean ( ) ds . commit ( ) self . state = self . STATES . CLEANED
def parse ( self , node ) : """Parse a given node . This function in turn calls the ` parse _ < nodeType > ` functions which handle the respective nodes ."""
pm = getattr ( self , "parse_%s" % node . __class__ . __name__ ) pm ( node )
def walk_up_dirs ( path ) : """Yields absolute directories starting with the given path , and iterating up through all it ' s parents , until it reaches a root directory"""
prev_path = None current_path = os . path . abspath ( path ) while current_path != prev_path : yield current_path prev_path = current_path current_path = os . path . dirname ( prev_path )
def publish ( self , value ) : """Accepts : float Returns : float"""
value = super ( Float , self ) . publish ( value ) if isinstance ( value , int ) : value = float ( value ) return value
def project_add_tags ( object_id , input_params = { } , always_retry = True , ** kwargs ) : """Invokes the / project - xxxx / addTags API method . For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Projects # API - method % 3A - % 2Fproject - xxxx % 2FaddTags"""
return DXHTTPRequest ( '/%s/addTags' % object_id , input_params , always_retry = always_retry , ** kwargs )
def get_filepaths_and_exts ( self ) : """Returns the paths of the output files produced by self and its extensions"""
filepaths = [ prod . filepath for prod in self . products ] exts = [ prod . ext for prod in self . products ] return filepaths , exts
def _match_service ( self , line_with_color ) : """Return line if line matches this service ' s name , return None otherwise ."""
line = re . compile ( "(\x1b\[\d+m)+" ) . sub ( "" , line_with_color ) # Strip color codes regexp = re . compile ( r"^\[(.*?)\]\s(.*?)$" ) if regexp . match ( line ) : title = regexp . match ( line ) . group ( 1 ) . strip ( ) if title in self . titles : return ( title , regexp . match ( line ) . group (...
def cluster_ensembles ( cluster_runs , hdf5_file_name = None , verbose = False , N_clusters_max = None ) : """Call up to three different functions for heuristic ensemble clustering ( namely CSPA , HGPA and MCLA ) then select as the definitive consensus clustering the one with the highest average mutual informat...
if hdf5_file_name is None : hdf5_file_name = './Cluster_Ensembles.h5' fileh = tables . open_file ( hdf5_file_name , 'w' ) fileh . create_group ( fileh . root , 'consensus_group' ) fileh . close ( ) cluster_ensemble = [ ] score = np . empty ( 0 ) if cluster_runs . shape [ 1 ] > 10000 : consensus_functions = [ HG...
def validate_key ( key : str ) : """Validates the given key . : param key : the key to validate : raises InvalidKeyError : raised if the given key is invalid"""
if "//" in key : raise DoubleSlashKeyError ( key ) elif normpath ( key ) != key : raise NonNormalisedKeyError ( key )
def flow ( self , active ) : """Enable / disable flow from peer This method asks the peer to pause or restart the flow of content data . This is a simple flow - control mechanism that a peer can use to avoid oveflowing its queues or otherwise finding itself receiving more messages than it can process . No...
args = AMQPWriter ( ) args . write_bit ( active ) self . _send_method ( ( 20 , 20 ) , args ) return self . wait ( allowed_methods = [ ( 20 , 21 ) , # Channel . flow _ ok ] )
def plotPotentials ( Pot , rmin = 0. , rmax = 1.5 , nrs = 21 , zmin = - 0.5 , zmax = 0.5 , nzs = 21 , phi = None , xy = False , t = 0. , effective = False , Lz = None , ncontours = 21 , savefilename = None , aspect = None , justcontours = False , levels = None , cntrcolors = None ) : """NAME : plotPotentials PU...
Pot = flatten ( Pot ) if _APY_LOADED : if hasattr ( Pot , '_ro' ) : tro = Pot . _ro else : tro = Pot [ 0 ] . _ro if isinstance ( rmin , units . Quantity ) : rmin = rmin . to ( units . kpc ) . value / tro if isinstance ( rmax , units . Quantity ) : rmax = rmax . to ( units...
def output_sub_line ( gandi , key , val , justify ) : """Base helper to output a key value using left justify ."""
msg = ( '\t%%-%ds:%%s' % justify ) % ( key , ( ' %s' % val ) if val else '' ) gandi . echo ( msg )
def getname ( obj ) : """Return the most qualified name of an object : param obj : object to fetch name : return : name of ` ` obj ` `"""
for name_attribute in ( '__qualname__' , '__name__' ) : try : # an object always has a class , as per Python data model return getattr ( obj , name_attribute , getattr ( obj . __class__ , name_attribute ) ) except AttributeError : pass raise TypeError ( 'object of type %r does not define a canon...
def train_sbrl ( data_file , label_file , lambda_ = 20 , eta = 2 , max_iters = 300000 , n_chains = 20 , alpha = 1 , seed = None , verbose = 0 ) : """The basic training function of the scalable bayesian rule list . Users are suggested to use SBRL instead of this function . It takes the paths of the pre - process...
if isinstance ( alpha , int ) : alphas = np . array ( [ alpha ] , dtype = np . int32 ) elif isinstance ( alpha , list ) : for a in alpha : assert isinstance ( a , int ) alphas = np . array ( alpha , dtype = np . int32 ) else : raise ValueError ( 'the argument alpha can only be int or List[int]' ...
def get ( self , ** kwargs ) : """Search records . Permissions : the ` list _ permission _ factory ` permissions are checked . : returns : Search result containing hits and aggregations as returned by invenio - search ."""
default_results_size = current_app . config . get ( 'RECORDS_REST_DEFAULT_RESULTS_SIZE' , 10 ) page = request . values . get ( 'page' , 1 , type = int ) size = request . values . get ( 'size' , default_results_size , type = int ) if page * size >= self . max_result_window : raise MaxResultWindowRESTError ( ) # Argu...
def packet_events ( packet : dict ) -> Generator : """Return list of all events in the packet . > > > x = list ( packet _ events ( { . . . ' protocol ' : ' alecto v1 ' , . . . ' id ' : ' ec02 ' , . . . ' temperature ' : 1.0, . . . ' temperature _ unit ' : ' ° C ' , . . . ' humidity ' : 10, . . . ' hum...
field_abbrev = { v : k for k , v in PACKET_FIELDS . items ( ) } packet_id = serialize_packet_id ( packet ) events = { f : v for f , v in packet . items ( ) if f in field_abbrev } if 'command' in events or 'version' in events : # switch events only have one event in each packet yield dict ( id = packet_id , ** event...
def get_version_from_dirname ( name , parent ) : """Extracted sdist"""
parent = parent . resolve ( ) re_dirname = re . compile ( f"{name}-{RE_VERSION}$" ) if not re_dirname . match ( parent . name ) : return None return Version . parse ( parent . name [ len ( name ) + 1 : ] )
def get_section_key_line ( self , data , key , opt_extension = ':' ) : """Get the next section line for a given key . : param data : the data to proceed : param key : the key : param opt _ extension : an optional extension to delimit the opt value"""
return super ( GoogledocTools , self ) . get_section_key_line ( data , key , opt_extension )