signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def intensity ( image ) : '''Calculates the average intensity of the pixels in an image . Accepts both RGB and grayscale images . : param image : numpy . ndarray : returns : image intensity : rtype : float'''
if len ( image . shape ) > 2 : # Convert to grayscale image = cv2 . cvtColor ( image , cv2 . COLOR_RGB2GRAY ) / 255 elif issubclass ( image . dtype . type , np . integer ) : image /= 255 return float ( np . sum ( image ) / np . prod ( image . shape ) )
def opt ( self , x_init , f_fp = None , f = None , fp = None ) : """Run the optimizer"""
rcstrings = [ '' , 'Maximum number of iterations exceeded' , 'Gradient and/or function calls not changing' ] opt_dict = { } if self . xtol is not None : print ( "WARNING: bfgs doesn't have an xtol arg, so I'm going to ignore it" ) if self . ftol is not None : print ( "WARNING: bfgs doesn't have an ftol arg, so ...
def register_arguments ( cls , parser ) : """Register command line options . Implement this method for normal options behavior with protection from OptionConflictErrors . If you override this method and want the default - - $ name option ( s ) to be registered , be sure to call super ( ) ."""
if hasattr ( cls , "_dont_register_arguments" ) : return prefix = cls . configuration_key_prefix ( ) cfgkey = cls . configuration_key parser . add_argument ( "--%s-%s" % ( prefix , cfgkey ) , action = "store_true" , dest = "%s_%s" % ( prefix , cfgkey ) , default = False , help = "%s: %s" % ( cls . __name__ , cls . ...
def sort_def_dict ( def_dict : Dict [ str , List [ str ] ] ) -> Dict [ str , List [ str ] ] : """Sort values of the lists of a defaultdict ( list ) ."""
for _ , dd_list in def_dict . items ( ) : dd_list . sort ( ) return def_dict
def split_by_files ( self , valid_names : 'ItemList' ) -> 'ItemLists' : "Split the data by using the names in ` valid _ names ` for validation ."
if isinstance ( self . items [ 0 ] , Path ) : return self . split_by_valid_func ( lambda o : o . name in valid_names ) else : return self . split_by_valid_func ( lambda o : os . path . basename ( o ) in valid_names )
def add ( obj ) : '''Handle a badge add API . - Expecting badge _ fieds as payload - Return the badge as payload - Return 200 if the badge is already - Return 201 if the badge is added'''
Form = badge_form ( obj . __class__ ) form = api . validate ( Form ) kind = form . kind . data badge = obj . get_badge ( kind ) if badge : return badge else : return obj . add_badge ( kind ) , 201
def _handle_watch_message ( self , message ) : """Processes a binary message received from the watch and broadcasts the relevant events . : param message : A raw message from the watch , without any transport framing . : type message : bytes"""
if self . log_protocol_level is not None : logger . log ( self . log_protocol_level , "<- %s" , hexlify ( message ) . decode ( ) ) message = self . pending_bytes + message while len ( message ) >= 4 : try : packet , length = PebblePacket . parse_message ( message ) except IncompleteMessage : ...
def put_item ( TableName = None , Item = None , Expected = None , ReturnValues = None , ReturnConsumedCapacity = None , ReturnItemCollectionMetrics = None , ConditionalOperator = None , ConditionExpression = None , ExpressionAttributeNames = None , ExpressionAttributeValues = None ) : """Creates a new item , or rep...
pass
def worker_logstart ( self , node , nodeid , location ) : """Emitted when a node calls the pytest _ runtest _ logstart hook ."""
self . config . hook . pytest_runtest_logstart ( nodeid = nodeid , location = location )
def run ( self , epochs ) : """Description : Run training for LipNet"""
best_loss = sys . maxsize for epoch in trange ( epochs ) : iter_no = 0 # # train sum_losses , len_losses = self . train_batch ( self . train_dataloader ) if iter_no % 20 == 0 : current_loss = sum_losses / len_losses print ( "[Train] epoch:{e} iter:{i} loss:{l:.4f}" . format ( e = epoch ,...
def determine_encoding ( path , default = None ) : """Determines the encoding of a file based on byte order marks . Arguments : path ( str ) : The path to the file . default ( str , optional ) : The encoding to return if the byte - order - mark lookup does not return an answer . Returns : str : The enco...
byte_order_marks = ( ( 'utf-8-sig' , ( codecs . BOM_UTF8 , ) ) , ( 'utf-16' , ( codecs . BOM_UTF16_LE , codecs . BOM_UTF16_BE ) ) , ( 'utf-32' , ( codecs . BOM_UTF32_LE , codecs . BOM_UTF32_BE ) ) , ) try : with open ( path , 'rb' ) as infile : raw = infile . read ( 4 ) except IOError : return default f...
def is_newer ( source , target ) : """Return true if ' source ' exists and is more recently modified than ' target ' , or if ' source ' exists and ' target ' doesn ' t . Return false if both exist and ' target ' is the same age or younger than ' source ' . Raise ValueError if ' source ' does not exist ."""
if not os . path . exists ( source ) : raise ValueError ( "file '%s' does not exist" % source ) if not os . path . exists ( target ) : return 1 from stat import ST_MTIME mtime1 = os . stat ( source ) [ ST_MTIME ] mtime2 = os . stat ( target ) [ ST_MTIME ] return mtime1 > mtime2
def _parse_tol ( rtol , atol ) : """Parse the tolerance keywords"""
# Process atol and rtol if rtol is None : rtol = - 12. * nu . log ( 10. ) else : # pragma : no cover rtol = nu . log ( rtol ) if atol is None : atol = - 12. * nu . log ( 10. ) else : # pragma : no cover atol = nu . log ( atol ) return ( rtol , atol )
def xml_iterator ( columns , rowlist , lang , add_vtype = False ) : """Convert an XML response into a double iterable , by rows and columns Options are : filter triples by language ( on literals ) , add element type"""
# Return the header row yield columns if not add_vtype else ( ( h , 'type' ) for h in columns ) # Now the data rows for row in rowlist : if not lang_match_xml ( row , lang ) : continue rowdata = { nam : val for nam , val in xml_row ( row , lang ) } yield ( rowdata . get ( field , ( '' , '' ) ) for f...
def tarfile_extract ( fileobj , dest_path ) : """Extract a tarfile described by a file object to a specified path . Args : fileobj ( file ) : File object wrapping the target tarfile . dest _ path ( str ) : Path to extract the contents of the tarfile to ."""
# Though this method doesn ' t fit cleanly into the TarPartition object , # tarballs are only ever extracted for partitions so the logic jives # for the most part . tar = tarfile . open ( mode = 'r|' , fileobj = fileobj , bufsize = pipebuf . PIPE_BUF_BYTES ) # canonicalize dest _ path so the prefix check below works de...
def directions ( client , origin , destination , mode = None , waypoints = None , alternatives = False , avoid = None , language = None , units = None , region = None , departure_time = None , arrival_time = None , optimize_waypoints = False , transit_mode = None , transit_routing_preference = None , traffic_model = No...
params = { "origin" : convert . latlng ( origin ) , "destination" : convert . latlng ( destination ) } if mode : # NOTE ( broady ) : the mode parameter is not validated by the Maps API # server . Check here to prevent silent failures . if mode not in [ "driving" , "walking" , "bicycling" , "transit" ] : rai...
def partition_found ( partition , description ) : """returns True , if the partition ( - - partition ) is in the description we received from the host"""
# if we want to have a linux partition ( / ) we use the full path ( startswith " / " would result in / / var / dev etc ) . # if we start with something else , we use the startswith function if "/" in partition : use_fullcompare = True else : use_fullcompare = False if use_fullcompare and ( partition == descript...
def generate_thumbnail ( self , thumbnail_options , high_resolution = False , silent_template_exception = False ) : """Return an unsaved ` ` ThumbnailFile ` ` containing a thumbnail image . The thumbnail image is generated using the ` ` thumbnail _ options ` ` dictionary ."""
thumbnail_options = self . get_options ( thumbnail_options ) orig_size = thumbnail_options [ 'size' ] # remember original size # Size sanity check . min_dim , max_dim = 0 , 0 for dim in orig_size : try : dim = int ( dim ) except ( TypeError , ValueError ) : continue min_dim , max_dim = min (...
async def prefetch ( self , query , * subqueries ) : """Asynchronous version of the ` prefetch ( ) ` from peewee . : return : Query that has already cached data for subqueries"""
query = self . _swap_database ( query ) subqueries = map ( self . _swap_database , subqueries ) return ( await prefetch ( query , * subqueries ) )
def feed_monitors ( self ) : """Pull from the cached monitors data and feed the workers queue . Run every interval ( refresh : test ) ."""
self . thread_debug ( "Filling worker queue..." , module = 'feed_monitors' ) for mon in self . monitors : self . thread_debug ( " Adding " + mon [ 'title' ] ) self . workers_queue . put ( mon )
def whatIfOrder ( self , contract : Contract , order : Order ) -> OrderState : """Retrieve commission and margin impact without actually placing the order . The given order will not be modified in any way . This method is blocking . Args : contract : Contract to test . order : Order to test ."""
return self . _run ( self . whatIfOrderAsync ( contract , order ) )
def update_aggregation ( self , course , aggregationid , new_data ) : """Update aggregation and returns a list of errored students"""
student_list = self . user_manager . get_course_registered_users ( course , False ) # If aggregation is new if aggregationid == 'None' : # Remove _ id for correct insertion del new_data [ '_id' ] new_data [ "courseid" ] = course . get_id ( ) # Insert the new aggregation result = self . database . aggreg...
def get_group_permissions ( self , user_obj , obj = None ) : """Returns a set of permission strings that this user has through his / her groups ."""
if user_obj . is_anonymous ( ) or obj is not None : return set ( ) if not hasattr ( user_obj , '_group_perm_cache' ) : if user_obj . is_superuser : perms = Permission . objects . all ( ) else : user_groups_field = get_user_class ( ) . _meta . get_field ( 'groups' ) # pylint : disable...
def lookup_search_result ( self , result , ** kw ) : """Perform : meth : ` lookup ` on return value of : meth : ` search ` ."""
return self . lookup ( s [ 'id_str' ] for s in result [ 'statuses' ] , ** kw )
def set_mode_broodlord_params ( self , zerg_count = None , vassal_overload_sos_interval = None , vassal_queue_items_sos = None ) : """This mode is a way for a vassal to ask for reinforcements to the Emperor . Reinforcements are new vassals spawned on demand generally bound on the same socket . . . warning : : I...
self . _set ( 'emperor-broodlord' , zerg_count ) self . _set ( 'vassal-sos' , vassal_overload_sos_interval ) self . _set ( 'vassal-sos-backlog' , vassal_queue_items_sos ) return self . _section
def similar ( obj1 , obj2 ) : """Calculate similarity between two ( Comparable ) objects ."""
Comparable . log ( obj1 , obj2 , '%' ) similarity = obj1 . similarity ( obj2 ) Comparable . log ( obj1 , obj2 , '%' , result = similarity ) return similarity
def recommend_for_record ( self , record_id , depth = 4 , num_reco = 10 ) : """Calculate recommendations for record ."""
data = calc_scores_for_node ( self . _graph , record_id , depth , num_reco ) return data . Node . tolist ( ) , data . Score . tolist ( )
def add_reference ( self , subj : Node , val : str ) -> None : """Add a fhir : link and RDF type arc if it can be determined : param subj : reference subject : param val : reference value"""
match = FHIR_RESOURCE_RE . match ( val ) ref_uri_str = res_type = None if match : ref_uri_str = val if match . group ( FHIR_RE_BASE ) else ( self . _base_uri + urllib . parse . quote ( val ) ) res_type = match . group ( FHIR_RE_RESOURCE ) elif '://' in val : ref_uri_str = val res_type = "Resource" elif ...
def get_jid ( jid ) : '''Return the information returned when the specified job id was executed'''
cb_ = _get_connection ( ) _verify_views ( ) ret = { } for result in cb_ . query ( DESIGN_NAME , 'jid_returns' , key = six . text_type ( jid ) , include_docs = True ) : ret [ result . value ] = result . doc . value return ret
def _read_stc ( stc_file ) : """Read Segment Table of Contents file . Returns hdr : dict - next _ segment : Sample frequency in Hertz - final : Number of channels stored - padding : Padding stamps : ndarray of dtype - segment _ name : Name of ERD / ETC file segment - start _ stamp : First sample sta...
hdr = _read_hdr_file ( stc_file ) # read header the normal way stc_dtype = dtype ( [ ( 'segment_name' , 'a256' ) , ( 'start_stamp' , '<i' ) , ( 'end_stamp' , '<i' ) , ( 'sample_num' , '<i' ) , ( 'sample_span' , '<i' ) ] ) with stc_file . open ( 'rb' ) as f : f . seek ( 352 ) # end of header hdr [ 'next_segm...
def check_physical ( self , line ) : """Run all physical checks on a raw input line ."""
self . physical_line = line if self . indent_char is None and len ( line ) and line [ 0 ] in ' \t' : self . indent_char = line [ 0 ] for name , check , argument_names in self . physical_checks : result = self . run_check ( check , argument_names ) if result is not None : offset , text = result ...
def geq_multiple ( self , other ) : """Return the next multiple of this time value , greater than or equal to ` ` other ` ` . If ` ` other ` ` is zero , return this time value . : rtype : : class : ` ~ aeneas . exacttiming . TimeValue `"""
if other == TimeValue ( "0.000" ) : return self return int ( math . ceil ( other / self ) ) * self
def trust_notebook ( self , path ) : """Trust the current notebook"""
if path . endswith ( '.ipynb' ) or path not in self . paired_notebooks : super ( TextFileContentsManager , self ) . trust_notebook ( path ) return fmt , formats = self . paired_notebooks [ path ] for alt_path , alt_fmt in paired_paths ( path , fmt , formats ) : if alt_fmt [ 'extension' ] == '.ipynb' : ...
def items ( sanitize = False ) : '''Return all of the minion ' s grains CLI Example : . . code - block : : bash salt ' * ' grains . items Sanitized CLI Example : . . code - block : : bash salt ' * ' grains . items sanitize = True'''
if salt . utils . data . is_true ( sanitize ) : out = dict ( __grains__ ) for key , func in six . iteritems ( _SANITIZERS ) : if key in out : out [ key ] = func ( out [ key ] ) return out else : return __grains__
def convert_values ( self , matchdict : Dict [ str , str ] ) -> Dict [ str , Any ] : """convert values of ` ` matchdict ` ` with converter this object has ."""
converted = { } for varname , value in matchdict . items ( ) : converter = self . converters [ varname ] converted [ varname ] = converter ( value ) return converted
def sparse_reindex ( self , new_index ) : """Conform sparse values to new SparseIndex Parameters new _ index : { BlockIndex , IntIndex } Returns reindexed : SparseSeries"""
if not isinstance ( new_index , splib . SparseIndex ) : raise TypeError ( "new index must be a SparseIndex" ) values = self . values values = values . sp_index . to_int_index ( ) . reindex ( values . sp_values . astype ( 'float64' ) , values . fill_value , new_index ) values = SparseArray ( values , sparse_index = ...
def _enqueue ( self , msg : Any , rid : int , signer : Signer ) -> None : """Enqueue the message into the remote ' s queue . : param msg : the message to enqueue : param rid : the id of the remote node"""
if rid not in self . outBoxes : self . outBoxes [ rid ] = deque ( ) self . outBoxes [ rid ] . append ( msg )
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_enode_bind_type ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) fcoe_get_interface = ET . Element ( "fcoe_get_interface" ) config = fcoe_get_interface output = ET . SubElement ( fcoe_get_interface , "output" ) fcoe_intf_list = ET . SubElement ( output , "fcoe-intf-list" ) fcoe_intf_fcoe_port_id_key = ET . SubElement ( fcoe_intf_list , "fcoe-intf-f...
def get_workflow ( self ) : """Returns the instantiated workflow class ."""
extra_context = self . get_initial ( ) entry_point = self . request . GET . get ( "step" , None ) workflow = self . workflow_class ( self . request , context_seed = extra_context , entry_point = entry_point ) return workflow
def get_base_attributes ( entity ) : """Build a dict of attributes of an entity . Returns attributes and their values , ignoring any properties , functions and anything that starts with an underscore ."""
attributes = { } cls = entity . __class__ for attr , _ in inspect . getmembers ( cls , lambda o : not isinstance ( o , property ) and not inspect . isroutine ( o ) ) : if not attr . startswith ( "_" ) : attributes [ attr ] = getattr ( entity , attr ) return attributes
def add ( class_ , name , value , sep = ';' ) : """Add a value to a delimited variable , but only when the value isn ' t already present ."""
values = class_ . get_values_list ( name , sep ) if value in values : return new_value = sep . join ( values + [ value ] ) winreg . SetValueEx ( class_ . key , name , 0 , winreg . REG_EXPAND_SZ , new_value ) class_ . notify ( )
def from_template ( cls , data , template ) : """Create a table from a predefined datatype . See the ` ` templates _ avail ` ` property for available names . Parameters data Data in a format that the ` ` _ _ init _ _ ` ` understands . template : str or dict Name of the dtype template to use from ` ` kp ...
name = DEFAULT_NAME if isinstance ( template , str ) : name = template table_info = TEMPLATES [ name ] else : table_info = template if 'name' in table_info : name = table_info [ 'name' ] dt = table_info [ 'dtype' ] loc = table_info [ 'h5loc' ] split = table_info [ 'split_h5' ] h5singleton = table_info [...
def _discoverAndVerify ( self , claimed_id , to_match_endpoints ) : """Given an endpoint object created from the information in an OpenID response , perform discovery and verify the discovery results , returning the matching endpoint that is the result of doing that discovery . @ type to _ match : openid . ...
logging . info ( 'Performing discovery on %s' % ( claimed_id , ) ) _ , services = self . _discover ( claimed_id ) if not services : raise DiscoveryFailure ( 'No OpenID information found at %s' % ( claimed_id , ) , None ) return self . _verifyDiscoveredServices ( claimed_id , services , to_match_endpoints )
def from_requirement ( cls , provider , requirement , parent ) : """Build an instance from a requirement ."""
candidates = provider . find_matches ( requirement ) if not candidates : raise NoVersionsAvailable ( requirement , parent ) return cls ( candidates = candidates , information = [ RequirementInformation ( requirement , parent ) ] , )
def _add_aliases ( self , node ) : """We delegate to this method instead of using visit _ alias ( ) to have access to line numbers and to filter imports from _ _ future _ _ ."""
assert isinstance ( node , ( ast . Import , ast . ImportFrom ) ) for name_and_alias in node . names : # Store only top - level module name ( " os . path " - > " os " ) . # We can ' t easily detect when " os . path " is used . name = name_and_alias . name . partition ( '.' ) [ 0 ] alias = name_and_alias . asname...
def to_json ( self ) : """Returns : str :"""
data = dict ( ) for key , value in self . __dict__ . items ( ) : if value : if hasattr ( value , 'to_dict' ) : data [ key ] = value . to_dict ( ) elif isinstance ( value , datetime ) : data [ key ] = value . strftime ( '%Y-%m-%d %H:%M:%S' ) else : data [ k...
def generate_hooked_command ( cmd_name , cmd_cls , hooks ) : """Returns a generated subclass of ` ` cmd _ cls ` ` that runs the pre - and post - command hooks for that command before and after the ` ` cmd _ cls . run ` ` method ."""
def run ( self , orig_run = cmd_cls . run ) : self . run_command_hooks ( 'pre_hooks' ) orig_run ( self ) self . run_command_hooks ( 'post_hooks' ) return type ( cmd_name , ( cmd_cls , object ) , { 'run' : run , 'run_command_hooks' : run_command_hooks , 'pre_hooks' : hooks . get ( 'pre' , [ ] ) , 'post_hooks...
def compute_hash_speed ( num , quiet = False ) : # type : ( int , bool ) - > float """Hash time ."""
namelist = NameList ( num ) os_fd , tmpfile_name = tempfile . mkstemp ( text = True ) schema = NameList . SCHEMA header_row = ',' . join ( [ f . identifier for f in schema . fields ] ) with open ( tmpfile_name , 'wt' ) as f : f . write ( header_row ) f . write ( '\n' ) for person in namelist . names : ...
def eat_line ( self ) : """Move current position forward until the next line ."""
if self . eos : return None eat_length = self . eat_length get_char = self . get_char has_space = self . has_space while has_space ( ) and get_char ( ) != '\n' : eat_length ( 1 ) eat_length ( 1 )
def append_text ( self , content ) : """Append text nodes into L { Content . data } @ param content : The current content being unmarshalled . @ type content : L { Content }"""
if content . node . hasText ( ) : content . text = content . node . getText ( )
def build ( mnemonic , oprnd1 , oprnd2 , oprnd3 ) : """Return the specified instruction ."""
ins = ReilInstruction ( ) ins . mnemonic = mnemonic ins . operands = [ oprnd1 , oprnd2 , oprnd3 ] return ins
def authenticate_redirect ( self , callback_uri = None , cancel_uri = None , extended_permissions = None , callback = None ) : """Perform the authentication redirect to GitHub"""
self . require_setting ( self . _CLIENT_ID_SETTING , self . _API_NAME ) scope = self . _BASE_SCOPE if extended_permissions : scope += extended_permissions args = { 'client_id' : self . settings [ self . _CLIENT_ID_SETTING ] , 'redirect_uri' : self . oauth2_redirect_uri ( callback_uri ) , 'scope' : ',' . join ( scop...
def controller_creatr ( filename ) : """Name of the controller file to be created"""
if not check ( ) : click . echo ( Fore . RED + 'ERROR: Ensure you are in a bast app to run the create:controller command' ) return path = os . path . abspath ( '.' ) + '/controller' if not os . path . exists ( path ) : os . makedirs ( path ) # if os . path . isfile ( path + ) file_name = str ( filename + '....
def send ( ch , message , ** kwargs ) : """Site : https : / / pushall . ru API : https : / / pushall . ru / blog / api Desc : App for notification to devices / browsers and messaging apps"""
params = { 'type' : kwargs . pop ( 'req_type' , 'self' ) , 'key' : settings . PUSHALL_API_KEYS [ ch ] [ 'key' ] , 'id' : settings . PUSHALL_API_KEYS [ ch ] [ 'id' ] , 'title' : kwargs . pop ( "title" , settings . PUSHALL_API_KEYS [ ch ] . get ( 'title' ) or "" ) , 'text' : message , 'priority' : kwargs . pop ( "priorit...
def setQuery ( self , query ) : """Assigns the query for this widget , loading the query builder tree with the pertinent information . : param query | < Query > | | < QueryCompound > | | None"""
tree = self . uiQueryTREE tree . blockSignals ( True ) tree . setUpdatesEnabled ( False ) tree . clear ( ) # assign a top level query item if ( Q . typecheck ( query ) and not query . isNull ( ) ) : XQueryItem ( tree , query ) # assign a top level query group elif ( QueryCompound . typecheck ( query ) and not query...
def output_sub_generic ( gandi , data , output_keys , justify = 10 ) : """Generic helper to output info from a data dict ."""
for key in output_keys : if key in data : output_sub_line ( gandi , key , data [ key ] , justify )
def lesser ( lhs , rhs ) : """Returns the result of element - wise * * lesser than * * ( < ) comparison operation with broadcasting . For each element in input arrays , return 1 ( true ) if lhs elements are less than rhs , otherwise return 0 ( false ) . Equivalent to ` ` lhs < rhs ` ` and ` ` mx . nd . broa...
# pylint : disable = no - member , protected - access return _ufunc_helper ( lhs , rhs , op . broadcast_lesser , lambda x , y : 1 if x < y else 0 , _internal . _lesser_scalar , _internal . _greater_scalar )
def fit ( self , x_train , y_train , x_valid = None , y_valid = None , epochs = 1 , batch_size = 32 , verbose = 1 , callbacks = None , shuffle = True ) : """Fit the model for a fixed number of epochs . Args : x _ train : list of training data . y _ train : list of training target ( label ) data . x _ valid ...
p = IndexTransformer ( initial_vocab = self . initial_vocab , use_char = self . use_char ) p . fit ( x_train , y_train ) embeddings = filter_embeddings ( self . embeddings , p . _word_vocab . vocab , self . word_embedding_dim ) model = BiLSTMCRF ( char_vocab_size = p . char_vocab_size , word_vocab_size = p . word_vocab...
def check_crtf ( self ) : """Checks for CRTF compatibility ."""
if self . region_type not in regions_attributes : raise ValueError ( "'{0}' is not a valid region type in this package" "supported by CRTF" . format ( self . region_type ) ) if self . coordsys not in valid_coordsys [ 'CRTF' ] : raise ValueError ( "'{0}' is not a valid coordinate reference frame in " "astropy su...
def connect_patch_namespaced_pod_proxy ( self , name , namespace , ** kwargs ) : """connect PATCH requests to proxy of Pod This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . connect _ patch _ namespaced _ pod _ p...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . connect_patch_namespaced_pod_proxy_with_http_info ( name , namespace , ** kwargs ) else : ( data ) = self . connect_patch_namespaced_pod_proxy_with_http_info ( name , namespace , ** kwargs ) return data
def _str_to_bool ( str_ ) : """Convert string to bool ( in argparse context ) ."""
if str_ . lower ( ) not in [ 'true' , 'false' , 'none' ] : raise ValueError ( 'Need bool; got %r' % str_ ) return { 'true' : True , 'false' : False , 'none' : None } [ str_ . lower ( ) ]
def release ( self ) : """Release the lock ."""
success , _ = self . etcd_client . transaction ( compare = [ self . etcd_client . transactions . value ( self . key ) == self . uuid ] , success = [ self . etcd_client . transactions . delete ( self . key ) ] , failure = [ ] ) return success
def pull ( self ) : """Enable or disable internal pull - up resistors for this pin . A value of digitalio . Pull . UP will enable a pull - up resistor , and None will disable it . Pull - down resistors are NOT supported !"""
if _get_bit ( self . _mcp . gppu , self . _pin ) : return digitalio . Pull . UP return None
def guess_file_name_stream_type_header ( args ) : """Guess filename , file stream , file type , file header from args . : param args : may be string ( filepath ) , 2 - tuples ( filename , fileobj ) , 3 - tuples ( filename , fileobj , contentype ) or 4 - tuples ( filename , fileobj , contentype , custom _ header...
ftype = None fheader = None if isinstance ( args , ( tuple , list ) ) : if len ( args ) == 2 : fname , fstream = args elif len ( args ) == 3 : fname , fstream , ftype = args else : fname , fstream , ftype , fheader = args else : fname , fstream = guess_filename_stream ( args ) ...
async def on_isupport_maxbans ( self , value ) : """Maximum entries in ban list . Replaced by MAXLIST ."""
if 'MAXLIST' not in self . _isupport : if not self . _list_limits : self . _list_limits = { } self . _list_limits [ 'b' ] = int ( value )
def orifice_expansibility_1989 ( D , Do , P1 , P2 , k ) : r'''Calculates the expansibility factor for orifice plate calculations based on the geometry of the plate , measured pressures of the orifice , and the isentropic exponent of the fluid . . . math : : \ epsilon = 1 - ( 0.41 + 0.35 \ beta ^ 4 ) \ Delta...
return 1.0 - ( 0.41 + 0.35 * ( Do / D ) ** 4 ) * ( P1 - P2 ) / ( k * P1 )
def _apply_post_render_hooks ( self , data , obj , fmt ) : """Apply the post - render hooks to the data ."""
hooks = self . post_render_hooks . get ( fmt , [ ] ) for hook in hooks : try : data = hook ( data , obj ) except Exception as e : self . param . warning ( "The post_render_hook %r could not " "be applied:\n\n %s" % ( hook , e ) ) return data
def create_app ( ) : """Flask application factory"""
# Create Flask app load app . config app = Flask ( __name__ ) app . config . from_object ( __name__ + '.ConfigClass' ) # Initialize Flask - BabelEx babel = Babel ( app ) # Initialize Flask - SQLAlchemy db = SQLAlchemy ( app ) # Define the User data - model . # NB : Make sure to add flask _ user UserMixin ! ! ! class Us...
def drive ( self ) : """Get wrapper to the drive containing this device ."""
if self . is_drive : return self cleartext = self . luks_cleartext_slave if cleartext : return cleartext . drive if self . is_block : return self . _daemon [ self . _P . Block . Drive ] return None
def decint ( n , signed = False ) : # pylint : disable = invalid - name , too - many - branches """Decode an unsigned / signed integer ."""
if isinstance ( n , str ) : n = utils . to_string ( n ) if n is True : return 1 if n is False : return 0 if n is None : return 0 if is_numeric ( n ) : if signed : if not - TT255 <= n <= TT255 - 1 : raise EncodingError ( 'Number out of range: %r' % n ) else : if not 0 ...
def search ( self , resource , resource_class , search_filter = None , dmql_query = None , limit = 9999999 , offset = 0 , optional_parameters = None , auto_offset = True , query_type = 'DMQL2' , standard_names = 0 , response_format = 'COMPACT-DECODED' ) : """Preform a search on the RETS board : param resource : T...
if ( search_filter and dmql_query ) or ( not search_filter and not dmql_query ) : raise ValueError ( "You may specify either a search_filter or dmql_query" ) search_helper = DMQLHelper ( ) if dmql_query : dmql_query = search_helper . dmql ( query = dmql_query ) else : dmql_query = search_helper . filter_to_...
def histogram ( a , bins = 10 , range = None ) : """Compute the histogram of the input data . Parameters a : NDArray Input data . The histogram is computed over the flattened array . bins : int or sequence of scalars If bins is an int , it defines the number of equal - width bins in the given range ( 10...
# pylint : disable = no - member , protected - access if isinstance ( bins , NDArray ) : return _internal . _histogram ( data = a , bins = bins ) elif isinstance ( bins , integer_types ) : if range is None : warnings . warn ( "range is not specified, using numpy's result " "to ensure consistency with nu...
def copy_from ( self , g ) : """Copy all nodes and edges from the given graph into this . Return myself ."""
renamed = { } for k , v in g . node . items ( ) : ok = k if k in self . place : n = 0 while k in self . place : k = ok + ( n , ) if isinstance ( ok , tuple ) else ( ok , n ) n += 1 renamed [ ok ] = k self . place [ k ] = v if type ( g ) is nx . MultiDiGraph : ...
def get_endpoint_by_endpoint_id ( self , endpoint_id ) : """Get an endpoint by endpoint id"""
self . _validate_uuid ( endpoint_id ) url = "/notification/v1/endpoint/{}" . format ( endpoint_id ) response = NWS_DAO ( ) . getURL ( url , self . _read_headers ) if response . status != 200 : raise DataFailureException ( url , response . status , response . data ) data = json . loads ( response . data ) return sel...
def readme ( ) : """Try converting the README to an RST document . Return it as is on failure ."""
try : import pypandoc readme_content = pypandoc . convert ( 'README.md' , 'rst' ) except ( IOError , ImportError ) : print ( "Warning: no pypandoc module found." ) try : readme_content = open ( 'README.md' ) . read ( ) except IOError : readme_content = '' return readme_content
def convert_nexson_format ( blob , out_nexson_format , current_format = None , remove_old_structs = True , pristine_if_invalid = False , sort_arbitrary = False ) : """Take a dict form of NexSON and converts its datastructures to those needed to serialize as out _ nexson _ format . If current _ format is not spe...
if not current_format : current_format = detect_nexson_version ( blob ) out_nexson_format = resolve_nexson_format ( out_nexson_format ) if current_format == out_nexson_format : if sort_arbitrary : sort_arbitrarily_ordered_nexson ( blob ) return blob two2zero = _is_by_id_hbf ( out_nexson_format ) and...
def lower_brkpts ( a , b , c , e , f , p_min , p_max , n ) : """lower _ brkpts : lower approximation of the cost function Parameters : - a , . . . , p _ max : cost parameters - n : number of breakpoints ' intervals to insert between valve points Returns : list of breakpoints in the form [ ( x0 , y0 ) , . . ...
EPS = 1.e-12 # for avoiding round - off errors if f == 0 : f = math . pi / ( p_max - p_min ) brk = [ ] nvalve = int ( math . ceil ( f * ( p_max - p_min ) / math . pi ) ) for i in range ( nvalve + 1 ) : p0 = p_min + i * math . pi / f if p0 >= p_max - EPS : brk . append ( ( p_max , cost ( a , b , c , ...
def emit_pdf ( outputs , options ) : '''Runs the PDF conversion command to generate the PDF .'''
cmd = options . pdf_cmd cmd = cmd . replace ( '%o' , options . pdfname ) if len ( outputs ) > 2 : cmd_print = cmd . replace ( '%i' , ' ' . join ( outputs [ : 2 ] + [ '...' ] ) ) else : cmd_print = cmd . replace ( '%i' , ' ' . join ( outputs ) ) cmd = cmd . replace ( '%i' , ' ' . join ( outputs ) ) if not option...
def _schmidt_count ( cos_dist , sigma = None ) : """Schmidt ( a . k . a . 1 % ) counting kernel function ."""
radius = 0.01 count = ( ( 1 - cos_dist ) <= radius ) . astype ( float ) # To offset the count . sum ( ) - 0.5 required for the kamb methods . . . count = 0.5 / count . size + count return count , ( cos_dist . size * radius )
def estimateKronCovariances ( phenos , K1r = None , K1c = None , K2r = None , K2c = None , covs = None , Acovs = None , covar_type = 'lowrank_diag' , rank = 1 ) : """estimates the background covariance model before testing Args : phenos : [ N x P ] SP . array of P phenotypes for N individuals K1r : [ N x N ] ...
print ( ".. Training the backgrond covariance with a GP model" ) vc = VAR . CVarianceDecomposition ( phenos ) if K1r is not None : vc . addRandomEffect ( K1r , covar_type = covar_type , rank = rank ) if K2r is not None : # TODO : fix this ; forces second term to be the noise covariance vc . addRandomEffect ( is...
def get_all_connected_devices ( self ) : """Get all info about devices connected to the box : return : a list with each device info : rtype : list"""
self . bbox_auth . set_access ( BboxConstant . AUTHENTICATION_LEVEL_PUBLIC , BboxConstant . AUTHENTICATION_LEVEL_PRIVATE ) self . bbox_url . set_api_name ( BboxConstant . API_HOSTS , None ) api = BboxApiCall ( self . bbox_url , BboxConstant . HTTP_METHOD_GET , None , self . bbox_auth ) resp = api . execute_api_request ...
def ChangeScaleFactor ( self , newfactor ) : """Changes the zoom of the graph manually . 1.0 is the original canvas size . Args : # float value between 0.0 and 5.0 newfactor : 0.7"""
if float ( newfactor ) > 0 and float ( newfactor ) < self . _MAX_ZOOM : self . _zoomfactor = newfactor
def filter ( self , fn , skip_na = True , seed = None ) : """Filter this SArray by a function . Returns a new SArray filtered by this SArray . If ` fn ` evaluates an element to true , this element is copied to the new SArray . If not , it isn ' t . Throws an exception if the return type of ` fn ` is not casta...
assert callable ( fn ) , "Input must be callable" if seed is None : seed = abs ( hash ( "%0.20f" % time . time ( ) ) ) % ( 2 ** 31 ) with cython_context ( ) : return SArray ( _proxy = self . __proxy__ . filter ( fn , skip_na , seed ) )
def connect_to_pipe ( pipe_name ) : """Connect to a new pipe in message mode ."""
pipe_handle = windll . kernel32 . CreateFileW ( pipe_name , DWORD ( GENERIC_READ | GENERIC_WRITE | FILE_WRITE_ATTRIBUTES ) , DWORD ( 0 ) , # No sharing . None , # Default security attributes . DWORD ( OPEN_EXISTING ) , # dwCreationDisposition . FILE_FLAG_OVERLAPPED , # dwFlagsAndAttributes . None # hTemplateFile , ) if...
def _operator_generator ( index , conj ) : """Internal method to generate the appropriate operator"""
pterm = PauliTerm ( 'I' , 0 , 1.0 ) Zstring = PauliTerm ( 'I' , 0 , 1.0 ) for j in range ( index ) : Zstring = Zstring * PauliTerm ( 'Z' , j , 1.0 ) pterm1 = Zstring * PauliTerm ( 'X' , index , 0.5 ) scalar = 0.5 * conj * 1.0j pterm2 = Zstring * PauliTerm ( 'Y' , index , scalar ) pterm = pterm * ( pterm1 + pterm2 )...
def find_rmlst_type ( kma_report , rmlst_report ) : """Uses a report generated by KMA to determine what allele is present for each rMLST gene . : param kma _ report : The . res report generated by KMA . : param rmlst _ report : rMLST report file to write information to . : return : a sorted list of loci prese...
genes_to_use = dict ( ) score_dict = dict ( ) gene_alleles = list ( ) with open ( kma_report ) as tsvfile : reader = csv . DictReader ( tsvfile , delimiter = '\t' ) for row in reader : gene_allele = row [ '#Template' ] score = int ( row [ 'Score' ] ) gene = gene_allele . split ( '_' ) [ ...
def write_data ( self , data , file_datetime ) : """Write data to the ndata file specified by reference . : param data : the numpy array data to write : param file _ datetime : the datetime for the file"""
with self . __lock : assert data is not None absolute_file_path = self . __file_path # logging . debug ( " WRITE data file % s for % s " , absolute _ file _ path , key ) make_directory_if_needed ( os . path . dirname ( absolute_file_path ) ) properties = self . read_properties ( ) if os . path . exi...
def decode ( self , codes ) : """Given PQ - codes , reconstruct original D - dimensional vectors approximately by fetching the codewords . Args : codes ( np . ndarray ) : PQ - cdoes with shape = ( N , M ) and dtype = self . code _ dtype . Each row is a PQ - code Returns : np . ndarray : Reconstructed ve...
assert codes . ndim == 2 N , M = codes . shape assert M == self . M assert codes . dtype == self . code_dtype vecs = np . empty ( ( N , self . Ds * self . M ) , dtype = np . float32 ) for m in range ( self . M ) : vecs [ : , m * self . Ds : ( m + 1 ) * self . Ds ] = self . codewords [ m ] [ codes [ : , m ] , : ] re...
def ast_from_module_name ( self , modname , context_file = None ) : """given a module name , return the astroid object"""
if modname in self . astroid_cache : return self . astroid_cache [ modname ] if modname == "__main__" : return self . _build_stub_module ( modname ) old_cwd = os . getcwd ( ) if context_file : os . chdir ( os . path . dirname ( context_file ) ) try : found_spec = self . file_from_module_name ( modname ,...
def _validate_query ( query ) : """Validate and clean up a query to be sent to Search . Cleans the query string , removes unneeded parameters , and validates for correctness . Does not modify the original argument . Raises an Exception on invalid input . Arguments : query ( dict ) : The query to validate ...
query = deepcopy ( query ) # q is always required if query [ "q" ] == BLANK_QUERY [ "q" ] : raise ValueError ( "No query specified." ) query [ "q" ] = _clean_query_string ( query [ "q" ] ) # limit should be set to appropriate default if not specified if query [ "limit" ] is None : query [ "limit" ] = SEARCH_LIM...
def serialized ( self , sep = os . linesep ) : """Return serialized url check data as unicode string ."""
return unicode_safe ( sep ) . join ( [ u"%s link" % self . scheme , u"base_url=%r" % self . base_url , u"parent_url=%r" % self . parent_url , u"base_ref=%r" % self . base_ref , u"recursion_level=%d" % self . recursion_level , u"url_connection=%s" % self . url_connection , u"line=%d" % self . line , u"column=%d" % self ...
def FindUniqueId ( dic ) : """Return a string not used as a key in the dictionary dic"""
name = str ( len ( dic ) ) while name in dic : # Use bigger numbers so it is obvious when an id is picked randomly . name = str ( random . randint ( 1000000 , 999999999 ) ) return name
def add_service ( self , service ) : """Add a service description . Handles transition from self . service = None , self . service = dict for a single service , and then self . service = [ dict , dict , . . . ] for multiple"""
if ( self . service is None ) : self . service = service elif ( isinstance ( self . service , dict ) ) : self . service = [ self . service , service ] else : self . service . append ( service )
def _central_crop ( image , crop_height , crop_width ) : """Performs central crops of the given image list . Args : image : a 3 - D image tensor crop _ height : the height of the image following the crop . crop _ width : the width of the image following the crop . Returns : 3 - D tensor with cropped ima...
shape = tf . shape ( image ) height , width = shape [ 0 ] , shape [ 1 ] mlperf_log . resnet_print ( key = mlperf_log . INPUT_CENTRAL_CROP , value = [ crop_height , crop_width ] ) amount_to_be_cropped_h = ( height - crop_height ) crop_top = amount_to_be_cropped_h // 2 amount_to_be_cropped_w = ( width - crop_width ) crop...
def CrearLiquidacion ( self , nro_orden = None , cuit_comprador = None , nro_act_comprador = None , nro_ing_bruto_comprador = None , cod_tipo_operacion = None , es_liquidacion_propia = None , es_canje = None , cod_puerto = None , des_puerto_localidad = None , cod_grano = None , cuit_vendedor = None , nro_ing_bruto_vend...
# limpio los campos especiales ( segun validaciones de AFIP ) if alic_iva_operacion == 0 : alic_iva_operacion = None # no informar alicuota p / monotributo if val_grado_ent == 0 : val_grado_ent = None # borrando datos corredor si no corresponden if actua_corredor == "N" : cuit_corredor = None comisi...
def execute_xpath ( xpath_string , sql_function , uuid , version ) : """Executes either xpath or xpath - module SQL function with given input params ."""
settings = get_current_registry ( ) . settings with db_connect ( ) as db_connection : with db_connection . cursor ( ) as cursor : try : cursor . execute ( SQL [ sql_function ] , { 'document_uuid' : uuid , 'document_version' : version , 'xpath_string' : xpath_string } ) except psycopg2 . ...
def _process_key ( evt ) : """Helper to convert from wx keycode to vispy keycode"""
key = evt . GetKeyCode ( ) if key in KEYMAP : return KEYMAP [ key ] , '' if 97 <= key <= 122 : key -= 32 if key >= 32 and key <= 127 : return keys . Key ( chr ( key ) ) , chr ( key ) else : return None , None
def from_headers ( strheader ) : """Parse cookie data from a string in HTTP header ( RFC 2616 ) format . @ return : list of cookies @ raises : ValueError for incomplete or invalid data"""
res = [ ] fp = StringIO ( strheader ) headers = httplib . HTTPMessage ( fp , seekable = True ) if "Host" not in headers : raise ValueError ( "Required header 'Host:' missing" ) host = headers [ "Host" ] path = headers . get ( "Path" , "/" ) for header in headers . getallmatchingheaders ( "Set-Cookie" ) : header...
def save ( self , running = None ) : """save or update this cached gear into the Ariane server cache : param running : the new running value . if None ignored : return :"""
LOGGER . debug ( "InjectorCachedGear.save" ) ret = True if running is not None : self . running = running if self . service is None : self . service = InjectorCachedGearService . make_admin_on_demand_service ( self ) if self . service is not None and not self . service . is_started : self . service . start ...
def convert_to_base ( num : int , base : int ) -> str : """Convert an integer number to a certain base system and return it as a string . The base must be less than or equal to 10. Examples : > > > convert _ to _ base ( 8 , 3) '22' > > > convert _ to _ base ( 8 , 2) '1000' > > > convert _ to _ base ( ...
if num == 0 : return '0' digits = [ ] while num : digits . append ( str ( num % base ) ) num //= base digits . reverse ( ) return '' . join ( digits )