signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def tokens2text ( docgraph , token_ids ) : """given a list of token node IDs , returns a their string representation ( concatenated token strings ) ."""
return ' ' . join ( docgraph . node [ token_id ] [ docgraph . ns + ':token' ] for token_id in token_ids )
def prox_hard ( X , step , thresh = 0 ) : """Hard thresholding X if | X | > = thresh , otherwise 0 NOTE : modifies X in place"""
thresh_ = _step_gamma ( step , thresh ) below = np . abs ( X ) < thresh_ X [ below ] = 0 return X
def human_repr ( self ) : """Return decoded human readable string for URL representation ."""
return urlunsplit ( SplitResult ( self . scheme , self . _make_netloc ( self . user , self . password , self . host , self . _val . port , encode = False ) , self . path , self . query_string , self . fragment , ) )
def getPathogenProteinCounts ( filenames ) : """Get the number of proteins for each pathogen in C { filenames } . @ param filenames : Either C { None } or a C { list } of C { str } FASTA file names . If C { None } an empty C { Counter } is returned . If FASTA file names are given , their sequence ids should h...
result = Counter ( ) if filenames : for filename in filenames : for protein in FastaReads ( filename ) : _ , pathogenName = splitNames ( protein . id ) if pathogenName != _NO_PATHOGEN_NAME : result [ pathogenName ] += 1 return result
def end_output ( self , ** kwargs ) : """Write XML end tag ."""
self . xml_endtag ( u"urlset" ) self . xml_end_output ( ) self . close_fileoutput ( )
def scan ( ) : """Scan for Crazyflie and return its URI ."""
# Initiate the low level drivers cflib . crtp . init_drivers ( enable_debug_driver = False ) # Scan for Crazyflies print ( 'Scanning interfaces for Crazyflies...' ) available = cflib . crtp . scan_interfaces ( ) interfaces = [ uri for uri , _ in available ] if not interfaces : return None return choose ( interfaces...
def types ( cls ) : """The constraints that can be used for the ' type ' rule . Type : A tuple of strings ."""
redundant_types = set ( cls . types_mapping ) & set ( cls . _types_from_methods ) if redundant_types : warn ( "These types are defined both with a method and in the" "'types_mapping' property of this validator: %s" % redundant_types ) return tuple ( cls . types_mapping ) + cls . _types_from_methods
def set_verbosity ( args ) : '''determine the message level in the environment to set based on args .'''
level = "INFO" if args . debug is True : level = "DEBUG" elif args . quiet is True : level = "QUIET" os . environ [ 'MESSAGELEVEL' ] = level os . putenv ( 'MESSAGELEVEL' , level ) os . environ [ 'SINGULARITY_MESSAGELEVEL' ] = level os . putenv ( 'SINGULARITY_MESSAGELEVEL' , level ) # Import logger to set from s...
def create_border ( video , color = "blue" , border_percent = 2 ) : """Creates a border around each frame to differentiate input and target . Args : video : 5 - D NumPy array . color : string , " blue " , " red " or " green " . border _ percent : Percentarge of the frame covered by the border . Returns : ...
# Do not create border if the video is not in RGB format if video . shape [ - 1 ] != 3 : return video color_to_axis = { "blue" : 2 , "red" : 0 , "green" : 1 } axis = color_to_axis [ color ] _ , _ , height , width , _ = video . shape border_height = np . ceil ( border_percent * height / 100.0 ) . astype ( np . int )...
def SystemFee ( self ) : """Get the system fee . Returns : Fixed8:"""
if self . AssetType == AssetType . GoverningToken or self . AssetType == AssetType . UtilityToken : return Fixed8 . Zero ( ) return super ( RegisterTransaction , self ) . SystemFee ( )
def fetch_alien ( self , ) : """Set and return , if the reftrack element is linked to the current scene . Askes the refobj interface for the current scene . If there is no current scene then True is returned . : returns : whether the element is linked to the current scene : rtype : bool : raises : None"""
parent = self . get_parent ( ) if parent : parentelement = parent . get_element ( ) else : parentelement = self . get_refobjinter ( ) . get_current_element ( ) if not parentelement : self . _alien = True return self . _alien element = self . get_element ( ) if element == parentelement : ...
def get_shrunk_data ( shrink_info ) : """Read shrunk file from tinypng . org api ."""
out_url = shrink_info [ 'output' ] [ 'url' ] try : return requests . get ( out_url ) . content except HTTPError as err : if err . code != 404 : raise exc = ValueError ( "Unable to read png file \"{0}\"" . format ( out_url ) ) exc . __cause__ = err raise exc
def env_timestamp ( name , required = False , default = empty ) : """Pulls an environment variable out of the environment and parses it to a ` ` datetime . datetime ` ` object . The environment variable is expected to be a timestamp in the form of a float . If the name is not present in the environment and no...
if required and default is not empty : raise ValueError ( "Using `default` with `required=True` is invalid" ) value = get_env_value ( name , required = required , default = empty ) # change datetime . datetime to time , return time . struct _ time type if default is not empty and value is empty : return default...
def is_link_inline ( cls , tag , attribute ) : '''Return whether the link is likely to be inline object .'''
if tag in cls . TAG_ATTRIBUTES and attribute in cls . TAG_ATTRIBUTES [ tag ] : attr_flags = cls . TAG_ATTRIBUTES [ tag ] [ attribute ] return attr_flags & cls . ATTR_INLINE return attribute != 'href'
def valueAt ( self , percent ) : """Returns the value at the inputed percent . : param percent | < float > : return < variant >"""
minim = self . minimum ( ) maxim = self . maximum ( ) rtype = self . rulerType ( ) # simple minimum if ( percent <= 0 ) : return minim # simple maximum elif ( 1 <= percent ) : return maxim # calculate a numeric percentage value elif ( rtype == XChartRuler . Type . Number ) : return ( maxim - minim ) * perce...
def get_cell ( self , index ) : """For a single index and return the value : param index : index value : return : value"""
i = sorted_index ( self . _index , index ) if self . _sort else self . _index . index ( index ) return self . _data [ i ]
def update_events ( self , events_data : List [ Tuple [ str , int ] ] ) -> None : """Given a list of identifier / data event tuples update them in the DB"""
cursor = self . conn . cursor ( ) cursor . executemany ( 'UPDATE state_events SET data=? WHERE identifier=?' , events_data , ) self . maybe_commit ( )
def synchronize_step_names ( project : 'projects.Project' , insert_index : int = None ) -> Response : """: param project : : param insert _ index :"""
response = Response ( ) response . returned = dict ( ) if not project . naming_scheme : return response create_mapper_func = functools . partial ( create_rename_entry , insertion_index = insert_index ) step_renames = list ( [ create_mapper_func ( s ) for s in project . steps ] ) step_renames = list ( filter ( lambd...
def search ( self , pattern , ** kwargs ) : """Searchs given pattern text in the document . Usage : : > > > script _ editor = Umbra . components _ manager . get _ interface ( " factory . script _ editor " ) True > > > codeEditor = script _ editor . get _ current _ editor ( ) True > > > codeEditor . sear...
settings = foundations . data_structures . Structure ( ** { "case_sensitive" : False , "whole_word" : False , "regular_expressions" : False , "backward_search" : False , "wrap_around" : True } ) settings . update ( kwargs ) self . __search_pattern = pattern if settings . regular_expressions : pattern = QRegExp ( pa...
def scoped_session_decorator ( func ) : """Manage contexts and add debugging to psiTurk sessions ."""
@ wraps ( func ) def wrapper ( * args , ** kwargs ) : from wallace . db import session as wallace_session with sessions_scope ( wallace_session ) as session : from psiturk . db import db_session as psi_session with sessions_scope ( psi_session ) as session_psiturk : # The sessions used in func c...
def apply ( self ) : """Apply the transformation by configuration ."""
source = self . document [ 'source' ] self . reporter . info ( 'AutoStructify: %s' % source ) # only transform markdowns if not source . endswith ( tuple ( self . config [ 'commonmark_suffixes' ] ) ) : return self . url_resolver = self . config [ 'url_resolver' ] assert callable ( self . url_resolver ) self . state...
def swap ( name , persist = True , config = '/etc/fstab' ) : '''Activates a swap device . . code - block : : yaml / root / swapfile : mount . swap . . note : : ` ` swap ` ` does not currently support LABEL'''
ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' } on_ = __salt__ [ 'mount.swaps' ] ( ) if __salt__ [ 'file.is_link' ] ( name ) : real_swap_device = __salt__ [ 'file.readlink' ] ( name ) if not real_swap_device . startswith ( '/' ) : real_swap_device = '/dev/{0}' . format ( os ...
def print_task_help ( self , task , name ) : """Prints the help for the passed task with the passed name . : param task : the task function object : param name : the name of the module . : return : None"""
TerminalColor . set ( 'GREEN' ) print ( get_signature ( name , task ) ) # TODO : print the location does not work properly and sometimes returns None # print ( ' = > defined in : { } ' . format ( inspect . getsourcefile ( task ) ) ) help_msg = inspect . getdoc ( task ) or '' TerminalColor . reset ( ) print ( ' ' + he...
def datastruct_formater ( data , frequence = FREQUENCE . DAY , market_type = MARKET_TYPE . STOCK_CN , default_header = [ ] ) : """一个任意格式转化为DataStruct的方法 Arguments : data { [ type ] } - - [ description ] Keyword Arguments : frequence { [ type ] } - - [ description ] ( default : { FREQUENCE . DAY } ) market...
if isinstance ( data , list ) : try : res = pd . DataFrame ( data , columns = default_header ) if frequence is FREQUENCE . DAY : if market_type is MARKET_TYPE . STOCK_CN : return QA_DataStruct_Stock_day ( res . assign ( date = pd . to_datetime ( res . date ) ) . set_index...
def __check_logging_rules ( configuration ) : """Check that the logging values are proper"""
valid_log_levels = [ 'debug' , 'info' , 'warning' , 'error' ] if configuration [ 'logging' ] [ 'log_level' ] . lower ( ) not in valid_log_levels : print ( 'Log level must be one of {0}' . format ( ', ' . join ( valid_log_levels ) ) ) sys . exit ( 1 )
def eject ( self , auth_no_user_interaction = None ) : """Eject media from the device ."""
return self . _assocdrive . _M . Drive . Eject ( '(a{sv})' , filter_opt ( { 'auth.no_user_interaction' : ( 'b' , auth_no_user_interaction ) , } ) )
def ret ( eqdata , ** kwargs ) : """Generate a DataFrame where the sole column , ' Return ' , is the return for the equity over the given number of sessions . For example , if ' XYZ ' has ' Adj Close ' of ` 100.0 ` on 2014-12-15 and ` 90.0 ` 4 * sessions * later on 2014-12-19 , then the ' Return ' value for...
if 'outputcol' not in kwargs : kwargs [ 'outputcol' ] = 'Return' result = growth ( eqdata , ** kwargs ) result . values [ : , : ] -= 1. return result
def kde_peak ( self , name , npoints = _npoints , ** kwargs ) : """Calculate peak of kernel density estimator"""
data = self . get ( name , ** kwargs ) return kde_peak ( data , npoints )
def is_stationary ( self ) : r"""Whether the MSM is stationary , i . e . whether the initial distribution is the stationary distribution of the hidden transition matrix ."""
# for disconnected matrices , the stationary distribution depends on the estimator , so we can ' t compute # it directly . Therefore we test whether the initial distribution is stationary . return np . allclose ( np . dot ( self . _Pi , self . _Tij ) , self . _Pi )
def _add_chrome_proxy_extension ( chrome_options , proxy_string , proxy_user , proxy_pass ) : """Implementation of https : / / stackoverflow . com / a / 35293284 for https : / / stackoverflow . com / questions / 12848327/ ( Run Selenium on a proxy server that requires authentication . )"""
if not "" . join ( sys . argv ) == "-c" : # Single - threaded proxy_helper . create_proxy_zip ( proxy_string , proxy_user , proxy_pass ) else : # Pytest multi - threaded test lock = threading . Lock ( ) with lock : time . sleep ( random . uniform ( 0.02 , 0.15 ) ) if not os . path . exists (...
def configure_common_directories ( cls , tc_config_files ) : """Configure common config and output folders for all tests : param tc _ config _ files : test case specific config files"""
if cls . config_directory is None : # Get config directory from properties config_directory = cls . get_configured_value ( 'Config_directory' , tc_config_files . config_directory , 'conf' ) prop_filenames = cls . get_configured_value ( 'Config_prop_filenames' , tc_config_files . config_properties_filenames , 'p...
def get_all_vpn_gateways ( self , vpn_gateway_ids = None , filters = None ) : """Retrieve information about your VpnGateways . You can filter results to return information only about those VpnGateways that match your search parameters . Otherwise , all VpnGateways associated with your account are returned . ...
params = { } if vpn_gateway_ids : self . build_list_params ( params , vpn_gateway_ids , 'VpnGatewayId' ) if filters : i = 1 for filter in filters : params [ ( 'Filter.%d.Name' % i ) ] = filter [ 0 ] params [ ( 'Filter.%d.Value.1' ) ] = filter [ 1 ] i += 1 return self . get_list ( 'De...
def apply_dmaglim ( self , dmaglim = None ) : """Applies a constraint that sets the maximum brightness for non - target star : func : ` stars . StarPopulation . set _ dmaglim ` not yet implemented ."""
raise NotImplementedError if 'bright blend limit' not in self . constraints : self . constraints . append ( 'bright blend limit' ) for pop in self . poplist : if not hasattr ( pop , 'dmaglim' ) or pop . is_specific : continue if dmaglim is None : dmag = pop . dmaglim else : dmag ...
def present ( self , path , timeout = 0 ) : """returns True if there is an entity at path"""
ret , data = self . sendmess ( MSG_PRESENCE , str2bytez ( path ) , timeout = timeout ) assert ret <= 0 and not data , ( ret , data ) if ret < 0 : return False else : return True
def console_get_background_flag ( con : tcod . console . Console ) -> int : """Return this consoles current blend mode . Args : con ( Console ) : Any Console instance . . . deprecated : : 8.5 Check : any : ` Console . default _ bg _ blend ` instead ."""
return int ( lib . TCOD_console_get_background_flag ( _console ( con ) ) )
def save ( self , * args , ** kwargs ) : """Saves changes made on model instance if ` ` request ` ` or ` ` track _ token ` ` keyword are provided ."""
from tracked_model . models import History , RequestInfo if self . pk : action = ActionType . UPDATE changes = None else : action = ActionType . CREATE changes = serializer . dump_model ( self ) request = kwargs . pop ( 'request' , None ) track_token = kwargs . pop ( 'track_token' , None ) super ( ) . s...
def pquery ( self , x_list , k = 1 , eps = 0 , p = 2 , distance_upper_bound = np . inf ) : """Function to parallelly query the K - D Tree"""
x = np . array ( x_list ) nx , mx = x . shape shmem_x = mp . Array ( ctypes . c_double , nx * mx ) shmem_d = mp . Array ( ctypes . c_double , nx * k ) shmem_i = mp . Array ( ctypes . c_double , nx * k ) _x = shmem_as_nparray ( shmem_x ) . reshape ( ( nx , mx ) ) _d = shmem_as_nparray ( shmem_d ) . reshape ( ( nx , k ) ...
def on_response ( self , msg : Dict [ str , str ] ) -> None : """Run when get response from browser ."""
response = msg . get ( 'data' , False ) if response : task = self . __tasks . pop ( msg . get ( 'reqid' ) , False ) if task and not task . cancelled ( ) and not task . done ( ) : task . set_result ( msg . get ( 'data' ) )
def get_key_rotation_status ( key_id , region = None , key = None , keyid = None , profile = None ) : '''Get status of whether or not key rotation is enabled for a key . CLI example : : salt myminion boto _ kms . get _ key _ rotation _ status ' alias / mykey ' '''
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) r = { } try : key_rotation_status = conn . get_key_rotation_status ( key_id ) r [ 'result' ] = key_rotation_status [ 'KeyRotationEnabled' ] except boto . exception . BotoServerError as e : r [ 'error' ] = __utils__ [ 'boto....
def generate ( mnx_dump ) : """Annotate a shortlist of metabolites with cross - references using MetaNetX . MNX _ DUMP : The chemicals dump from MetaNetX usually called ' chem _ xref . tsv ' . Will be downloaded if it doesn ' t exist ."""
LOGGER . info ( "Read shortlist." ) targets = pd . read_table ( join ( dirname ( __file__ ) , "shortlist.tsv" ) ) if not exists ( mnx_dump ) : # Download the MetaNetX chemicals dump if it doesn ' t exists . # Download done as per https : / / stackoverflow . com / a / 16696317. LOGGER . info ( "MetaNetX dump '%s' do...
def rec_append_fields ( rec , names , arrs , dtypes = None ) : """Return a new record array with field names populated with data from arrays in * arrs * . If appending a single field , then * names * , * arrs * and * dtypes * do not have to be lists . They can just be the values themselves ."""
if ( not isstring ( names ) and iterable ( names ) and len ( names ) and isstring ( names [ 0 ] ) ) : if len ( names ) != len ( arrs ) : raise ValueError ( "number of arrays do not match number of names" ) else : # we have only 1 name and 1 array names = [ names ] arrs = [ arrs ] arrs = list ( map (...
def prj_save ( self ) : """Save the current project : returns : None : rtype : None : raises : None"""
if not self . cur_prj : return desc = self . prj_desc_pte . toPlainText ( ) semester = self . prj_semester_le . text ( ) fps = self . prj_fps_dsb . value ( ) resx = self . prj_res_x_sb . value ( ) resy = self . prj_res_y_sb . value ( ) scale = self . prj_scale_cb . currentText ( ) self . cur_prj . description = des...
def _make_tuple ( self , env ) : """Instantiate the Tuple based on this TupleNode ."""
t = runtime . Tuple ( self , env , dict2tuple ) # A tuple also provides its own schema spec schema = schema_spec_from_tuple ( t ) t . attach_schema ( schema ) return t
def full_update_params ( self , conn_method_name , params ) : """When a API method on the collection is called , this goes through the params & run a series of hooks to allow for updating those parameters . Typically , this method is * * NOT * * call by the user . However , the user may wish to define other m...
# We ' ll check for custom methods to do addition , specific work . custom_method_name = 'update_params_{0}' . format ( conn_method_name ) custom_method = getattr ( self , custom_method_name , None ) if custom_method : # Let the specific method further process the data . params = custom_method ( params ) # Now that...
def send_ready ( self ) : """Returns true if data can be written to this channel without blocking . This means the channel is either closed ( so any write attempt would return immediately ) or there is at least one byte of space in the outbound buffer . If there is at least one byte of space in the outbound...
self . lock . acquire ( ) try : if self . closed or self . eof_sent : return True return self . out_window_size > 0 finally : self . lock . release ( )
def to_dict ( self ) : """extract the data of the content and return it as a dictionary"""
# 1 . extract the schema fields data = self . extract_fields ( ) # 2 . include custom key - value pairs listed in the mapping dictionary for key , attr in self . attributes . iteritems ( ) : if key in self . ignore : continue # skip ignores # fetch the mapped attribute value = getattr ( self...
def isIdentity ( M , tol = 1e-06 ) : """Check if vtkMatrix4x4 is Identity ."""
for i in [ 0 , 1 , 2 , 3 ] : for j in [ 0 , 1 , 2 , 3 ] : e = M . GetElement ( i , j ) if i == j : if np . abs ( e - 1 ) > tol : return False elif np . abs ( e ) > tol : return False return True
def roughpage ( request , url ) : """Public interface to the rough page view ."""
if settings . APPEND_SLASH and not url . endswith ( '/' ) : # redirect to the url which have end slash return redirect ( url + '/' , permanent = True ) # get base filename from url filename = url_to_filename ( url ) # try to find the template _ filename with backends template_filenames = get_backend ( ) . prepare_f...
def bofh_excuse ( how_many = 1 ) : """Generate random BOFH themed technical excuses ! Args : how _ many : Number of excuses to generate . ( Default : 1) Returns : A list of BOFH excuses ."""
excuse_path = os . path . join ( os . path . dirname ( __file__ ) , 'bofh_excuses.json' ) with open ( excuse_path , 'r' ) as _f : excuse_dict = json . load ( _f ) return [ generate_random_string ( excuse_dict ) for _ in range ( int ( how_many ) ) ]
def pstdev ( data , mu = None ) : """Return the square root of the population variance . See ` ` pvariance ` ` for arguments and other details ."""
var = pvariance ( data , mu ) try : return var . sqrt ( ) except AttributeError : return math . sqrt ( var )
def diff ( self , dt = None , abs = True ) : """Returns the difference between two Date objects as a Period . : type dt : Date or None : param abs : Whether to return an absolute interval or not : type abs : bool : rtype : Period"""
if dt is None : dt = self . today ( ) return Period ( self , Date ( dt . year , dt . month , dt . day ) , absolute = abs )
def devpiserver_cmdline_run ( xom ) : '''Load theme when ` theme ` parameter is ' semantic - ui ' .'''
if xom . config . args . theme == 'semantic-ui' : xom . config . args . theme = resource_filename ( 'devpi_semantic_ui' , '' ) xom . log . info ( "Semantic UI Theme loaded" )
def write_backup_state_to_json_file ( self ) : """Periodically write a JSON state file to disk"""
start_time = time . time ( ) state_file_path = self . config [ "json_state_file_path" ] self . state [ "walreceivers" ] = { key : { "latest_activity" : value . latest_activity , "running" : value . running , "last_flushed_lsn" : value . last_flushed_lsn } for key , value in self . walreceivers . items ( ) } self . stat...
def get_active_for ( self , user , user_agent = _MARK , ip_address = _MARK ) : """Return last known session for given user . : param user : user session : type user : ` abilian . core . models . subjects . User ` : param user _ agent : * exact * user agent string to lookup , or ` None ` to have user _ agent...
conditions = [ LoginSession . user == user ] if user_agent is not _MARK : if user_agent is None : user_agent = request . environ . get ( "HTTP_USER_AGENT" , "" ) conditions . append ( LoginSession . user_agent == user_agent ) if ip_address is not _MARK : if ip_address is None : ip_addresses ...
def setwrap ( value : Any ) -> Set [ str ] : """Returns a flattened and stringified set from the given object or iterable . For use in public functions which accept argmuents or kwargs that can be one object or a list of objects ."""
return set ( map ( str , set ( flatten ( [ value ] ) ) ) )
def pretty_printer_factory ( p_todolist , p_additional_filters = None ) : """Returns a pretty printer suitable for the ls and dep subcommands ."""
p_additional_filters = p_additional_filters or [ ] printer = PrettyPrinter ( ) printer . add_filter ( PrettyPrinterNumbers ( p_todolist ) ) for ppf in p_additional_filters : printer . add_filter ( ppf ) # apply colors at the last step , the ANSI codes may confuse the # preceding filters . printer . add_filter ( Pre...
def fit ( self , X , y = None , ** kwargs ) : """Fits the model and generates the silhouette visualization ."""
# TODO : decide to use this method or the score method to draw . # NOTE : Probably this would be better in score , but the standard score # is a little different and I ' m not sure how it ' s used . # Fit the wrapped estimator self . estimator . fit ( X , y , ** kwargs ) # Get the properties of the dataset self . n_sam...
def read_settings ( self , configfile ) : '''Reads the settings from the ec2 . ini file'''
if six . PY3 : config = configparser . ConfigParser ( ) else : config = configparser . SafeConfigParser ( ) config . read ( configfile ) # is eucalyptus ? self . eucalyptus_host = None self . eucalyptus = False if config . has_option ( 'ec2' , 'eucalyptus' ) : self . eucalyptus = config . getboolean ( 'ec2'...
def _match ( self , struct1 , struct2 , fu , s1_supercell = True , use_rms = False , break_on_match = False ) : """Matches one struct onto the other"""
ratio = fu if s1_supercell else 1 / fu if len ( struct1 ) * ratio >= len ( struct2 ) : return self . _strict_match ( struct1 , struct2 , fu , s1_supercell = s1_supercell , break_on_match = break_on_match , use_rms = use_rms ) else : return self . _strict_match ( struct2 , struct1 , fu , s1_supercell = ( not s1_...
def precision_recall_by_user ( observed_user_items , recommendations , cutoffs = [ 10 ] ) : """Compute precision and recall at a given cutoff for each user . In information retrieval terms , precision represents the ratio of relevant , retrieved items to the number of relevant items . Recall represents the rati...
assert type ( observed_user_items ) == _SFrame assert type ( recommendations ) == _SFrame assert type ( cutoffs ) == list assert min ( cutoffs ) > 0 , "All cutoffs must be positive integers." assert recommendations . num_columns ( ) >= 2 user_id = recommendations . column_names ( ) [ 0 ] item_id = recommendations . col...
def _get_conn ( ret = None ) : '''Return a MSSQL connection .'''
_options = _get_options ( ret ) dsn = _options . get ( 'dsn' ) user = _options . get ( 'user' ) passwd = _options . get ( 'passwd' ) return pyodbc . connect ( 'DSN={0};UID={1};PWD={2}' . format ( dsn , user , passwd ) )
def show_tree ( self , cachelim = np . inf ) : """Cachelim is in Mb . For any cached jacobians above cachelim , they are also added to the graph ."""
import tempfile import subprocess assert DEBUG , "Please use dr tree visualization functions in debug mode" def string_for ( self , my_name ) : if hasattr ( self , 'label' ) : my_name = self . label my_name = '%s (%s)' % ( my_name , str ( self . __class__ . __name__ ) ) result = [ ] if not hasat...
def posterior_predictive_to_xarray ( self ) : """Convert posterior _ predictive samples to xarray ."""
data = { k : np . expand_dims ( v , 0 ) for k , v in self . posterior_predictive . items ( ) } return dict_to_dataset ( data , library = self . pymc3 , coords = self . coords , dims = self . dims )
def generate_password ( length = 8 , lower = True , upper = True , number = True ) : """generates a simple password . We should not really use this in production . : param length : the length of the password : param lower : True of lower case characters are allowed : param upper : True if upper case character...
lletters = "abcdefghijklmnopqrstuvwxyz" uletters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # This doesn ' t guarantee both lower and upper cases will show up alphabet = lletters + uletters digit = "0123456789" mypw = "" def _random_character ( texts ) : return texts [ random . randrange ( len ( texts ) ) ] if not lower : ...
def exception ( self ) : """: return : the StreamingQueryException if the query was terminated by an exception , or None ."""
if self . _jsq . exception ( ) . isDefined ( ) : je = self . _jsq . exception ( ) . get ( ) msg = je . toString ( ) . split ( ': ' , 1 ) [ 1 ] # Drop the Java StreamingQueryException type info stackTrace = '\n\t at ' . join ( map ( lambda x : x . toString ( ) , je . getStackTrace ( ) ) ) return Stre...
def delta ( self , date_from = None , date_format = None , days = 0 , hours = 0 , minutes = 0 , seconds = 0 , days_range = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] ) : """Retourne la date courante ou depuis une date fournie moins un delta et étant autorisé dans une plage de jour ( lundi = 1 . . . dimanche = 7) : param :...
# check des jours autorisés range_correct = False for i in range ( 1 , 8 ) : if i in days_range : # au moins un jour autorisé est correcte ( de 1 à 7) range_correct = True # si aucun jour dans days _ range ne correspond à jour réel , # on affecte un défaut if not range_correct : days_range = [ i f...
def reply_cached_media ( self , file_id : str , quote : bool = None , caption : str = "" , parse_mode : str = "" , disable_notification : bool = None , reply_to_message_id : int = None , reply_markup : Union [ "pyrogram.InlineKeyboardMarkup" , "pyrogram.ReplyKeyboardMarkup" , "pyrogram.ReplyKeyboardRemove" , "pyrogram....
if quote is None : quote = self . chat . type != "private" if reply_to_message_id is None and quote : reply_to_message_id = self . message_id return self . _client . send_cached_media ( chat_id = self . chat . id , file_id = file_id , caption = caption , parse_mode = parse_mode , disable_notification = disable_...
def tag_myself ( project = 'cwc' , ** other_tags ) : """Function run when indra is used in an EC2 instance to apply tags ."""
base_url = "http://169.254.169.254" try : resp = requests . get ( base_url + "/latest/meta-data/instance-id" ) except requests . exceptions . ConnectionError : logger . warning ( "Could not connect to service. Note this should only " "be run from within a batch job." ) return instance_id = resp . text tag_i...
def install ( ** kwargs ) : """Install the pre - commit hook ."""
force = kwargs . get ( 'force' ) preserve_legacy = kwargs . get ( 'preserve_legacy' ) colorama . init ( strip = kwargs . get ( 'no_color' ) ) stdout = subprocess . check_output ( 'which therapist' , shell = True ) therapist_bin = stdout . decode ( 'utf-8' ) . split ( ) [ 0 ] git_dir = current_git_dir ( ) if git_dir is ...
def _get_url_datafiles ( url_db_view , url_db_content , mrio_regex , access_cookie = None ) : """Urls of mrio files by parsing url content for mrio _ regex Parameters url _ db _ view : url str Url which shows the list of mrios in the db url _ db _ content : url str Url which needs to be appended before th...
# Use post here - NB : get could be necessary for some other pages # but currently works for wiod and eora returnvalue = namedtuple ( 'url_content' , [ 'raw_text' , 'data_urls' ] ) url_text = requests . post ( url_db_view , cookies = access_cookie ) . text data_urls = [ url_db_content + ff for ff in re . findall ( mrio...
def execute_command ( self , cmd , params = None , callback = None , raw = False ) : '''Execute a command and return a parsed response .'''
def execute_with_callbacks ( cmd , params = None , callback = None , raw = False ) : code , params = self . send_command ( cmd , params , raw ) if callback : callback ( code , params ) return code , params if self . daemon : t = Thread ( target = execute_with_callbacks , args = ( cmd , ) , kwarg...
def parse_qtype ( self , param_type , param_value ) : '''parse type of quniform or qloguniform'''
if param_type == 'quniform' : return self . _parse_quniform ( param_value ) if param_type == 'qloguniform' : param_value [ : 2 ] = np . log ( param_value [ : 2 ] ) return list ( np . exp ( self . _parse_quniform ( param_value ) ) ) raise RuntimeError ( "Not supported type: %s" % param_type )
def _set_level1_into_level2 ( self , v , load = False ) : """Setter method for level1 _ into _ level2 , mapped from YANG variable / routing _ system / router / isis / router _ isis _ cmds _ holder / address _ family / ipv6 / af _ ipv6 _ unicast / af _ ipv6 _ attributes / af _ common _ attributes / redistribute / is...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = level1_into_level2 . level1_into_level2 , is_container = 'container' , presence = False , yang_name = "level1-into-level2" , rest_name = "level-2" , parent = self , path_helper = self . _path_helper , extmethods = self . _ext...
def invert ( self , nz , A , C ) : """Inversion and resolution of a tridiagonal matrix A X = C Input : nz number of layers a ( * , 1 ) lower diagonal ( Ai , i - 1) a ( * , 2 ) principal diagonal ( Ai , i ) a ( * , 3 ) upper diagonal ( Ai , i + 1) Output x results"""
X = [ 0 for i in range ( nz ) ] for i in reversed ( range ( nz - 1 ) ) : C [ i ] = C [ i ] - A [ i ] [ 2 ] * C [ i + 1 ] / A [ i + 1 ] [ 1 ] A [ i ] [ 1 ] = A [ i ] [ 1 ] - A [ i ] [ 2 ] * A [ i + 1 ] [ 0 ] / A [ i + 1 ] [ 1 ] for i in range ( 1 , nz , 1 ) : C [ i ] = C [ i ] - A [ i ] [ 0 ] * C [ i - 1 ] /...
def open_report_template_path ( self ) : """Open File dialog to choose the report template path ."""
# noinspection PyCallByClass , PyTypeChecker directory_name = QFileDialog . getExistingDirectory ( self , self . tr ( 'Templates directory' ) , self . leReportTemplatePath . text ( ) , QFileDialog . ShowDirsOnly ) if directory_name : self . leReportTemplatePath . setText ( directory_name )
def save ( self , unsave = False ) : """Save the object . : returns : The json response from the server ."""
url = self . reddit_session . config [ 'unsave' if unsave else 'save' ] data = { 'id' : self . fullname , 'executed' : 'unsaved' if unsave else 'saved' } response = self . reddit_session . request_json ( url , data = data ) self . reddit_session . evict ( self . reddit_session . config [ 'saved' ] ) return response
def main ( ) : """Main function . Mostly parsing the command line arguments ."""
parser = argparse . ArgumentParser ( ) parser . add_argument ( '--backend' , choices = [ 'gatttool' , 'bluepy' , 'pygatt' ] , default = 'gatttool' ) parser . add_argument ( '-v' , '--verbose' , action = 'store_const' , const = True ) subparsers = parser . add_subparsers ( help = 'sub-command help' , ) parser_poll = sub...
def build_foreach ( self , component , runnable , foreach , name_mappings = { } ) : """Iterate over ForEach constructs and process nested elements . @ param component : Component model containing structure specifications . @ type component : lems . model . component . FatComponent @ param runnable : Runnable ...
if self . debug : print ( "\n++++++++ Calling build_foreach of %s with runnable %s, parent %s, name_mappings: %s" % ( component . id , runnable . id , runnable . parent , name_mappings ) ) target_array = runnable . resolve_path ( foreach . instances ) for target_runnable in target_array : if self . debug : ...
def add_months ( self , datetimestr , n , return_date = False ) : """Returns a time that n months after a time . Notice : for example , the date that one month after 2015-01-31 supposed to be 2015-02-31 . But there ' s no 31th in Feb , so we fix that value to 2015-02-28. : param datetimestr : a datetime obj...
a_datetime = self . parse_datetime ( datetimestr ) month_from_ordinary = a_datetime . year * 12 + a_datetime . month month_from_ordinary += n year , month = divmod ( month_from_ordinary , 12 ) try : a_datetime = datetime ( year , month , a_datetime . day , a_datetime . hour , a_datetime . minute , a_datetime . seco...
def delivery_stats ( self ) : '''Returns a summary of inactive emails and bounces by type .'''
self . _check_values ( ) req = Request ( __POSTMARK_URL__ + 'deliverystats' , None , { 'Accept' : 'application/json' , 'Content-Type' : 'application/json' , 'X-Postmark-Server-Token' : self . __api_key , 'User-agent' : self . __user_agent } ) # Attempt send try : # print ' sending request to postmark : ' result = u...
def get_review_sh ( self , revision , item ) : """Add sorting hat enrichment fields for the author of the revision"""
identity = self . get_sh_identity ( revision ) update = parser . parse ( item [ self . get_field_date ( ) ] ) erevision = self . get_item_sh_fields ( identity , update ) return erevision
def from_jd ( jd ) : '''Calculate Bahai date from Julian day'''
jd = trunc ( jd ) + 0.5 g = gregorian . from_jd ( jd ) gy = g [ 0 ] bstarty = EPOCH_GREGORIAN_YEAR if jd <= gregorian . to_jd ( gy , 3 , 20 ) : x = 1 else : x = 0 # verify this next line . . . bys = gy - ( bstarty + ( ( ( gregorian . to_jd ( gy , 1 , 1 ) <= jd ) and x ) ) ) year = bys + 1 days = jd - to_jd ( ye...
def get_cfg ( ast_func ) : """Traverses the AST and returns the corresponding CFG : param ast _ func : The AST representation of function : type ast _ func : ast . Function : returns : The CFG representation of the function : rtype : cfg . Function"""
cfg_func = cfg . Function ( ) for ast_var in ast_func . input_variable_list : cfg_var = cfg_func . get_variable ( ast_var . name ) cfg_func . add_input_variable ( cfg_var ) for ast_var in ast_func . output_variable_list : cfg_var = cfg_func . get_variable ( ast_var . name ) cfg_func . add_output_variabl...
def get_sequence_rules_for_assessment_part ( self , assessment_part_id ) : """Gets a ` ` SequenceRuleList ` ` for the given source assessment part . arg : assessment _ part _ id ( osid . id . Id ) : an assessment part ` ` Id ` ` return : ( osid . assessment . authoring . SequenceRuleList ) - the returned ` ...
# Implemented from template for # osid . learning . ActivityLookupSession . get _ activities _ for _ objective _ template # NOTE : This implementation currently ignores plenary view collection = JSONClientValidated ( 'assessment_authoring' , collection = 'SequenceRule' , runtime = self . _runtime ) result = collection ...
def multi_process_pynac ( file_list , pynac_func , num_iters = 100 , max_workers = 8 ) : """Use a ProcessPool from the ` ` concurrent . futures ` ` module to execute ` ` num _ iters ` ` number of instances of ` ` pynac _ func ` ` . This function takes advantage of ` ` do _ single _ dynac _ process ` ` and ` ` p...
with ProcessPoolExecutor ( max_workers = max_workers ) as executor : tasks = [ executor . submit ( do_single_dynac_process , num , file_list , pynac_func ) for num in range ( num_iters ) ] exc = [ task . exception ( ) for task in tasks if task . exception ( ) ] if exc : return exc else : return "No errors e...
def merge_adjacent ( dom , tag_name ) : """Merge all adjacent tags with the specified tag name . Return the number of merges performed ."""
for node in dom . getElementsByTagName ( tag_name ) : prev_sib = node . previousSibling if prev_sib and prev_sib . nodeName == node . tagName : for child in list ( node . childNodes ) : prev_sib . appendChild ( child ) remove_node ( node )
def info_player_id ( self , name ) : '''Get id using name football player'''
number = 0 name = name . title ( ) . replace ( " " , "+" ) headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/plain" , 'Referer' : 'http://' + self . domain + '/team_news.phtml' , "User-Agent" : user_agent } req = self . session . get ( 'http://stats.comunio.es/search.php?name=' + name ...
def is_stream_handler ( self , request ) : """Handler for request is stream or not . : param request : Request object : return : bool"""
handler = self . get ( request ) [ 0 ] if ( hasattr ( handler , 'view_class' ) and hasattr ( handler . view_class , request . method . lower ( ) ) ) : handler = getattr ( handler . view_class , request . method . lower ( ) ) return hasattr ( handler , 'is_stream' )
def cols_to_dt ( df , col_list , set_format = None , infer_format = True , dest = False ) : """Coerces a list of columns to datetime Parameters : df - DataFrame DataFrame to operate on col _ list - list of strings names of columns to coerce dest - bool , default False Whether to apply the result to th...
if not dest : return _pd . DataFrame ( { col_name : col_to_dt ( df , col_name , set_format , infer_format ) for col_name in col_list } ) for col_name in col_list : col_to_dt ( df , col_name , set_format , infer_format , dest )
def get_meta ( collection ) : """Return the meta - description of a given resource . : param collection : The collection to get meta - info for"""
cls = endpoint_class ( collection ) description = cls . meta ( ) return jsonify ( description )
def get_lastfm ( ) : """Returns the lastfm360k dataset , downloading locally if necessary . Returns a tuple of ( artistids , userids , plays ) where plays is a CSR matrix"""
filename = os . path . join ( _download . LOCAL_CACHE_DIR , "lastfm_360k.hdf5" ) if not os . path . isfile ( filename ) : log . info ( "Downloading dataset to '%s'" , filename ) _download . download_file ( URL , filename ) else : log . info ( "Using cached dataset at '%s'" , filename ) with h5py . File ( fi...
def _pop_params ( cls , kwargs ) : """Pop entries from the ` kwargs ` passed to cls . _ _ new _ _ based on the values in ` cls . params ` . Parameters kwargs : dict The kwargs passed to cls . _ _ new _ _ . Returns params : list [ ( str , object ) ] A list of string , value pairs containing the entries...
params = cls . params if not isinstance ( params , Mapping ) : params = { k : NotSpecified for k in params } param_values = [ ] for key , default_value in params . items ( ) : try : value = kwargs . pop ( key , default_value ) if value is NotSpecified : raise KeyError ( key ) ...
async def get_stats ( self , battletag : str , regions = ( EUROPE , KOREA , AMERICAS , CHINA , JAPAN , ANY ) , platform = None , _session = None , handle_ratelimit = None , max_tries = None , request_timeout = None ) : """Returns the stats for the profiles on the specified regions and platform . The format for regi...
if platform is None : platform = self . default_platform try : blob_dict = await self . _base_request ( battletag , "stats" , _session , platform = platform , handle_ratelimit = handle_ratelimit , max_tries = max_tries , request_timeout = request_timeout ) except ProfileNotFoundError as e : # The battletag does...
def get_pb_ids ( self ) -> List [ str ] : """Return the list of PB ids associated with the SBI . Returns : list , Processing block ids"""
values = DB . get_hash_value ( self . _key , 'processing_block_ids' ) return ast . literal_eval ( values )
def is_volatile ( type_ ) : """returns True , if type represents C + + volatile type , False otherwise"""
nake_type = remove_alias ( type_ ) if isinstance ( nake_type , cpptypes . volatile_t ) : return True elif isinstance ( nake_type , cpptypes . const_t ) : return is_volatile ( nake_type . base ) elif isinstance ( nake_type , cpptypes . array_t ) : return is_volatile ( nake_type . base ) return False
def get_against ( ) : """Determines the revision against which the staged data ought to be checked . : returns : The revision . : rtype : : class : ` str `"""
global __cached_against if __cached_against is not None : return __cached_against status = subprocess . call ( [ "git" , "rev-parse" , "--verify" , "HEAD" ] , stdout = open ( os . devnull , 'w' ) , stderr = subprocess . STDOUT ) if not status : against = 'HEAD' else : # Initial commit : diff against an empty tr...
def delete ( self , username , realm = None ) : """Delete a storage password by username and / or realm . The identifier can be passed in through the username parameter as < username > or < realm > : < username > , but the preferred way is by passing in the username and realm parameters . : param username :...
if realm is None : # This case makes the username optional , so # the full name can be passed in as realm . # Assume it ' s already encoded . name = username else : # Encode each component separately name = UrlEncoded ( realm , encode_slash = True ) + ":" + UrlEncoded ( username , encode_slash = True ) # Append...
def dijkstra ( graph , weight , source = 0 , target = None ) : """single source shortest paths by Dijkstra : param graph : directed graph in listlist or listdict format : param weight : in matrix format or same listdict graph : assumes : weights are non - negative : param source : source vertex : type sou...
n = len ( graph ) assert all ( weight [ u ] [ v ] >= 0 for u in range ( n ) for v in graph [ u ] ) prec = [ None ] * n black = [ False ] * n dist = [ float ( 'inf' ) ] * n dist [ source ] = 0 heap = [ ( 0 , source ) ] while heap : dist_node , node = heappop ( heap ) # Closest node from source if not black [...
def to_bytes ( self , request = None ) : '''Called to transform the collection of ` ` streams ` ` into the content string . This method can be overwritten by derived classes . : param streams : a collection ( list or dictionary ) containing ` ` strings / bytes ` ` used to build the final ` ` string / bytes ...
data = bytearray ( ) for chunk in self . stream ( request ) : if isinstance ( chunk , str ) : chunk = chunk . encode ( self . charset ) data . extend ( chunk ) return bytes ( data )
def read_srml_month_from_solardat ( station , year , month , filetype = 'PO' ) : """Request a month of SRML [ 1 ] data from solardat and read it into a Dataframe . Parameters station : str The name of the SRML station to request . year : int Year to request data for month : int Month to request data...
file_name = "{station}{filetype}{year:02d}{month:02d}.txt" . format ( station = station , filetype = filetype , year = year % 100 , month = month ) url = "http://solardat.uoregon.edu/download/Archive/" data = read_srml ( url + file_name ) return data