signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def compute ( self , activeColumns , basalInput , apicalInput = ( ) , basalGrowthCandidates = None , apicalGrowthCandidates = None , learn = True ) : """Perform one timestep . Use the basal and apical input to form a set of predictions , then activate the specified columns , then learn . @ param activeColumns (...
activeColumns = np . asarray ( activeColumns ) basalInput = np . asarray ( basalInput ) apicalInput = np . asarray ( apicalInput ) if basalGrowthCandidates is None : basalGrowthCandidates = basalInput basalGrowthCandidates = np . asarray ( basalGrowthCandidates ) if apicalGrowthCandidates is None : apicalGrowth...
def __init_keystone_session_v3 ( self , check = False ) : """Return a new session object , created using Keystone API v3. . . note : : Note that the only supported authN method is password authentication ; token or other plug - ins are not currently supported ."""
try : # may fail on Python 2.6? from keystoneauth1 . identity import v3 as keystone_v3 except ImportError : log . warning ( "Cannot load Keystone API v3 library." ) return None auth = keystone_v3 . Password ( auth_url = self . _os_auth_url , username = self . _os_username , password = self . _os_password , ...
def correctness_and_confidence ( sess , model , x , y , batch_size = None , devices = None , feed = None , attack = None , attack_params = None ) : """Report whether the model is correct and its confidence on each example in a dataset . : param sess : tf . Session : param model : cleverhans . model . Model ...
_check_x ( x ) _check_y ( y ) if x . shape [ 0 ] != y . shape [ 0 ] : raise ValueError ( "Number of input examples and labels do not match." ) factory = _CorrectAndProbFactory ( model , attack , attack_params ) out = batch_eval_multi_worker ( sess , factory , [ x , y ] , batch_size = batch_size , devices = devices ...
def subscribe_to_events ( config , subscriber , events , model = None ) : """Helper function to subscribe to group of events . : param config : Pyramid contig instance . : param subscriber : Event subscriber function . : param events : Sequence of events to subscribe to . : param model : Model predicate val...
kwargs = { } if model is not None : kwargs [ 'model' ] = model for evt in events : config . add_subscriber ( subscriber , evt , ** kwargs )
def _Sublimation_Pressure ( T ) : """Sublimation Pressure correlation Parameters T : float Temperature , [ K ] Returns P : float Pressure at sublimation line , [ MPa ] Notes Raise : class : ` NotImplementedError ` if input isn ' t in limit : * 50 ≤ T ≤ 273.16 Examples > > > _ Sublimation _ Pre...
if 50 <= T <= 273.16 : Tita = T / Tt suma = 0 a = [ - 0.212144006e2 , 0.273203819e2 , - 0.61059813e1 ] expo = [ 0.333333333e-2 , 1.20666667 , 1.70333333 ] for ai , expi in zip ( a , expo ) : suma += ai * Tita ** expi return exp ( suma / Tita ) * Pt else : raise NotImplementedError ( ...
def takef ( d , l , val = None ) : '''take ( f ) a list of keys and fill in others with val'''
return { i : ( d [ i ] if i in d else val ) for i in l } ;
def object_to_json ( obj ) : """Convert object that cannot be natively serialized by python to JSON representation ."""
if isinstance ( obj , ( datetime . datetime , datetime . date , datetime . time ) ) : return obj . isoformat ( ) return str ( obj )
def import_source ( self , CachableSource ) : """Updates cache area and returns number of items updated with all available entries in ICachableSource"""
_count = 0 for item in CachableSource . items ( ) : if self . cache ( item ) : _count += 1 return _count
def _zoom ( scale : uniform = 1.0 , row_pct : uniform = 0.5 , col_pct : uniform = 0.5 ) : "Zoom image by ` scale ` . ` row _ pct ` , ` col _ pct ` select focal point of zoom ."
s = 1 - 1 / scale col_c = s * ( 2 * col_pct - 1 ) row_c = s * ( 2 * row_pct - 1 ) return _get_zoom_mat ( 1 / scale , 1 / scale , col_c , row_c )
def launch ( self , tunnelPorts = None ) : """Launch every worker assigned on this host ."""
if self . isLocal ( ) : # Launching local workers c = self . _getWorkerCommandList ( ) self . subprocesses . append ( subprocess . Popen ( c ) ) else : # Launching remotely BASE_SSH [ 0 ] = self . ssh_executable sshCmd = BASE_SSH if not self . rsh else BASE_RSH if tunnelPorts is not None : s...
def direct_messages_new ( self , text , user_id = None , screen_name = None ) : """Sends a new direct message to the given user from the authenticating user . https : / / dev . twitter . com / docs / api / 1.1 / post / direct _ messages / new : param str text : ( * required * ) The text of your direct messa...
params = { } set_str_param ( params , 'text' , text ) set_str_param ( params , 'user_id' , user_id ) set_str_param ( params , 'screen_name' , screen_name ) return self . _post_api ( 'direct_messages/new.json' , params )
def skip_tree_node ( self , tree_node , tx_context = None ) : """method skips the node and all its dependants and child nodes"""
if not tx_context : # create transaction context if one was not provided # format : { process _ name : { timeperiod : AbstractTreeNode } } tx_context = collections . defaultdict ( dict ) if tree_node . timeperiod in tx_context [ tree_node . process_name ] : # the node has already been marked for skipping return...
def is_member ( self , group_distinguishedname ) : """For the current ADUser instance , determine if the user is a member of a specific group ( the group DN is used ) . The result may not be accurate if explicit _ membership _ only was set to True when the object factory method ( user ( ) or users ( ) ) was ...
# pylint : disable = no - member if group_distinguishedname . lower ( ) in [ dn . lower ( ) for dn in self . memberof ] : # pylint : enable = no - member return True else : return False
def write ( self , data , msg_type , ** options ) : '''Serializes and pushes single data object to a wrapped stream . : Parameters : - ` data ` - data to be serialized - ` msg _ type ` ( one of the constants defined in : class : ` . MessageType ` ) - type of the message : Options : - ` single _ char _ s...
self . _buffer = BytesIO ( ) self . _options = MetaData ( ** CONVERSION_OPTIONS . union_dict ( ** options ) ) # header and placeholder for message size self . _buffer . write ( ( '%s%s\0\0\0\0\0\0' % ( ENDIANESS , chr ( msg_type ) ) ) . encode ( self . _encoding ) ) self . _write ( data ) # update message size data_siz...
def closed ( self , user ) : """Moved to CLOSED and not later moved to ASSIGNED"""
decision = False for record in self . history : # Completely ignore older changes if record [ "when" ] < self . options . since . date : continue # Look for status change to CLOSED ( unless already found ) if not decision and record [ "when" ] < self . options . until . date : for change in ...
def tabular ( client , datasets ) : """Format datasets with a tabular output ."""
from renku . models . _tabulate import tabulate click . echo ( tabulate ( datasets , headers = OrderedDict ( ( ( 'short_id' , 'id' ) , ( 'name' , None ) , ( 'created' , None ) , ( 'authors_csv' , 'authors' ) , ) ) , ) )
def default_triple ( cls , inner_as_primary = True , inner_as_overcontact = False , starA = 'starA' , starB = 'starB' , starC = 'starC' , inner = 'inner' , outer = 'outer' , contact_envelope = 'contact_envelope' ) : """Load a bundle with a default triple system . Set inner _ as _ primary based on what hierarchica...
if not conf . devel : raise NotImplementedError ( "'default_triple' not officially supported for this release. Enable developer mode to test." ) b = cls ( ) b . add_star ( component = starA ) b . add_star ( component = starB ) b . add_star ( component = starC ) b . add_orbit ( component = inner , period = 1 ) b . ...
def mongodb_drop_collection ( database_name , collection_name ) : """Drop Collection"""
try : mongodb_client_url = getattr ( settings , 'MONGODB_CLIENT' , 'mongodb://localhost:27017/' ) mc = MongoClient ( mongodb_client_url , document_class = OrderedDict ) dbs = mc [ database_name ] dbs . drop_collection ( collection_name ) # print " success " return "" except : # error connecting ...
def resources_with_possible_perms ( cls , instance , resource_ids = None , resource_types = None , db_session = None ) : """returns list of permissions and resources for this user : param instance : : param resource _ ids : restricts the search to specific resources : param resource _ types : restricts the se...
perms = resource_permissions_for_users ( cls . models_proxy , ANY_PERMISSION , resource_ids = resource_ids , resource_types = resource_types , user_ids = [ instance . id ] , db_session = db_session , ) for resource in instance . resources : perms . append ( PermissionTuple ( instance , ALL_PERMISSIONS , "user" , No...
def measure ( self , vid ) : """Return a measure , given its vid or another reference"""
from ambry . orm import Column if isinstance ( vid , PartitionColumn ) : return vid elif isinstance ( vid , Column ) : return PartitionColumn ( vid ) else : return PartitionColumn ( self . table . column ( vid ) , self )
def make_digest_acl ( username , password , read = False , write = False , create = False , delete = False , admin = False , allperms = False ) : '''Generate acl object . . note : : This is heavily used in the zookeeper state and probably is not useful as a cli module username username of acl password pla...
return kazoo . security . make_digest_acl ( username , password , read , write , create , delete , admin , allperms )
def on_cache_changed ( self , direct , which = None ) : """A callback funtion , which sets local flags when the elements of some cached inputs change this function gets ' hooked up ' to the inputs when we cache them , and upon their elements being changed we update here ."""
for what in [ direct , which ] : ind_id = self . id ( what ) _ , cache_ids = self . cached_input_ids . get ( ind_id , [ None , [ ] ] ) for cache_id in cache_ids : self . inputs_changed [ cache_id ] = True
def stochastic_event_set ( sources , source_site_filter = nofilter ) : """Generates a ' Stochastic Event Set ' ( that is a collection of earthquake ruptures ) representing a possible * realization * of the seismicity as described by a source model . The calculator loops over sources . For each source , it loo...
for source , s_sites in source_site_filter ( sources ) : try : for rupture in source . iter_ruptures ( ) : [ n_occ ] = rupture . sample_number_of_occurrences ( ) for _ in range ( n_occ ) : yield rupture except Exception as err : etype , err , tb = sys . ex...
def anchor ( self ) : """int or str indicating element under which to insert this subtotal . An int anchor is the id of the dimension element ( category or subvariable ) under which to place this subtotal . The return value can also be one of ' top ' or ' bottom ' . The return value defaults to ' bottom ' f...
anchor = self . _subtotal_dict [ "anchor" ] try : anchor = int ( anchor ) if anchor not in self . valid_elements . element_ids : return "bottom" return anchor except ( TypeError , ValueError ) : return anchor . lower ( )
def update_frontend ( self , info ) : """Updates frontend with info from the log : param info : dict - Information from a line in the log . i . e regular line , new step ."""
headers = { 'Content-Type' : 'text/event-stream' } if info . get ( 'when' ) : info [ 'when' ] = info [ 'when' ] . isoformat ( ) requests . post ( self . base_url + '/publish' , data = json . dumps ( info ) , headers = headers )
def parse_value_namedobject ( self , tup_tree ) : """< ! ELEMENT VALUE . NAMEDOBJECT ( CLASS | ( INSTANCENAME , INSTANCE ) ) >"""
self . check_node ( tup_tree , 'VALUE.NAMEDOBJECT' ) k = kids ( tup_tree ) len_k = len ( k ) if len_k == 2 : inst_path = self . parse_instancename ( k [ 0 ] ) _object = self . parse_instance ( k [ 1 ] ) _object . path = inst_path return ( name ( tup_tree ) , attrs ( tup_tree ) , _object ) if len_k == 1 ...
def stylus ( input , output , ** kw ) : """Process Stylus ( . styl ) files"""
stdin = open ( input , 'r' ) stdout = open ( output , 'w' ) cmd = '%s --include %s' % ( current_app . config . get ( 'STYLUS_BIN' ) , os . path . abspath ( os . path . dirname ( input ) ) ) subprocess . call ( cmd , shell = True , stdin = stdin , stdout = stdout )
def make_value_from_env ( self , param , value_type , function ) : """get environment variable"""
value = os . getenv ( param ) if value is None : self . notify_user ( "Environment variable `%s` undefined" % param ) return self . value_convert ( value , value_type )
def dataReceived ( self , data ) : """Takes " data " which we assume is json encoded If data has a subject _ id attribute , we pass that to the dispatcher as the subject _ id so it will get carried through into any return communications and be identifiable to the client falls back to just passing the messag...
try : address = self . guid data = json . loads ( data ) threads . deferToThread ( send_signal , self . dispatcher , data ) if 'hx_subscribe' in data : return self . dispatcher . subscribe ( self . transport , data ) if 'address' in data : address = data [ 'address' ] else : ...
def app_reverse ( viewname , urlconf = None , args = None , kwargs = None , * vargs , ** vkwargs ) : """Reverse URLs from application contents Works almost like Django ' s own reverse ( ) method except that it resolves URLs from application contents . The second argument , ` ` urlconf ` ` , has to correspond ...
# First parameter might be a request instead of an urlconf path , so # we ' ll try to be helpful and extract the current urlconf from it extra_context = getattr ( urlconf , '_feincms_extra_context' , { } ) appconfig = extra_context . get ( 'app_config' , { } ) urlconf = appconfig . get ( 'urlconf_path' , urlconf ) appc...
def newick ( args ) : """% prog newick idslist Query a list of IDs to retrieve phylogeny ."""
p = OptionParser ( newick . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) idsfile , = args mylist = [ x . strip ( ) for x in open ( idsfile ) if x . strip ( ) ] print ( get_taxids ( mylist ) ) t = TaxIDTree ( mylist ) print ( t )
def vm_disk_snapshot_delete ( name , kwargs = None , call = None ) : '''Deletes a disk snapshot based on the given VM and the disk _ id . . . versionadded : : 2016.3.0 name The name of the VM containing the snapshot to delete . disk _ id The ID of the disk to save . snapshot _ id The ID of the snapsho...
if call != 'action' : raise SaltCloudSystemExit ( 'The vm_disk_snapshot_delete action must be called with -a or --action.' ) if kwargs is None : kwargs = { } disk_id = kwargs . get ( 'disk_id' , None ) snapshot_id = kwargs . get ( 'snapshot_id' , None ) if disk_id is None or snapshot_id is None : raise Salt...
def getStartNodes ( fdefs , calls ) : '''Return a list of nodes in fdefs that have no inbound edges'''
s = [ ] for source in fdefs : for fn in fdefs [ source ] : inboundEdges = False for call in calls : if call . target == fn : inboundEdges = True if not inboundEdges : s . append ( fn ) return s
def modify_replication_group ( ReplicationGroupId = None , ReplicationGroupDescription = None , PrimaryClusterId = None , SnapshottingClusterId = None , AutomaticFailoverEnabled = None , CacheSecurityGroupNames = None , SecurityGroupIds = None , PreferredMaintenanceWindow = None , NotificationTopicArn = None , CachePar...
pass
def categorical_case ( pmf , fns , rand = None ) : """Returns the outputs of fns [ i ] with probability pmf [ i ] . Args : pmf : A 1 - D tensor of probabilities , the probability mass function . fns : A list of callables that return tensors , same length as pmf . rand : An optional scalar between 0.0 and 1....
rand = tf . random_uniform ( [ ] ) if rand is None else rand cmf = tf . pad ( tf . cumsum ( pmf ) , [ ( 1 , 0 ) ] ) cmf = [ cmf [ i ] for i in range ( len ( fns ) + 1 ) ] preds = [ ( rand >= a ) & ( rand < b ) for a , b in zip ( cmf [ : - 1 ] , cmf [ 1 : ] ) ] return tf . case ( list ( zip ( preds , fns ) ) , exclusive...
def write ( self , data : bytes , sync : bool = False ) -> None : """异步写入 , 通过 asyncio 的原生异步"""
if sync : self . sync_write ( data ) else : self . _transport . write ( data )
def check ( source , filename = '<string>' , report_level = docutils . utils . Reporter . INFO_LEVEL , ignore = None , debug = False ) : """Yield errors . Use lower report _ level for noisier error output . Each yielded error is a tuple of the form : ( line _ number , message ) Line numbers are indexed at 1...
# Do this at call time rather than import time to avoid unnecessarily # mutating state . register_code_directive ( ) ignore_sphinx ( ) ignore = ignore or { } try : ignore . setdefault ( 'languages' , [ ] ) . extend ( find_ignored_languages ( source ) ) except Error as error : yield ( error . line_number , '{}' ...
def attachment_form ( context , obj ) : """Renders a " upload attachment " form . The user must own ` ` attachments . add _ attachment permission ` ` to add attachments ."""
if context [ 'user' ] . has_perm ( 'attachments.add_attachment' ) : return { 'form' : AttachmentForm ( ) , 'form_url' : add_url_for_obj ( obj ) , 'next' : context . request . build_absolute_uri ( ) , } else : return { 'form' : None }
def _get_request_token ( self ) : """Fetch a request token from ` self . request _ token _ url ` ."""
params = { 'oauth_callback' : self . get_callback_url ( ) } response , content = self . client ( ) . request ( self . request_token_url , "POST" , body = urllib . urlencode ( params ) ) content = smart_unicode ( content ) if not response [ 'status' ] == '200' : raise OAuthError ( _ ( u"Invalid status code %s while ...
def cv ( params , dtrain , num_boost_round = 10 , nfold = 3 , metrics = ( ) , obj = None , feval = None , fpreproc = None , as_pandas = True , show_progress = None , show_stdv = True , seed = 0 ) : # pylint : disable = invalid - name """Cross - validation with given paramaters . Parameters params : dict Boost...
results = [ ] cvfolds = mknfold ( dtrain , nfold , params , seed , metrics , fpreproc ) for i in range ( num_boost_round ) : for fold in cvfolds : fold . update ( i , obj ) res = aggcv ( [ f . eval ( i , feval ) for f in cvfolds ] , show_stdv = show_stdv , show_progress = show_progress , as_pandas = as_...
def append ( self , signals , acquisition_info = "Python" , common_timebase = False , units = None ) : """Appends a new data group . For channel dependencies type Signals , the * samples * attribute must be a numpy . recarray Parameters signals : list | Signal | pandas . DataFrame list of * Signal * objec...
if isinstance ( signals , Signal ) : signals = [ signals ] elif isinstance ( signals , DataFrame ) : self . _append_dataframe ( signals , acquisition_info , units = units ) return version = self . version interp_mode = self . _integer_interpolation # check if the signals have a common timebase # if not inte...
def move_asset_behind ( self , asset_id , composition_id , reference_id ) : """Reorders assets in a composition by moving the specified asset behind of a reference asset . arg : asset _ id ( osid . id . Id ) : ` ` Id ` ` of the ` ` Asset ` ` arg : composition _ id ( osid . id . Id ) : ` ` Id ` ` of the ` ` Co...
if ( not isinstance ( composition_id , ABCId ) and composition_id . get_identifier_namespace ( ) != 'repository.Composition' ) : raise errors . InvalidArgument ( 'the argument is not a valid OSID Id' ) composition_map , collection = self . _get_composition_collection ( composition_id ) composition_map [ 'assetIds' ...
def generate_sbi_json ( num_pbs : int = 3 , project : str = 'sip' , programme_block : str = 'sip_demos' , pb_config : Union [ dict , List [ dict ] ] = None , workflow_config : Union [ dict , List [ dict ] ] = None , register_workflows = True ) -> str : """Return a JSON string used to configure an SBI ."""
return json . dumps ( generate_sbi_config ( num_pbs , project , programme_block , pb_config , workflow_config , register_workflows ) )
def denormalize_bboxes ( bboxes , rows , cols ) : """Denormalize a list of bounding boxes ."""
return [ denormalize_bbox ( bbox , rows , cols ) for bbox in bboxes ]
def parse_xml_dataset ( elem , handle_units ) : """Create a netCDF - like dataset from XML data ."""
points , units = zip ( * [ parse_xml_point ( p ) for p in elem . findall ( 'point' ) ] ) # Group points by the contents of each point datasets = { } for p in points : datasets . setdefault ( tuple ( p ) , [ ] ) . append ( p ) all_units = combine_dicts ( units ) return [ combine_xml_points ( d , all_units , handle_u...
def output_before_run ( self , run ) : """The method output _ before _ run ( ) prints the name of a file to terminal . It returns the name of the logfile . @ param run : a Run object"""
# output in terminal runSet = run . runSet try : OutputHandler . print_lock . acquire ( ) try : runSet . started_runs += 1 except AttributeError : runSet . started_runs = 1 timeStr = time . strftime ( "%H:%M:%S" , time . localtime ( ) ) + " " progressIndicator = " ({0}/{1})" . form...
def log_raise ( log , err_str , err_type = RuntimeError ) : """Log an error message and raise an error . Arguments log : ` logging . Logger ` object err _ str : str Error message to be logged and raised . err _ type : ` Exception ` object Type of error to raise ."""
log . error ( err_str ) # Make sure output is flushed # ( happens automatically to ` StreamHandlers ` , but not ` FileHandlers ` ) for handle in log . handlers : handle . flush ( ) # Raise given error raise err_type ( err_str )
def is_parent ( self , id_ , parent_id ) : """Tests if an ` ` Id ` ` is a direct parent of another . arg : id ( osid . id . Id ) : the ` ` Id ` ` to query arg : parent _ id ( osid . id . Id ) : the ` ` Id ` ` of a parent return : ( boolean ) - ` ` true ` ` if this ` ` parent _ id ` ` is a parent of ` ` id ,...
return bool ( self . _rls . get_relationships_by_genus_type_for_peers ( parent_id , id_ , self . _relationship_type ) . available ( ) )
def __tableStringParser ( self , tableString ) : """Will parse and check tableString parameter for any invalid strings . Args : tableString ( str ) : Standard table string with header and decisions . Raises : ValueError : tableString is empty . ValueError : One of the header element is not unique . Valu...
error = [ ] header = [ ] decisions = [ ] if tableString . split ( ) == [ ] : error . append ( 'Table variable is empty!' ) else : tableString = tableString . split ( '\n' ) newData = [ ] for element in tableString : if element . strip ( ) : newData . append ( element ) for elemen...
def update ( self , enabled = values . unset , webhook_url = values . unset , webhook_method = values . unset ) : """Update the ExportConfigurationInstance : param bool enabled : The enabled : param unicode webhook _ url : The webhook _ url : param unicode webhook _ method : The webhook _ method : returns :...
data = values . of ( { 'Enabled' : enabled , 'WebhookUrl' : webhook_url , 'WebhookMethod' : webhook_method , } ) payload = self . _version . update ( 'POST' , self . _uri , data = data , ) return ExportConfigurationInstance ( self . _version , payload , resource_type = self . _solution [ 'resource_type' ] , )
def random ( cls , length , bit_prob = .5 ) : """Create a bit string of the given length , with the probability of each bit being set equal to bit _ prob , which defaults to . 5. Usage : # Create a random BitString of length 10 with mostly zeros . bits = BitString . random ( 10 , bit _ prob = . 1) Argumen...
assert isinstance ( length , int ) and length >= 0 assert isinstance ( bit_prob , ( int , float ) ) and 0 <= bit_prob <= 1 bits = 0 for _ in range ( length ) : bits <<= 1 bits += ( random . random ( ) < bit_prob ) return cls ( bits , length )
def model_counts_map ( self , name = None , exclude = None , use_mask = False ) : """Return the model counts map for a single source , a list of sources , or for the sum of all sources in the ROI . The exclude parameter can be used to exclude one or more components when generating the model map . Parameters...
maps = [ c . model_counts_map ( name , exclude , use_mask = use_mask ) for c in self . components ] return skymap . coadd_maps ( self . geom , maps )
def write_xml ( self ) : '''Writes a VocabularyKey Xml as per Healthvault schema . : returns : lxml . etree . Element representing a single VocabularyKey'''
key = None if self . language is not None : lang = { } lang [ '{http://www.w3.org/XML/1998/namespace}lang' ] = self . language key = etree . Element ( 'vocabulary-key' , attrib = lang ) else : key = etree . Element ( 'vocabulary-key' ) name = etree . Element ( 'name' ) name . text = self . name key . ap...
def print_boards ( hwpack = 'arduino' , verbose = False ) : """print boards from boards . txt ."""
if verbose : pp ( boards ( hwpack ) ) else : print ( '\n' . join ( board_names ( hwpack ) ) )
def possible_completions ( self , e ) : u"""List the possible completions of the text before point ."""
completions = self . _get_completions ( ) self . _display_completions ( completions ) self . finalize ( )
def _from_dict ( cls , _dict ) : """Initialize a ClassifierList object from a json dictionary ."""
args = { } if 'classifiers' in _dict : args [ 'classifiers' ] = [ Classifier . _from_dict ( x ) for x in ( _dict . get ( 'classifiers' ) ) ] else : raise ValueError ( 'Required property \'classifiers\' not present in ClassifierList JSON' ) return cls ( ** args )
def clear ( self , * objs ) : """Clear the third relationship table , but not the ModelA or ModelB"""
if objs : keys = get_objs_columns ( objs ) self . do_ ( self . model . table . delete ( self . condition & self . model . table . c [ self . model . _primary_field ] . in_ ( keys ) ) ) else : self . do_ ( self . model . table . delete ( self . condition ) )
def number_of_items ( pronac , dt ) : """This metric calculates the project number of declared number of items and compare it to projects in the same segment output : is _ outlier : True if projects number of items is not compatible to others projects in the same segment valor : absolute number of items ...
df = data . items_by_project project = df . loc [ df [ 'PRONAC' ] == pronac ] seg = project . iloc [ 0 ] [ "idSegmento" ] info = data . items_by_project_agg . to_dict ( orient = "index" ) [ seg ] mean , std = info . values ( ) threshold = mean + 1.5 * std project_items_count = project . shape [ 0 ] is_outlier = project...
def minify ( text , minifier ) : '''Minifies the source text ( if needed )'''
# there really isn ' t a good way to know if a file is already minified . # our heuristic is if source is more than 50 bytes greater of dest OR # if a hard return is found in the first 50 chars , we assume it is not minified . minified = minifier ( text ) if abs ( len ( text ) - len ( minified ) ) > 50 or '\n' in text ...
def run_wagtail_migration_before_core_34 ( apps , schema_editor ) : """Migration 34 needs migration 0040 from wagtail core and this Migration will run wagtail migration before molo core migration 34"""
db_alias = schema_editor . connection . alias emit_pre_migrate_signal ( verbosity = 2 , interactive = False , db = db_alias )
def regex ( regex ) : """Return strategy that generates strings that match given regex . Regex can be either a string or compiled regex ( through ` re . compile ( ) ` ) . You can use regex flags ( such as ` re . IGNORECASE ` , ` re . DOTALL ` or ` re . UNICODE ` ) to control generation . Flags can be passed e...
if not hasattr ( regex , 'pattern' ) : regex = re . compile ( regex ) pattern = regex . pattern flags = regex . flags codes = sre . parse ( pattern ) return _strategy ( codes , Context ( flags = flags ) ) . filter ( regex . match )
def skewvT ( self , R , romberg = False , nsigma = None , phi = 0. ) : """NAME : skewvT PURPOSE : calculate skew in vT at R by marginalizing over velocity INPUT : R - radius at which to calculate < vR > ( can be Quantity ) OPTIONAL INPUT : nsigma - number of sigma to integrate the velocities over KE...
surfmass = self . surfacemass ( R , romberg = romberg , nsigma = nsigma , use_physical = False ) vt = self . _vmomentsurfacemass ( R , 0 , 1 , romberg = romberg , nsigma = nsigma ) / surfmass vt2 = self . _vmomentsurfacemass ( R , 0 , 2 , romberg = romberg , nsigma = nsigma ) / surfmass vt3 = self . _vmomentsurfacemass...
def points_are_in_a_straight_line ( points , tolerance = 1e-7 ) : """Check whether a set of points fall on a straight line . Calculates the areas of triangles formed by triplets of the points . Returns False is any of these areas are larger than the tolerance . Args : points ( list ( np . array ) ) : list o...
a = points [ 0 ] b = points [ 1 ] for c in points [ 2 : ] : if area_of_a_triangle_in_cartesian_space ( a , b , c ) > tolerance : return False return True
def get_assets_by_provider ( self , resource_id = None ) : """Gets an ` ` AssetList ` ` from the given provider . In plenary mode , the returned list contains all known assets or an error results . Otherwise , the returned list may contain only those assets that are accessible through this session . arg : r...
return AssetList ( self . _provider_session . get_assets_by_provider ( resource_id ) , self . _config_map )
def age ( self , minimum : int = 16 , maximum : int = 66 ) -> int : """Get a random integer value . : param maximum : Maximum value of age . : param minimum : Minimum value of age . : return : Random integer . : Example : 23."""
age = self . random . randint ( minimum , maximum ) self . _store [ 'age' ] = age return age
def get_chunk ( self , ji ) : """Get a EOCubeChunk"""
return EOCubeSceneCollectionChunk ( ji = ji , df_layers = self . df_layers , chunksize = self . chunksize , variables = self . variables , qa = self . qa , qa_valid = self . qa_valid , wdir = self . wdir )
def gen_bisz ( src , dst ) : """Return a BISZ instruction ."""
return ReilBuilder . build ( ReilMnemonic . BISZ , src , ReilEmptyOperand ( ) , dst )
def available_for_protocol ( self , protocol ) : """Check if the current function can be executed from a request defining the given protocol"""
if self . protocol == ALL or protocol == ALL : return True return protocol in ensure_sequence ( self . protocol )
def set_roi ( location ) : """Send MAV _ CMD _ DO _ SET _ ROI message to point camera gimbal at a specified region of interest ( LocationGlobal ) . The vehicle may also turn to face the ROI . For more information see : http : / / copter . ardupilot . com / common - mavlink - mission - command - messages - m...
# create the MAV _ CMD _ DO _ SET _ ROI command msg = vehicle . message_factory . command_long_encode ( 0 , 0 , # target system , target component mavutil . mavlink . MAV_CMD_DO_SET_ROI , # command 0 , # confirmation 0 , 0 , 0 , 0 , # params 1-4 location . lat , location . lon , location . alt ) # send command to vehic...
def _get_pkg_ds_avail ( ) : '''Get the package information of the available packages , maintained by dselect . Note , this will be not very useful , if dselect isn ' t installed . : return :'''
avail = "/var/lib/dpkg/available" if not salt . utils . path . which ( 'dselect' ) or not os . path . exists ( avail ) : return dict ( ) # Do not update with dselect , just read what is . ret = dict ( ) pkg_mrk = "Package:" pkg_name = "package" with salt . utils . files . fopen ( avail ) as fp_ : for pkg_info i...
def create_module ( clear_target , target ) : """Creates a new template HFOS plugin module"""
if os . path . exists ( target ) : if clear_target : shutil . rmtree ( target ) else : log ( "Target exists! Use --clear to delete it first." , emitter = 'MANAGE' ) sys . exit ( 2 ) done = False info = None while not done : info = _ask_questionnaire ( ) pprint ( info ) done =...
def _calldata_fields ( fields , exclude_fields , format_ids ) : """Utility function to determine which calldata ( i . e . , FORMAT ) fields to extract ."""
if fields is None : # no fields specified by user # default to all standard fields plus all FORMAT fields in VCF header fields = config . STANDARD_CALLDATA_FIELDS + format_ids else : # fields specified by user for f in fields : # check if field is standard or defined in VCF header if ( f not in config ....
def cee_map_remap_fabric_priority_fabric_remapped_priority ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) cee_map = ET . SubElement ( config , "cee-map" , xmlns = "urn:brocade.com:mgmt:brocade-cee-map" ) name_key = ET . SubElement ( cee_map , "name" ) name_key . text = kwargs . pop ( 'name' ) remap = ET . SubElement ( cee_map , "remap" ) fabric_priority = ET . SubElement ( remap , "fabric...
def get_entrust ( self ) : """获取委托单 ( 目前返回20次调仓的结果 ) 操作数量都按1手模拟换算的 : return :"""
xq_entrust_list = self . _get_xq_history ( ) entrust_list = [ ] replace_none = lambda s : s or 0 for xq_entrusts in xq_entrust_list : status = xq_entrusts [ "status" ] # 调仓状态 if status == "pending" : status = "已报" elif status in [ "canceled" , "failed" ] : status = "废单" else : ...
def daemon ( self ) : """Return whether process is a daemon : return :"""
if self . _process : return self . _process . daemon else : return self . _pargs . get ( 'daemonic' , False )
def sodium_memcmp ( inp1 , inp2 ) : """Compare contents of two memory regions in constant time"""
ensure ( isinstance ( inp1 , bytes ) , raising = exc . TypeError ) ensure ( isinstance ( inp2 , bytes ) , raising = exc . TypeError ) ln = max ( len ( inp1 ) , len ( inp2 ) ) buf1 = ffi . new ( "char []" , ln ) buf2 = ffi . new ( "char []" , ln ) ffi . memmove ( buf1 , inp1 , len ( inp1 ) ) ffi . memmove ( buf2 , inp2 ...
def ValidateYesNoUnknown ( value , column_name = None , problems = None ) : """Validates a value " 0 " for uknown , " 1 " for yes , and " 2 " for no ."""
if IsEmpty ( value ) or IsValidYesNoUnknown ( value ) : return True else : if problems : problems . InvalidValue ( column_name , value ) return False
def _get_image ( structure , site ) : """Private convenience method for get _ nn _ info , gives lattice image from provided PeriodicSite and Structure . Image is defined as displacement from original site in structure to a given site . i . e . if structure has a site at ( - 0.1 , 1.0 , 0.3 ) , then ( 0.9 , 0 ...
original_site = structure [ NearNeighbors . _get_original_site ( structure , site ) ] image = np . around ( np . subtract ( site . frac_coords , original_site . frac_coords ) ) image = tuple ( image . astype ( int ) ) return image
def add ( self , name , priority = 3 , comment = "" , parent = "" ) : """Adds new item to the model . Name argument may contain ( ref : ) syntax , which will be stripped down as needed . : parent : should have a form " < itemref > . < subitemref . . . > " ( e . g . " 1.1 " ) . : name : Name ( with refs ) . ...
item = [ name , priority , comment , False , [ ] ] data = self . data for c in self . _split ( parent ) : data = data [ int ( c ) - 1 ] [ 4 ] data . append ( item )
def call_api ( self , url , data , files = { } , print_response = True ) : """call api with given parameters and returns its result : param url : end point : param data : post data : param files : files if needed : param print _ response : print log if required : return : status code , response"""
if type ( url ) != str : return False , "Url must be string" if type ( data ) != dict : return False , "Data must be a dict" if type ( files ) != dict : return False , "Files must be a dict" if type ( print_response ) != bool : return False , "Print_response must be boolean" url = self . HOST + url data...
def set_default_subject ( self , subject ) : """Sets the subject ' s location media URL as a link . It displays as the default subject on PFE . - * * subject * * can be a single : py : class : ` . Subject ` instance or a single subject ID . Examples : : collection . set _ default _ subject ( 1234) colle...
if not ( isinstance ( subject , Subject ) or isinstance ( subject , ( int , str , ) ) ) : raise TypeError if isinstance ( subject , Subject ) : _subject_id = subject . id else : _subject_id = str ( subject ) self . http_post ( '{}/links/default_subject' . format ( self . id ) , json = { 'default_subject' : ...
def uuids ( self , where , archiver = "" , timeout = DEFAULT_TIMEOUT ) : """Using the given where - clause , finds all UUIDs that match Arguments : [ where ] : the where clause ( e . g . ' path like " keti " ' , ' SourceName = " TED Main " ' ) [ archiver ] : if specified , this is the archiver to use . Else ,...
resp = self . query ( "select uuid where {0}" . format ( where ) , archiver , timeout ) uuids = [ ] for r in resp [ "metadata" ] : uuids . append ( r [ "uuid" ] ) return uuids
def find ( self , * args , ** kwargs ) : """Performs the same action as : meth : ` search ` but asserts a single result . : return : : raises SearchNoneFoundError : if nothing was found : raises SearchMultipleFoundError : if more than one result is found"""
result = self . search ( * args , ** kwargs ) if len ( result ) == 0 : raise SearchNoneFoundError ( "nothing found" ) elif len ( result ) > 1 : raise SearchMultipleFoundError ( "more than one result found" ) return result [ 0 ]
def edit_resource ( self , transaction , path ) : """Render a POST on an already created resource . : param path : the path of the resource : param transaction : the transaction : return : the transaction"""
resource_node = self . _parent . root [ path ] transaction . resource = resource_node # If - Match if transaction . request . if_match : if None not in transaction . request . if_match and str ( transaction . resource . etag ) not in transaction . request . if_match : transaction . response . code = defines...
def bezier_radialrange ( seg , origin , return_all_global_extrema = False ) : """returns the tuples ( d _ min , t _ min ) and ( d _ max , t _ max ) which minimize and maximize , respectively , the distance d = | self . point ( t ) - origin | . return _ all _ global _ extrema : Multiple such t _ min or t _ max v...
def _radius ( tau ) : return abs ( seg . point ( tau ) - origin ) shifted_seg_poly = seg . poly ( ) - origin r_squared = real ( shifted_seg_poly ) ** 2 + imag ( shifted_seg_poly ) ** 2 extremizers = [ 0 , 1 ] + polyroots01 ( r_squared . deriv ( ) ) extrema = [ ( _radius ( t ) , t ) for t in extremizers ] if return_...
def rootAuthority ( xri ) : """Return the root authority for an XRI . Example : : rootAuthority ( " xri : / / @ example " ) = = " xri : / / @ " @ type xri : unicode @ returntype : unicode"""
if xri . startswith ( 'xri://' ) : xri = xri [ 6 : ] authority = xri . split ( '/' , 1 ) [ 0 ] if authority [ 0 ] == '(' : # Cross - reference . # XXX : This is incorrect if someone nests cross - references so there # is another close - paren in there . Hopefully nobody does that # before we have a real xriparse fu...
def read_file ( self , path , ** kwargs ) : """Read file input into memory , returning deserialized objects : param path : Path of file to read"""
try : with open ( path , "r" ) as handle : parsed_data = yaml . safe_load ( handle ) return parsed_data except IOError : LOGGER . warning ( "Error reading file: {0}" . format ( path ) ) except TypeError : LOGGER . warning ( "Error reading file: {0}" . format ( path ) ) return None
def validate_types ( self , definition ) : """This function performs some basic sanity checks on the scalar definition : - Checks that all the required fields are available . - Checks that all the fields have the expected types . : param definition : the dictionary containing the scalar properties . : raise...
if not self . _strict_type_checks : return # The required and optional fields in a scalar type definition . REQUIRED_FIELDS = { 'bug_numbers' : list , # This contains ints . See LIST _ FIELDS _ CONTENT . 'description' : string_types , 'expires' : string_types , 'kind' : string_types , 'notification_emails' : list ,...
def autoexec ( pipe = None , name = None , exit_handler = None ) : """create a pipeline with a context that will automatically execute the pipeline upon leaving the context if no exception was raised . : param pipe : : param name : : return :"""
return pipeline ( pipe = pipe , name = name , autoexec = True , exit_handler = exit_handler )
def conditional_probability_alive ( self , frequency , recency , T ) : """Conditional probability alive . Compute the probability that a customer with history ( frequency , recency , T ) is currently alive . From paper : http : / / brucehardie . com / notes / 009 / pareto _ nbd _ derivations _ 2005-11-05 . ...
x , t_x = frequency , recency r , alpha , s , beta = self . _unload_params ( "r" , "alpha" , "s" , "beta" ) A_0 = self . _log_A_0 ( [ r , alpha , s , beta ] , x , t_x , T ) return 1.0 / ( 1.0 + exp ( log ( s ) - log ( r + s + x ) + ( r + x ) * log ( alpha + T ) + s * log ( beta + T ) + A_0 ) )
def increment ( index , dims , data_shape ) : """Increments a given index according to the shape of the data added : param index : Current index to be incremented : type index : list : param dims : Shape of the data that the index is being incremented by : type dims : tuple : param data _ shape : Shape of...
# check dimensions of data match structure inc_to_match = data_shape [ 1 : ] for dim_a , dim_b in zip ( inc_to_match , dims [ - 1 * ( len ( inc_to_match ) ) : ] ) : if dim_a != dim_b : raise DataIndexError ( ) # now we can safely discard all but the highest dimension inc_index = len ( index ) - len ( data_s...
def build_event_out ( self , event_out ) : """Build event out code . @ param event _ out : event out object @ type event _ out : lems . model . dynamics . EventOut @ return : Generated event out code @ rtype : string"""
event_out_code = [ 'if "{0}" in self.event_out_callbacks:' . format ( event_out . port ) , ' for c in self.event_out_callbacks[\'{0}\']:' . format ( event_out . port ) , ' c()' ] return event_out_code
def _active_cli ( self ) : """Return the active ` CommandLineInterface ` ."""
cli = self . cli # If there is a sub CLI . That one is always active . while cli . _sub_cli : cli = cli . _sub_cli return cli
def from_numpy_arrays ( freq_data , noise_data , length , delta_f , low_freq_cutoff ) : """Interpolate n PSD ( as two 1 - dimensional arrays of frequency and data ) to the desired length , delta _ f and low frequency cutoff . Parameters freq _ data : array Array of frequencies . noise _ data : array PSD...
# Only include points above the low frequency cutoff if freq_data [ 0 ] > low_freq_cutoff : raise ValueError ( 'Lowest frequency in input data ' ' is higher than requested low-frequency cutoff ' + str ( low_freq_cutoff ) ) kmin = int ( low_freq_cutoff / delta_f ) flow = kmin * delta_f data_start = ( 0 if freq_data ...
def course_feature ( catalog , soup ) : """Parses all the courses ( AKA , the most important part ) ."""
courses = { } count = 0 for course_data in parse_tables ( soup ) : c = create_course ( course_data ) count += 1 courses [ str ( c ) ] = c catalog . courses = FrozenDict ( courses ) logger . info ( 'Catalog has %d courses (manual: %d)' % ( len ( courses ) , count ) )
def stop_process ( parser_args ) : """Stop / Kill specific daemon"""
from synergy . system import process_helper try : pid = process_helper . get_process_pid ( parser_args . process_name ) if pid is None or process_helper . poll_process ( parser_args . process_name ) is False : message = 'ERROR: Process {0} is already terminated {1}\n' . format ( parser_args . process_na...
def item ( text , level = 0 , options = None ) : """Print indented item ."""
# Extra line before in each section ( unless brief ) if level == 0 and not options . brief : print ( '' ) # Only top - level items displayed in brief mode if level == 1 and options . brief : return # Four space for each level , additional space for wiki format indent = level * 4 if options . format == "wiki" an...
def boards ( self , startAt = 0 , maxResults = 50 , type = None , name = None , projectKeyOrID = None ) : """Get a list of board resources . : param startAt : The starting index of the returned boards . Base index : 0. : param maxResults : The maximum number of boards to return per page . Default : 50 : param...
params = { } if type : params [ 'type' ] = type if name : params [ 'name' ] = name if projectKeyOrID : params [ 'projectKeyOrId' ] = projectKeyOrID if self . _options [ 'agile_rest_path' ] == GreenHopperResource . GREENHOPPER_REST_PATH : # Old , private API did not support pagination , all records were pres...
def _handle_keypad_message ( self , data ) : """Handle keypad messages . : param data : keypad message to parse : type data : string : returns : : py : class : ` ~ alarmdecoder . messages . Message `"""
msg = Message ( data ) if self . _internal_address_mask & msg . mask > 0 : if not self . _ignore_message_states : self . _update_internal_states ( msg ) self . on_message ( message = msg ) return msg
def tlsa_data ( pub , usage , selector , matching ) : '''Generate a TLSA rec : param pub : Pub key in PEM format : param usage : : param selector : : param matching : : return : TLSA data portion'''
usage = RFC . validate ( usage , RFC . TLSA_USAGE ) selector = RFC . validate ( selector , RFC . TLSA_SELECT ) matching = RFC . validate ( matching , RFC . TLSA_MATCHING ) pub = ssl . PEM_cert_to_DER_cert ( pub . strip ( ) ) if matching == 0 : cert_fp = binascii . b2a_hex ( pub ) else : hasher = hashlib . new (...