signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _build_filename_from_browserstack_json ( j ) : """Build a useful filename for an image from the screenshot json metadata"""
filename = '' device = j [ 'device' ] if j [ 'device' ] else 'Desktop' if j [ 'state' ] == 'done' and j [ 'image_url' ] : detail = [ device , j [ 'os' ] , j [ 'os_version' ] , j [ 'browser' ] , j [ 'browser_version' ] , '.jpg' ] filename = '_' . join ( item . replace ( " " , "_" ) for item in detail if item ) e...
def login ( self , username , password , token ) : '''Login to Salesforce . com and starts a client session . Unlike other toolkits , token is a separate parameter , because Salesforce doesn ' t explicitly tell you to append it when it gives you a login error . Folks that are new to the API may not know this ...
self . _setHeaders ( 'login' ) result = self . _sforce . service . login ( username , password + token ) # set session header header = self . generateHeader ( 'SessionHeader' ) header . sessionId = result [ 'sessionId' ] self . setSessionHeader ( header ) self . _sessionId = result [ 'sessionId' ] self . _userId = resu...
def List ( self , * branches , ** kwargs ) : """While ` Seq ` is sequential , ` phi . dsl . Expression . List ` allows you to split the computation and get back a list with the result of each path . While the list literal should be the most incarnation of this expresion , it can actually be any iterable ( implement...
gs = [ _parse ( code ) . _f for code in branches ] def h ( x , state ) : ys = [ ] for g in gs : y , state = g ( x , state ) ys . append ( y ) return ( ys , state ) return self . __then__ ( h , ** kwargs )
def _adjust_width ( self ) : """Shrinks bar if number of iterations is less than the bar width"""
if self . bar_width > self . max_iter : self . bar_width = int ( self . max_iter )
def _calc ( self , x , y ) : """List based implementation of binary tree algorithm for concordance measure after : cite : ` Christensen2005 ` ."""
x = np . array ( x ) y = np . array ( y ) n = len ( y ) perm = list ( range ( n ) ) perm . sort ( key = lambda a : ( x [ a ] , y [ a ] ) ) vals = y [ perm ] ExtraY = 0 ExtraX = 0 ACount = 0 BCount = 0 CCount = 0 DCount = 0 ECount = 0 DCount = 0 Concordant = 0 Discordant = 0 # ids for left child li = [ None ] * ( n - 1 ...
def is_the_same_indel ( self , other_record , ref_seq ) : '''Returns True iff this record and other _ record are the " same " indel . At repeats , there is more than one way to report the same variant . eg : pos = 42 , ref = CAAA , alt = CAA pos = 43 , ref = AAA , alt = AA pos = 44 , ref = AA , alt = A'''
if self . CHROM != other_record . CHROM or len ( self . ALT ) > 1 or len ( other_record . ALT ) > 1 or self . is_snp ( ) or other_record . is_snp ( ) : return False # The number of nuleotides that have been added or removed # is a necessary condition of the indels being the same , # so check that before devling int...
def cnst_AT ( self , Y ) : r"""Compute : math : ` A ^ T \ mathbf { y } ` . In this case : math : ` A ^ T \ mathbf { y } = ( I \ ; \ ; \ Gamma _ 0 ^ T \ ; \ ; \ Gamma _ 1 ^ T \ ; \ ; \ ldots ) \ mathbf { y } ` ."""
return self . cnst_A0T ( self . block_sep0 ( Y ) ) + np . sum ( self . cnst_A1T ( self . block_sep1 ( Y ) ) , axis = - 1 )
def checkGeneTreeMatchesSpeciesTree ( speciesTree , geneTree , processID ) : """Function to check ids in gene tree all match nodes in species tree"""
def fn ( tree , l ) : if tree . internal : fn ( tree . left , l ) fn ( tree . right , l ) else : l . append ( processID ( tree . iD ) ) l = [ ] fn ( speciesTree , l ) l2 = [ ] fn ( geneTree , l2 ) for i in l2 : # print " node " , i , l assert i in l
def create_inline ( project , resource , offset ) : """Create a refactoring object for inlining Based on ` resource ` and ` offset ` it returns an instance of ` InlineMethod ` , ` InlineVariable ` or ` InlineParameter ` ."""
pyname = _get_pyname ( project , resource , offset ) message = 'Inline refactoring should be performed on ' 'a method, local variable or parameter.' if pyname is None : raise rope . base . exceptions . RefactoringError ( message ) if isinstance ( pyname , pynames . ImportedName ) : pyname = pyname . _get_import...
def format_string ( string , foreground = None , background = None , reset = True , bold = False , faint = False , italic = False , underline = False , blink = False , inverted = False ) : """Returns a Unicode string formatted with an ANSI escape sequence . string String to format foreground Foreground colo...
colour_format = format_escape ( foreground , background , bold , faint , italic , underline , blink , inverted ) reset_format = '' if not reset else ANSI_FORMAT_RESET return '{}{}{}' . format ( colour_format , string , reset_format )
def _get_connection ( self ) : """Returns connection to the postgres database . Returns : connection to postgres database who stores mpr data ."""
if not getattr ( self , '_connection' , None ) : logger . debug ( 'Creating new connection.\n dsn: {}' . format ( self . _dsn ) ) d = parse_url_to_dict ( self . _dsn ) self . _connection = psycopg2 . connect ( database = d [ 'path' ] . strip ( '/' ) , user = d [ 'username' ] , password = d [ 'password' ] ...
def decode ( self , codes ) : """Given PQ - codes , reconstruct original D - dimensional vectors via : func : ` PQ . decode ` , and applying an inverse - rotation . Args : codes ( np . ndarray ) : PQ - cdoes with shape = ( N , M ) and dtype = self . code _ dtype . Each row is a PQ - code Returns : np . ...
# Because R is a rotation matrix ( R ^ t * R = I ) , R ^ - 1 should be R ^ t return self . pq . decode ( codes ) @ self . R . T
def _resource_index ( self , resource ) : """Get index for given resource . by default it will be ` self . index ` , but it can be overriden via app . config : param resource : resource name"""
datasource = self . get_datasource ( resource ) indexes = self . _resource_config ( resource , 'INDEXES' ) or { } default_index = self . _resource_config ( resource , 'INDEX' ) return indexes . get ( datasource [ 0 ] , default_index )
def ping ( self ) : """Check connectivity to InfluxDB . : returns : The version of the InfluxDB the client is connected to"""
response = self . request ( url = "ping" , method = 'GET' , expected_response_code = 204 ) return response . headers [ 'X-Influxdb-Version' ]
def _get_gene_info ( self , limit ) : """Currently loops through the gene _ info file and creates the genes as classes , typed with SO . It will add their label , any alternate labels as synonyms , alternate ids as equivlaent classes . HPRDs get added as protein products . The chromosome and chr band get ad...
src_key = 'gene_info' if self . test_mode : graph = self . testgraph else : graph = self . graph geno = Genotype ( graph ) model = Model ( graph ) # not unzipping the file LOG . info ( "Processing 'Gene Info' records" ) line_counter = 0 gene_info = '/' . join ( ( self . rawdir , self . files [ src_key ] [ 'file...
def clear_data ( self ) : """Removes the content data . raise : NoAccess - ` ` Metadata . isRequired ( ) ` ` is ` ` true ` ` or ` ` Metadata . isReadOnly ( ) ` ` is ` ` true ` ` * compliance : mandatory - - This method must be implemented . *"""
# cjshaw @ mit . edu , Jan 9 , 2015 # Removes the item from AWS S3 and resets URL to ' ' odl_repo , url = get_aws_s3_handle ( self . _config_map ) existing_url = self . _payload . get_url_metadata ( ) . get_existing_string_values ( ) [ 0 ] # try to clear from payload first , in case that fails we won ' t mess with AWS ...
def create_cmd ( self , args ) : '''' create ' sub - command : param args : cli arguments : return :'''
cmd = args . get ( 'cmd_create' ) if cmd == 'conf' : conf_file = args [ 'conf_file' ] conf_id = args [ 'id' ] return self . load_xml_conf ( conf_file , conf_id ) else : print ( "Error: Create %s is invalid or not implemented" % cmd )
def Main ( ) : """The main function . Returns : bool : True if successful or False otherwise ."""
tool = image_export_tool . ImageExportTool ( ) if not tool . ParseArguments ( ) : return False if tool . list_signature_identifiers : tool . ListSignatureIdentifiers ( ) return True if not tool . has_filters : logging . warning ( 'No filter defined exporting all files.' ) # TODO : print more status info...
def _add_tip_during_transfer ( self , tips , ** kwargs ) : """Performs a : any : ` pick _ up _ tip ` when running a : any : ` transfer ` , : any : ` distribute ` , or : any : ` consolidate ` ."""
if self . has_tip_rack ( ) and tips > 0 and not self . current_tip ( ) : self . pick_up_tip ( )
def raw ( self , use_local = True ) : """Load the raw dataset from remote URL or local file Parameters use _ local : boolean If True ( default ) , then attempt to load the dataset locally . If False or if the dataset is not available locally , then load the data from an external URL ."""
if use_local and self . is_local : return pkgutil . get_data ( 'vega_datasets' , self . pkg_filename ) else : return urlopen ( self . url ) . read ( )
def load_tensor ( f , format = None ) : # type : ( Union [ IO [ bytes ] , Text ] , Optional [ Any ] ) - > TensorProto '''Loads a serialized TensorProto into memory @ params f can be a file - like object ( has " read " function ) or a string containing a file name format is for future use @ return Loaded i...
s = _load_bytes ( f ) return load_tensor_from_string ( s , format = format )
def send_game ( self , chat_id : Union [ int , str ] , game_short_name : str , disable_notification : bool = None , reply_to_message_id : int = None , reply_markup : Union [ "pyrogram.InlineKeyboardMarkup" , "pyrogram.ReplyKeyboardMarkup" , "pyrogram.ReplyKeyboardRemove" , "pyrogram.ForceReply" ] = None ) -> "pyrogram....
r = self . send ( functions . messages . SendMedia ( peer = self . resolve_peer ( chat_id ) , media = types . InputMediaGame ( id = types . InputGameShortName ( bot_id = types . InputUserSelf ( ) , short_name = game_short_name ) , ) , message = "" , silent = disable_notification or None , reply_to_msg_id = reply_to_mes...
def extract_subtree ( self , node ) : '''Return a copy of the subtree rooted at ` ` node ` ` Args : ` ` node ` ` ( ` ` Node ` ` ) : The root of the desired subtree Returns : ` ` Tree ` ` : A copy of the subtree rooted at ` ` node ` `'''
if not isinstance ( node , Node ) : raise TypeError ( "node must be a Node" ) r = self . root ; self . root = node ; o = copy ( self ) ; self . root = r ; return o
def make_arrow ( self , portal ) : """Make an : class : ` Arrow ` to represent a : class : ` Portal ` , store it , and return it ."""
if ( portal [ "origin" ] not in self . spot or portal [ "destination" ] not in self . spot ) : raise ValueError ( "An :class:`Arrow` should only be made after " "the :class:`Spot`s it connects" ) if ( portal [ "origin" ] in self . arrow and portal [ "destination" ] in self . arrow [ portal [ "origin" ] ] ) : ra...
def _analyze_txt_config ( self , config_string = None ) : """Analyze the given container and return the corresponding job . If ` ` config _ string ` ` is ` ` None ` ` , try reading it from the TXT config file inside the container . : param string config _ string : the configuration string : rtype : : class ...
self . log ( u"Analyzing container with TXT config string" ) if config_string is None : self . log ( u"Analyzing container with TXT config file" ) config_entry = self . container . entry_config_txt self . log ( [ u"Found TXT config entry '%s'" , config_entry ] ) config_dir = os . path . dirname ( config...
def request ( self , method , endpoint , payload = None , timeout = 5 ) : """Send request to API ."""
url = self . api_url + endpoint data = None headers = { } if payload is not None : data = json . dumps ( payload ) headers [ 'Content-Type' ] = 'application/json' try : if self . auth_token is not None : headers [ API_AUTH_HEADER ] = self . auth_token response = self . session . request ( me...
def get_response ( url , plugins , timeout = SPLASH_TIMEOUT ) : """Return response with HAR , inline scritps and software detected by JS matchers . : rtype : dict"""
lua_script = create_lua_script ( plugins ) lua = urllib . parse . quote_plus ( lua_script ) page_url = f'{SPLASH_URL}/execute?url={url}&timeout={timeout}&lua_source={lua}' try : with docker_container ( ) : logger . debug ( '[+] Sending request to Splash instance' ) res = requests . get ( page_url ) ...
def parse ( self , path ) : """Extracts a dictionary of values from the XML file at the specified path ."""
# Load the template that will be used for parsing the values . expath , template , root = self . _load_template ( path ) if expath is not None : values = template . parse ( root ) return ( values , template )
def _search ( self , search_terms , begins_with = None ) : """Returns a list of Archive id ' s in the table on Dynamo"""
kwargs = dict ( ProjectionExpression = '#id' , ExpressionAttributeNames = { "#id" : "_id" } ) if len ( search_terms ) > 0 : kwargs [ 'FilterExpression' ] = reduce ( lambda x , y : x & y , [ Attr ( 'tags' ) . contains ( arg ) for arg in search_terms ] ) if begins_with : if 'FilterExpression' in kwargs : ...
def to_code_array ( self ) : """Replaces everything in code _ array from xls _ file"""
self . _xls2shape ( ) worksheets = self . workbook . sheet_names ( ) for tab , worksheet_name in enumerate ( worksheets ) : worksheet = self . workbook . sheet_by_name ( worksheet_name ) self . _xls2code ( worksheet , tab ) self . _xls2attributes ( worksheet , tab ) self . _xls2row_heights ( worksheet ,...
def _extract_blocks ( x , block_h , block_w ) : """Helper function for local 2d attention . Args : x : a [ batch , height , width , depth ] tensor block _ h : An integer . block height block _ w : An inteter . block width returns : a [ batch , num _ heads , height / block _ h , width / block _ w , depth...
( _ , height , width , depth ) = common_layers . shape_list ( x ) assert height % block_h == 0 assert width % block_w == 0 x = tf . reshape ( x , [ - 1 , height // block_h , block_h , width // block_w , block_w , depth ] ) return tf . transpose ( x , [ 0 , 1 , 3 , 2 , 4 , 5 ] )
def package_meta ( ) : """Read _ _ init _ _ . py for global package metadata . Do this without importing the package ."""
_version_re = re . compile ( r'__version__\s+=\s+(.*)' ) _url_re = re . compile ( r'__url__\s+=\s+(.*)' ) _license_re = re . compile ( r'__license__\s+=\s+(.*)' ) with open ( 'lambda_uploader/__init__.py' , 'rb' ) as ffinit : initcontent = ffinit . read ( ) version = str ( ast . literal_eval ( _version_re . sea...
def rotate_bitmaps_to_roots ( bitmaps , roots ) : """Circularly shift a relative bitmaps to asbolute pitch classes . See : func : ` rotate _ bitmap _ to _ root ` for more information . Parameters bitmap : np . ndarray , shape = ( N , 12) Bitmap of active notes , relative to the given root . root : np . nd...
abs_bitmaps = [ ] for bitmap , chord_root in zip ( bitmaps , roots ) : abs_bitmaps . append ( rotate_bitmap_to_root ( bitmap , chord_root ) ) return np . asarray ( abs_bitmaps )
def cli ( env , volume_id , capacity , tier , upgrade ) : """Order snapshot space for a file storage volume ."""
file_manager = SoftLayer . FileStorageManager ( env . client ) if tier is not None : tier = float ( tier ) try : order = file_manager . order_snapshot_space ( volume_id , capacity = capacity , tier = tier , upgrade = upgrade ) except ValueError as ex : raise exceptions . ArgumentError ( str ( ex ) ) if 'pla...
def receive ( self , path , diffTo , diffFrom ) : """Receive a btrfs diff ."""
diff = self . toObj . diff ( diffTo , diffFrom ) self . _open ( self . butterStore . receive ( diff , [ path , ] ) )
def scale ( self , width : int , height : int ) -> None : """Scale this Image to the new width and height . Args : width ( int ) : The new width of the Image after scaling . height ( int ) : The new height of the Image after scaling ."""
lib . TCOD_image_scale ( self . image_c , width , height ) self . width , self . height = width , height
def p_print_list_at ( p ) : """print _ at : AT expr COMMA expr"""
p [ 0 ] = make_sentence ( 'PRINT_AT' , make_typecast ( TYPE . ubyte , p [ 2 ] , p . lineno ( 1 ) ) , make_typecast ( TYPE . ubyte , p [ 4 ] , p . lineno ( 3 ) ) )
def _make_temp_directory ( prefix ) : '''Generate a temporary directory that would not live beyond the lifetime of unity _ server . Caller is expected to clean up the temp file as soon as the directory is no longer needed . But the directory will be cleaned as unity _ server restarts'''
temp_dir = _make_temp_filename ( prefix = str ( prefix ) ) _os . makedirs ( temp_dir ) return temp_dir
def fetchUserJobs ( self , jobs ) : """Takes a user input array of jobs , verifies that they are in the jobStore and returns the array of jobsToReport . : param list jobs : A list of jobs to be verified . : returns jobsToReport : A list of jobs which are verified to be in the jobStore ."""
jobsToReport = [ ] for jobID in jobs : try : jobsToReport . append ( self . jobStore . load ( jobID ) ) except JobException : print ( 'The job %s could not be found.' % jobID , file = sys . stderr ) raise return jobsToReport
def _validate_platforms_in_image ( self , image ) : """Ensure that the image provides all platforms expected for the build ."""
expected_platforms = get_platforms ( self . workflow ) if not expected_platforms : self . log . info ( 'Skipping validation of available platforms ' 'because expected platforms are unknown' ) return if len ( expected_platforms ) == 1 : self . log . info ( 'Skipping validation of available platforms for base...
def save ( self ) : """Saves pypirc file with new configuration information ."""
for server , conf in self . servers . iteritems ( ) : self . _add_index_server ( ) for conf_k , conf_v in conf . iteritems ( ) : if not self . conf . has_section ( server ) : self . conf . add_section ( server ) self . conf . set ( server , conf_k , conf_v ) with open ( self . rc_fil...
def search ( self , index = None , doc_type = None , body = None , ** query_params ) : """Make a search query on the elastic search ` < http : / / www . elastic . co / guide / en / elasticsearch / reference / current / search - search . html > ` _ : param index : the index name to query : param doc _ type : h...
path = self . _es_parser . make_path ( index , doc_type , EsMethods . SEARCH ) result = yield self . _perform_request ( HttpMethod . POST , path , body = body , params = query_params ) returnValue ( result )
def response_hook ( self , r , ** kwargs ) : """The actual hook handler ."""
if r . status_code == 401 : # Handle server auth . www_authenticate = r . headers . get ( 'www-authenticate' , '' ) . lower ( ) auth_type = _auth_type_from_header ( www_authenticate ) if auth_type is not None : return self . retry_using_http_NTLM_auth ( 'www-authenticate' , 'Authorization' , r , aut...
def _get_cached_stats ( self , app_stats ) : """Process : * cached _ host _ check _ stats * cached _ service _ check _ stats"""
stats = { } app_keys = [ "cached_host_check_stats" , "cached_service_check_stats" , ] for app_key in app_keys : if app_key not in app_stats . keys ( ) : continue ( x01 , x05 , x15 ) = self . _convert_tripplet ( app_stats [ app_key ] ) scratch = app_key . split ( "_" ) [ 1 ] stats [ "%ss.cached.0...
def by_id ( cls , user_id , db_session = None ) : """fetch user by user id : param user _ id : : param db _ session : : return :"""
db_session = get_db_session ( db_session ) query = db_session . query ( cls . model ) query = query . filter ( cls . model . id == user_id ) query = query . options ( sa . orm . eagerload ( "groups" ) ) return query . first ( )
def get_n_header ( f , header_char = '"' ) : '''Get the nummber of header rows in a Little Leonardo data file Args f : file stream File handle for the file from which header rows will be read header _ char : str Character array at beginning of each header line Returns n _ header : int Number of head...
n_header = 0 reading_headers = True while reading_headers : line = f . readline ( ) if line . startswith ( header_char ) : n_header += 1 else : reading_headers = False return n_header
def get_config ( self , budget ) : """Function to sample a new configuration This function is called inside BOHB to query a new configuration Parameters : budget : float the budget for which this configuration is scheduled Returns config return a valid configuration with parameters and budget"""
logger . debug ( 'start sampling a new configuration.' ) sample = None info_dict = { } # If no model is available , sample from prior # also mix in a fraction of random configs if len ( self . kde_models . keys ( ) ) == 0 or np . random . rand ( ) < self . random_fraction : sample = self . configspace . sample_conf...
def validate_term ( term , so = None , method = "verify" ) : """Validate an SO term against so . obo"""
if so is None : so = load_GODag ( ) oterm = term if term not in so . valid_names : if "resolve" in method : if "_" in term : tparts = deque ( term . split ( "_" ) ) tparts . pop ( ) if "prefix" in method else tparts . popleft ( ) nterm = "_" . join ( tparts ) . strip ...
def expand_groups ( config_ids , maps ) : """Iterates over a list of container configuration ids , expanding groups of container configurations . : param config _ ids : List of container configuration ids . : type config _ ids : collections . Iterable [ dockermap . map . input . InputConfigId | dockermap . map ...
for config_id in config_ids : if config_id . map_name == '__all__' : c_maps = six . iteritems ( maps ) else : c_maps = ( config_id . map_name , maps [ config_id . map_name ] ) , if isinstance ( config_id , InputConfigId ) : instance_name = config_id . instance_names elif isinstan...
def _merge_user_attrs ( self , attrs_backend , attrs_out , backend_name ) : """merge attributes from one backend search to the attributes dict output"""
for attr in attrs_backend : if attr in self . attributes . backend_attributes [ backend_name ] : attrid = self . attributes . backend_attributes [ backend_name ] [ attr ] if attrid not in attrs_out : attrs_out [ attrid ] = attrs_backend [ attr ]
def _update_length ( self ) : """Update the length field of the struct ."""
action_length = 4 + len ( self . field . pack ( ) ) overflow = action_length % 8 self . length = action_length if overflow : self . length = action_length + 8 - overflow
def _split ( self , string ) : """Iterates over the ngrams of a string ( no padding ) . > > > from ngram import NGram > > > n = NGram ( ) > > > list ( n . _ split ( " hamegg " ) ) [ ' ham ' , ' ame ' , ' meg ' , ' egg ' ]"""
for i in range ( len ( string ) - self . N + 1 ) : yield string [ i : i + self . N ]
def parse_names ( cls , expression ) : """Return the list of identifiers used in the expression ."""
names = set ( ) try : ast_node = ast . parse ( expression , "ast" ) class Visitor ( ast . NodeVisitor ) : def visit_Name ( self , node ) : names . add ( node . id ) Visitor ( ) . visit ( ast_node ) except Exception : pass return names
def rdist ( x , y ) : """Reduced Euclidean distance . Parameters x : array of shape ( embedding _ dim , ) y : array of shape ( embedding _ dim , ) Returns The squared euclidean distance between x and y"""
result = 0.0 for i in range ( x . shape [ 0 ] ) : result += ( x [ i ] - y [ i ] ) ** 2 return result
def __set_formula ( self , formula ) : """Sets a formula in this cell . Any cell value can be set using this method . Actual formulas must start with an equal sign ."""
array = ( ( self . _clean_formula ( formula ) , ) , ) return self . _get_target ( ) . setFormulaArray ( array )
def _symmetrize_correlograms ( correlograms ) : """Return the symmetrized version of the CCG arrays ."""
n_clusters , _ , n_bins = correlograms . shape assert n_clusters == _ # We symmetrize c [ i , j , 0 ] . # This is necessary because the algorithm in correlograms ( ) # is sensitive to the order of identical spikes . correlograms [ ... , 0 ] = np . maximum ( correlograms [ ... , 0 ] , correlograms [ ... , 0 ] . T ) sym ...
def multihead_attention_vars ( mesh , heads , io_channels , kv_channels , master_dtype , slice_dtype , activation_dtype ) : """Deprecated version of multihead _ attention _ params with combine = True ."""
return multihead_attention_params ( mesh , heads , io_channels , kv_channels , mtf . VariableDType ( master_dtype , slice_dtype , activation_dtype ) , combine = True )
def remove_connection ( provider_id , provider_user_id ) : """Remove a specific connection for the authenticated user to the specified provider"""
provider = get_provider_or_404 ( provider_id ) ctx = dict ( provider = provider . name , user = current_user , provider_user_id = provider_user_id ) deleted = _datastore . delete_connection ( user_id = current_user . get_id ( ) , provider_id = provider_id , provider_user_id = provider_user_id ) if deleted : after_t...
def download_and_calibrate_parallel ( list_of_ids , n = None ) : """Download and calibrate in parallel . Parameters list _ of _ ids : list , optional container with img _ ids to process n : int Number of cores for the parallel processing . Default : n _ cores _ system / / 2"""
setup_cluster ( n_cores = n ) c = Client ( ) lbview = c . load_balanced_view ( ) lbview . map_async ( download_and_calibrate , list_of_ids ) subprocess . Popen ( [ "ipcluster" , "stop" , "--quiet" ] )
def exponential ( x , y , xscale , yscale ) : """Two - dimensional oriented exponential decay pattern ."""
if xscale == 0.0 or yscale == 0.0 : return x * 0.0 with float_error_ignore ( ) : x_w = np . divide ( x , xscale ) y_h = np . divide ( y , yscale ) return np . exp ( - np . sqrt ( x_w * x_w + y_h * y_h ) )
def calculate_signature ( key , data , timestamp = None ) : """Calculates the signature for the given request data ."""
# Create a timestamp if one was not given if timestamp is None : timestamp = int ( time . time ( ) ) # Construct the message from the timestamp and the data in the request message = str ( timestamp ) + '' . join ( "%s%s" % ( k , v ) for k , v in sorted ( data . items ( ) ) ) # Calculate the signature ( HMAC SHA256 ...
def to_html ( sample , stats_object ) : """Generate a HTML report from summary statistics and a given sample . Parameters sample : DataFrame the sample you want to print stats _ object : dict Summary statistics . Should be generated with an appropriate describe ( ) function Returns str containing pr...
n_obs = stats_object [ 'table' ] [ 'n' ] value_formatters = formatters . value_formatters row_formatters = formatters . row_formatters if not isinstance ( sample , pd . DataFrame ) : raise TypeError ( "sample must be of type pandas.DataFrame" ) if not isinstance ( stats_object , dict ) : raise TypeError ( "stat...
def msvs_parse_version ( s ) : """Split a Visual Studio version , which may in fact be something like '7.0Exp ' , into is version number ( returned as a float ) and trailing " suite " portion ."""
num , suite = version_re . match ( s ) . groups ( ) return float ( num ) , suite
def getTotalPrice ( self ) : """compute total price"""
price = self . getPrice ( ) price = Decimal ( price or '0.00' ) vat = Decimal ( self . getVAT ( ) ) vat = vat and vat / 100 or 0 price = price + ( price * vat ) return price . quantize ( Decimal ( '0.00' ) )
def to_datetime ( self , column ) : '''This function converts epoch timestamps to datetimes . : param column : column to convert from current state - > datetime'''
if column in self : if self [ column ] . dtype in NUMPY_NUMERICAL : self [ column ] = pd . to_datetime ( self [ column ] , unit = 's' ) else : self [ column ] = pd . to_datetime ( self [ column ] , utc = True )
def parse ( cls , args ) : """Parse command line arguments to construct a dictionary of command parameters that can be used to create a command Args : ` args ` : sequence of arguments Returns : Dictionary that can be used in create method Raises : ParseError : when the arguments are not correct"""
try : ( options , args ) = cls . optparser . parse_args ( args ) if options . inline is None and options . script_location is None : raise ParseError ( "One of script or it's location" " must be specified" , cls . optparser . format_help ( ) ) except OptionParsingError as e : raise ParseError ( e . ...
def __generate_tree ( self , top , src , resources , models , ctrls , views , utils ) : """Creates directories and packages"""
res = self . __mkdir ( top ) for fn in ( src , models , ctrls , views , utils ) : res = self . __mkpkg ( fn ) or res res = self . __mkdir ( resources ) or res res = self . __mkdir ( os . path . join ( resources , "ui" , "builder" ) ) or res res = self . __mkdir ( os . path . join ( resources , "ui" , "styles" ) ) o...
def rotate ( name , pattern = None , conf_file = default_conf , ** kwargs ) : '''Set up pattern for logging . name : string alias for entryname pattern : string alias for log _ file conf _ file : string optional path to alternative configuration file kwargs : boolean | string | int optional addition...
# # cleanup kwargs kwargs = salt . utils . args . clean_kwargs ( ** kwargs ) # # inject name into kwargs if 'entryname' not in kwargs and name and not name . startswith ( '/' ) : kwargs [ 'entryname' ] = name # # inject pattern into kwargs if 'log_file' not in kwargs : if pattern and pattern . startswith ( '/' ...
def wrap_line ( line , maxline = 79 , result = [ ] , count = count ) : """We have a line that is too long , so we ' re going to try to wrap it ."""
# Extract the indentation append = result . append extend = result . extend indentation = line [ 0 ] lenfirst = len ( indentation ) indent = lenfirst - len ( indentation . lstrip ( ) ) assert indent in ( 0 , lenfirst ) indentation = line . pop ( 0 ) if indent else '' # Get splittable / non - splittable groups dgroups =...
def pprint ( sequence_file , annotation = None , annotation_file = None , block_length = 10 , blocks_per_line = 6 ) : """Pretty - print sequence ( s ) from a file ."""
annotations = [ ] if annotation : annotations . append ( [ ( first - 1 , last ) for first , last in annotation ] ) try : # Peek to see if this looks like a FASTA file . line = next ( sequence_file ) if line . startswith ( '>' ) : _pprint_fasta ( itertools . chain ( [ line ] , sequence_file ) , annot...
def contents ( self ) : """Return the list of contained directory entries , loading them if not already loaded ."""
if not self . contents_read : self . contents_read = True base = self . path for entry in os . listdir ( self . source_path ) : source_path = os . path . join ( self . source_path , entry ) target_path = os . path . join ( base , entry ) if os . path . isdir ( source_path ) : ...
def _canBeExpanded ( self , headVerbRoot , headVerbWID , suitableNomAdvExpansions , expansionVerbs , widToToken ) : '''Teeb kindlaks , kas kontekst on verbiahela laiendamiseks piisavalt selge / yhene : 1 ) Nii ' nom / adv ' kandidaate kui ka Vinf kandidaate on täpselt üks ; 2 ) Nom / adv ei kuulu mingi suurem...
if len ( suitableNomAdvExpansions ) == 1 and expansionVerbs : # Kontrollime , kas leidub t2pselt yks laiendiks sobiv verb ( kui leidub # rohkem , on kontekst kahtlane ja raske otsustada , kas tasub laiendada # v6i mitte ) suitableExpansionVerbs = [ expVerb for expVerb in expansionVerbs if expVerb [ 2 ] == suitableN...
def finish_async_rpc ( self , address , rpc_id , response ) : """Finish a previous asynchronous RPC . This method should be called by a peripheral tile that previously had an RPC called on it and chose to response asynchronously by raising ` ` AsynchronousRPCResponse ` ` in the RPC handler itself . The resp...
pending = self . _pending_rpcs . get ( address ) if pending is None : raise ArgumentError ( "No asynchronously RPC currently in progress on tile %d" % address ) responder = pending . get ( rpc_id ) if responder is None : raise ArgumentError ( "RPC %04X is not running asynchronous on tile %d" % ( rpc_id , addres...
async def get_creds_display_coarse ( self , filt : dict = None ) -> str : """Return human - readable credentials from wallet by input filter for schema identifier and / or credential definition identifier components ; return all credentials for no filter . : param filt : indy - sdk filter for credentials ; i ...
LOGGER . debug ( 'HolderProver.get_creds_display_coarse >>> filt: %s' , filt ) rv_json = await anoncreds . prover_get_credentials ( self . wallet . handle , json . dumps ( filt or { } ) ) LOGGER . debug ( 'HolderProver.get_creds_display_coarse <<< %s' , rv_json ) return rv_json
def rebin ( a , * args ) : """See http : / / scipy - cookbook . readthedocs . io / items / Rebinning . html Note : integer division in the computation of ' factor ' has been included to avoid the following runtime message : VisibleDeprecationWarning : using a non - integer number instead of an integer will ...
shape = a . shape len_shape = len ( shape ) factor = np . asarray ( shape ) // np . asarray ( args ) ev_list = [ 'a.reshape(' ] + [ 'args[%d], factor[%d], ' % ( i , i ) for i in range ( len_shape ) ] + [ ')' ] + [ '.mean(%d)' % ( i + 1 ) for i in range ( len_shape ) ] # print ( ' ' . join ( ev _ list ) ) return eval ( ...
def _ProcessSources ( self , sources , parser_factory ) : """Iterates through sources yielding action responses ."""
for source in sources : for action , request in self . _ParseSourceType ( source ) : yield self . _RunClientAction ( action , request , parser_factory , source . path_type )
def normalizeGlyphUnicode ( value ) : """Normalizes glyph unicode . * * * value * * must be an int or hex ( represented as a string ) . * * * value * * must be in a unicode range . * Returned value will be an ` ` int ` ` ."""
if not isinstance ( value , ( int , basestring ) ) or isinstance ( value , bool ) : raise TypeError ( "Glyph unicode must be a int or hex string, not %s." % type ( value ) . __name__ ) if isinstance ( value , basestring ) : try : value = int ( value , 16 ) except ValueError : raise ValueErro...
def list_indexes ( cls ) : """Returns a dictionary with the key as the es _ index name and the object is a list of rdfclasses for that index args : None"""
cls_list = cls . list_mapped_classes ( ) rtn_obj = { } for key , value in cls_list . items ( ) : idx = value . es_defs . get ( 'kds_esIndex' ) [ 0 ] try : rtn_obj [ idx ] . append ( value ) except KeyError : rtn_obj [ idx ] = [ value ] return rtn_obj
def replaceChild ( self , new_child : 'WdomElement' , old_child : 'WdomElement' ) -> Node : """Replace child nodes ."""
if self . connected : self . _replace_child_web ( new_child , old_child ) return self . _replace_child ( new_child , old_child )
def export_configuration_generator ( self , sql , sql_args ) : """Generator for : class : ` meteorpi _ model . ExportConfiguration ` : param sql : A SQL statement which must return rows describing export configurations : param sql _ args : Any variables required to populate the query provided in ' sql ' :...
self . con . execute ( sql , sql_args ) results = self . con . fetchall ( ) output = [ ] for result in results : if result [ 'exportType' ] == "observation" : search = mp . ObservationSearch . from_dict ( json . loads ( result [ 'searchString' ] ) ) elif result [ 'exportType' ] == "file" : searc...
def json_loads ( cls , s , ** kwargs ) : """A rewrap of json . loads done for one reason - to inject a custom ` cls ` kwarg : param s : : param kwargs : : return : : rtype : dict"""
if 'cls' not in kwargs : kwargs [ 'cls' ] = cls . json_decoder return json . loads ( s , ** kwargs )
def send ( self , msg ) : """send message to client ."""
assert isinstance ( msg , str ) , "String is required" if self . _debug : log . info ( "outgoing message: %s, %s" , self . id , str ( msg ) [ : 200 ] ) if self . state != STATE_OPEN : return self . _feed ( FRAME_MESSAGE , msg )
def runGetRnaQuantificationSet ( self , id_ ) : """Runs a getRnaQuantificationSet request for the specified ID ."""
compoundId = datamodel . RnaQuantificationSetCompoundId . parse ( id_ ) dataset = self . getDataRepository ( ) . getDataset ( compoundId . dataset_id ) rnaQuantificationSet = dataset . getRnaQuantificationSet ( id_ ) return self . runGetRequest ( rnaQuantificationSet )
def field_elongation ( ra , dec , date ) : """For a given field , calculate the solar elongation at the given date . : param ra : field ' s right ascension . unit = " h " format = " RAh : RAm : RAs " : param dec : field ' s declination . degrees : param date : date at which to calculate elongation : return ...
sun = ephem . Sun ( ) sun . compute ( date ) sep = ephem . separation ( ( ra , dec ) , sun ) retval = 180. - math . degrees ( sep ) return retval
def num_examples ( self ) : """The number of examples this subset spans ."""
if self . is_list : return len ( self . list_or_slice ) else : start , stop , step = self . slice_to_numerical_args ( self . list_or_slice , self . original_num_examples ) return stop - start
def get_file_path_validator ( default_file_param = None ) : """Creates a namespace validator that splits out ' path ' into ' directory _ name ' and ' file _ name ' . Allows another path - type parameter to be named which can supply a default filename ."""
def validator ( namespace ) : if not hasattr ( namespace , 'path' ) : return path = namespace . path dir_name , file_name = os . path . split ( path ) if path else ( None , '' ) if default_file_param and '.' not in file_name : dir_name = path file_name = os . path . split ( getat...
def fast_sweep_time_evolution ( Ep , epsilonp , gamma , omega_level , rm , xi , theta , semi_analytic = True , file_name = None , return_code = False ) : r"""Return a spectrum of time evolutions of the density matrix . We test a basic two - level system . > > > import numpy as np > > > from sympy import symbo...
# We unpack variables . if True : Nl = xi . shape [ 0 ] # We determine which arguments are constants . if True : try : Ep = np . array ( [ complex ( Ep [ l ] ) for l in range ( Nl ) ] ) variable_Ep = False except : variable_Ep = True try : epsilonp = [ np . array ( [ comp...
def get_id_generator ( self , name ) : """Creates cluster - wide : class : ` ~ hazelcast . proxy . id _ generator . IdGenerator ` . : param name : ( str ) , name of the IdGenerator proxy . : return : ( : class : ` ~ hazelcast . proxy . id _ generator . IdGenerator ` ) , IdGenerator proxy for the given name ."""
atomic_long = self . get_atomic_long ( ID_GENERATOR_ATOMIC_LONG_PREFIX + name ) return self . proxy . get_or_create ( ID_GENERATOR_SERVICE , name , atomic_long = atomic_long )
def build_alignment ( self , score , pieces ) : """converts a score and pieces to an alignment"""
# build text self . open_seqs ( ) text1 = text2 = "" end1 = end2 = None for ( start1 , start2 , length , pctId ) in pieces : if ( end1 != None ) : if ( start1 == end1 ) : # insertion in sequence 2 text1 += self . seq1_gap * ( start2 - end2 ) text2 += self . seq2_file . get ( end2 , s...
def strip_exts ( s , exts ) : """Given a string and an interable of extensions , strip the extenion off the string if the string ends with one of the extensions ."""
f_split = os . path . splitext ( s ) if f_split [ 1 ] in exts : return f_split [ 0 ] else : return s
def mask_file ( regionfile , infile , outfile , negate = False ) : """Created a masked version of file , using a region . Parameters regionfile : str A file which can be loaded as a : class : ` AegeanTools . regions . Region ` . The image will be masked according to this region . infile : str Input FITS...
# Check that the input file is accessible and then open it if not os . path . exists ( infile ) : raise AssertionError ( "Cannot locate fits file {0}" . format ( infile ) ) im = pyfits . open ( infile ) if not os . path . exists ( regionfile ) : raise AssertionError ( "Cannot locate region file {0}" . format ( ...
def _get_field_method ( self , tp ) : """Returns a reference to the form element ' s constructor method ."""
method = self . field_constructor . get ( tp ) if method and hasattr ( self , method . __name__ ) : return getattr ( self , method . __name__ ) return method
def load_EROS_lc ( filename = 'lm0010n22323.time' ) : """Read an EROS light curve and return its data . Parameters filename : str , optional A light - curve filename . Returns dates : numpy . ndarray An array of dates . magnitudes : numpy . ndarray An array of magnitudes . errors : numpy . ndarray...
module_path = dirname ( __file__ ) file_path = join ( module_path , 'lightcurves' , filename ) data = np . loadtxt ( file_path ) date = data [ : , 0 ] mag = data [ : , 1 ] err = data [ : , 2 ] return date , mag , err
def all_packages ( self ) : """Returns a list of all packages ."""
p = dict ( self . parsed_pipfile . get ( "dev-packages" , { } ) ) p . update ( self . parsed_pipfile . get ( "packages" , { } ) ) return p
def _add_rid_to_vrf_list ( self , ri ) : """Add router ID to a VRF list . In order to properly manage VRFs in the ASR , their usage has to be tracked . VRFs are provided with neutron router objects in their hosting _ info fields of the gateway ports . This means that the VRF is only available when the gatew...
if ri . ex_gw_port or ri . router . get ( 'gw_port' ) : driver = self . driver_manager . get_driver ( ri . id ) vrf_name = driver . _get_vrf_name ( ri ) if not vrf_name : return if not self . _router_ids_by_vrf . get ( vrf_name ) : LOG . debug ( "++ CREATING VRF %s" % vrf_name ) ...
def login ( session , user , password , database = None , server = None ) : """Logs into a MyGeotab server and stores the returned credentials . : param session : The current Session object . : param user : The username used for MyGeotab servers . Usually an email address . : param password : The password ass...
if not user : user = click . prompt ( "Username" , type = str ) if not password : password = click . prompt ( "Password" , hide_input = True , type = str ) try : with click . progressbar ( length = 1 , label = "Logging in..." ) as progressbar : session . login ( user , password , database , server )...
def stylemap ( self , definitions = True , all = True , cache = False ) : """return a dictionary of styles from . docx word / styles . xml , keyed to the id ( the id is used in the . docx word / document . xml rather than the style names ; this method creates a mapping for us to use when outputting the document...
if self . _stylemap is not None and cache == True : return self . _stylemap else : self . _stylemap = None # expire the cache x = self . xml ( src = 'word/styles.xml' ) document = self . xml ( src = 'word/document.xml' ) footnotes = self . xml ( src = 'word/footnotes.xml' ) # None if no foot...
def _reset_state_mode ( self , state , mode ) : """Reset the state mode to the given mode , and apply the custom state options specified with this analysis . : param state : The state to work with . : param str mode : The state mode . : return : None"""
state . set_mode ( mode ) state . options |= self . _state_add_options state . options = state . options . difference ( self . _state_remove_options )
def is_unclaimed ( work ) : """Returns True if work piece is unclaimed ."""
if work [ 'is_completed' ] : return False cutoff_time = time . time ( ) - MAX_PROCESSING_TIME if ( work [ 'claimed_worker_id' ] and work [ 'claimed_worker_start_time' ] is not None and work [ 'claimed_worker_start_time' ] >= cutoff_time ) : return False return True
def make_name ( self ) : """Autogenerates a : attr : ` name ` from : attr : ` title _ for _ name `"""
if self . title : self . name = six . text_type ( make_name ( self . title_for_name , maxlength = self . __name_length__ ) )