signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def info ( docgraph ) : """print node and edge statistics of a document graph"""
print networkx . info ( docgraph ) , '\n' node_statistics ( docgraph ) print edge_statistics ( docgraph )
def save_weights ( weights_list , filename ) : """Save the model weights to the given filename using numpy ' s " . npz " format . Parameters weights _ list : list of array filename : string Should end in " . npz " ."""
numpy . savez ( filename , ** dict ( ( ( "array_%d" % i ) , w ) for ( i , w ) in enumerate ( weights_list ) ) )
def create_all_recommendations ( self , cores , ip_views = False ) : """Calculate the recommendations for all records ."""
global _store _store = self . store _create_all_recommendations ( cores , ip_views , self . config )
def upvote_num ( self ) : """čŽ·å–ę”¶åˆ°ēš„ēš„čµžåŒę•°é‡ . : return : ę”¶åˆ°ēš„ēš„čµžåŒę•°é‡ : rtype : int"""
if self . url is None : return 0 else : number = int ( self . soup . find ( 'span' , class_ = 'zm-profile-header-user-agree' ) . strong . text ) return number
def check_exclude_rec ( self ) : # pylint : disable = access - member - before - definition """Check if this timeperiod is tagged : return : if tagged return false , if not true : rtype : bool"""
if self . rec_tag : msg = "[timeentry::%s] is in a loop in exclude parameter" % ( self . get_name ( ) ) self . add_error ( msg ) return False self . rec_tag = True for timeperiod in self . exclude : timeperiod . check_exclude_rec ( ) return True
def _check_for_dictionary_key ( self , logical_id , dictionary , keys ) : """Checks a dictionary to make sure it has a specific key . If it does not , an InvalidResourceException is thrown . : param string logical _ id : logical id of this resource : param dict dictionary : the dictionary to check : param l...
for key in keys : if key not in dictionary : raise InvalidResourceException ( logical_id , 'Resource is missing the required [{}] ' 'property.' . format ( key ) )
def load_file ( path ) : """Open a file on your local drive , using its extension to guess its type . This routine only works on ` ` . bsp ` ` ephemeris files right now , but will gain support for additional file types in the future . : : from skyfield . api import load _ file planets = load _ file ( ' ~ / ...
path = os . path . expanduser ( path ) base , ext = os . path . splitext ( path ) if ext == '.bsp' : return SpiceKernel ( path ) raise ValueError ( 'unrecognized file extension: {}' . format ( path ) )
def strategy ( self , * names , ** kwargs ) : """StrategyDict wrapping method for adding a new strategy . Parameters * names : Positional arguments with all names ( strings ) that could be used to call the strategy to be added , to be used both as key items and as attribute names . keep _ name : Boole...
def decorator ( func ) : keep_name = kwargs . pop ( "keep_name" , False ) if kwargs : key = next ( iter ( kwargs ) ) raise TypeError ( "Unknown keyword argument '{}'" . format ( key ) ) if not keep_name : func . __name__ = str ( names [ 0 ] ) self [ names ] = func return self...
def IsBinary ( self , filename ) : """Returns true if the guessed mimetyped isnt ' t in text group ."""
mimetype = mimetypes . guess_type ( filename ) [ 0 ] if not mimetype : return False # e . g . README , " real " binaries usually have an extension # special case for text files which don ' t start with text / if mimetype in TEXT_MIMETYPES : return False return not mimetype . startswith ( "text/" )
def can_update_asset_contents ( self , asset_id = None ) : """Tests if this user can update ` ` AssetContent ` ` . A return of true does not guarantee successful authorization . A return of false indicates that it is known updating an ` ` AssetContent ` ` will result in a ` ` PermissionDenied ` ` . This is ...
url_path = construct_url ( 'authorization' , bank_id = self . _catalog_idstr ) return self . _get_request ( url_path ) [ 'assetHints' ] [ 'canUpdate' ]
def delete ( self , block_type , block_num ) : """Deletes a block : param block _ type : Type of block : param block _ num : Bloc number"""
logger . info ( "deleting block" ) blocktype = snap7 . snap7types . block_types [ block_type ] result = self . library . Cli_Delete ( self . pointer , blocktype , block_num ) return result
def show_terms_if_not_agreed ( context , field = TERMS_HTTP_PATH_FIELD ) : """Displays a modal on a current page if a user has not yet agreed to the given terms . If terms are not specified , the default slug is used . A small snippet is included into your template if a user who requested the view has not yet...
request = context [ 'request' ] url = urlparse ( request . META [ field ] ) not_agreed_terms = TermsAndConditions . get_active_terms_not_agreed_to ( request . user ) if not_agreed_terms and is_path_protected ( url . path ) : return { 'not_agreed_terms' : not_agreed_terms , 'returnTo' : url . path } else : retur...
def _load_equipment_data ( self ) : """Load equipment data for transformers , cables etc . Returns : obj : ` dict ` of : pandas : ` pandas . DataFrame < dataframe > `"""
package_path = edisgo . __path__ [ 0 ] equipment_dir = self . config [ 'system_dirs' ] [ 'equipment_dir' ] data = { } equipment = { 'mv' : [ 'trafos' , 'lines' , 'cables' ] , 'lv' : [ 'trafos' , 'cables' ] } for voltage_level , eq_list in equipment . items ( ) : for i in eq_list : equipment_parameters = sel...
def datagramReceived ( self , datagram , address ) : """After receiving a datagram , generate the deferreds and add myself to it ."""
def write ( result ) : print "Writing %r" % result self . transport . write ( result , address ) d = self . d ( ) # d . addCallbacks ( write , log . err ) d . addCallback ( write ) # errors are silently ignored ! d . callback ( datagram )
def query_all ( ** kwargs ) : '''query all the posts .'''
kind = kwargs . get ( 'kind' , '1' ) limit = kwargs . get ( 'limit' , 10 ) return TabPost . select ( ) . where ( ( TabPost . kind == kind ) & ( TabPost . valid == 1 ) ) . order_by ( TabPost . time_update . desc ( ) ) . limit ( limit )
def _init_v ( self , t , w0 , dt ) : """Leapfrog updates the velocities offset a half - step from the position updates . If we ' re given initial conditions aligned in time , e . g . the positions and velocities at the same 0th step , then we have to initially scoot the velocities forward by a half step to ...
# here is where we scoot the velocity at t = t1 to v ( t + 1/2) F0 = self . F ( t . copy ( ) , w0 . copy ( ) , * self . _func_args ) a0 = F0 [ self . ndim : ] v_1_2 = w0 [ self . ndim : ] + a0 * dt / 2. return v_1_2
def request ( self , path , method = 'GET' , headers = None , ** kwargs ) : """Perform a HTTP request . Given a relative Bugzilla URL path , an optional request method , and arguments suitable for requests . Request ( ) , perform a HTTP request ."""
headers = { } if headers is None else headers . copy ( ) headers [ "User-Agent" ] = "Bugsy" kwargs [ 'headers' ] = headers url = '%s/%s' % ( self . bugzilla_url , path ) return self . _handle_errors ( self . session . request ( method , url , ** kwargs ) )
def _execute ( self , native , command , data = None , returning = True , mapper = dict ) : """Executes the inputted command into the current connection cursor . : param command | < str > data | < dict > | | None : return [ { < str > key : < variant > , . . } , . . ] , < int > count"""
if data is None : data = { } with native . cursor ( ) as cursor : log . debug ( '***********************' ) log . debug ( command % data ) log . debug ( '***********************' ) try : rowcount = 0 for cmd in command . split ( ';' ) : cmd = cmd . strip ( ) i...
def clone ( self , ** kw ) : """Return a new instance with specified attributes changed . The new instance has the same attribute values as the current object , except for the changes passed in as keyword arguments ."""
newpolicy = self . __class__ . __new__ ( self . __class__ ) for attr , value in self . __dict__ . items ( ) : object . __setattr__ ( newpolicy , attr , value ) for attr , value in kw . items ( ) : if not hasattr ( self , attr ) : raise TypeError ( "{!r} is an invalid keyword argument for {}" . format ( ...
def notify ( self , notices ) : """Send notifications to the users via . the provided methods Args : notices ( : obj : ` dict ` of ` str ` : ` dict ` ) : List of the notifications to send Returns : ` None `"""
issues_html = get_template ( 'unattached_ebs_volume.html' ) issues_text = get_template ( 'unattached_ebs_volume.txt' ) for recipient , issues in list ( notices . items ( ) ) : if issues : message_html = issues_html . render ( issues = issues ) message_text = issues_text . render ( issues = issues ) ...
def flex_api ( self ) : """Access the FlexApi Twilio Domain : returns : FlexApi Twilio Domain : rtype : twilio . rest . flex _ api . FlexApi"""
if self . _flex_api is None : from twilio . rest . flex_api import FlexApi self . _flex_api = FlexApi ( self ) return self . _flex_api
def HandleGetBlocksMessageReceived ( self , payload ) : """Process a GetBlocksPayload payload . Args : payload ( neo . Network . Payloads . GetBlocksPayload ) :"""
if not self . leader . ServiceEnabled : return inventory = IOHelper . AsSerializableWithType ( payload , 'neo.Network.Payloads.GetBlocksPayload.GetBlocksPayload' ) if not inventory : return blockchain = BC . Default ( ) hash = inventory . HashStart [ 0 ] if not blockchain . GetHeader ( hash ) : return hashe...
def main ( argv = None ) : """Main program entry point for parsing command line arguments"""
parser = argparse . ArgumentParser ( description = "Benchmark driver" ) parser . add_argument ( "--max-records" , type = int , default = 100 * 1000 ) parser . add_argument ( "--engine" , type = str , choices = ( "vcfpy" , "pyvcf" ) , default = "vcfpy" ) parser . add_argument ( "--input-vcf" , type = str , required = Tr...
def get_changes ( self , fixer = str . lower , task_handle = taskhandle . NullTaskHandle ( ) ) : """Fix module names ` fixer ` is a function that takes and returns a ` str ` . Given the name of a module , it should return the fixed name ."""
stack = changestack . ChangeStack ( self . project , 'Fixing module names' ) jobset = task_handle . create_jobset ( 'Fixing module names' , self . _count_fixes ( fixer ) + 1 ) try : while True : for resource in self . _tobe_fixed ( fixer ) : jobset . started_job ( resource . path ) r...
def get_object_data ( self , ref ) : """As get _ object _ header , but returns object data as well : return : ( hexsha , type _ string , size _ as _ int , data _ string ) : note : not threadsafe"""
hexsha , typename , size , stream = self . stream_object_data ( ref ) data = stream . read ( size ) del ( stream ) return ( hexsha , typename , size , data )
def get_comments_by_ids ( self , comment_ids ) : """Gets a ` ` CommentList ` ` corresponding to the given ` ` IdList ` ` . arg : comment _ ids ( osid . id . IdList ) : the list of ` ` Ids ` ` to retrieve return : ( osid . commenting . CommentList ) - the returned ` ` Comment list ` ` raise : NotFound - an...
# Implemented from template for # osid . resource . ResourceLookupSession . get _ resources _ by _ ids # NOTE : This implementation currently ignores plenary view collection = JSONClientValidated ( 'commenting' , collection = 'Comment' , runtime = self . _runtime ) object_id_list = [ ] for i in comment_ids : object...
def cat_trials ( x3d ) : """Concatenate trials along time axis . Parameters x3d : array , shape ( t , m , n ) Segmented input data with t trials , m signals , and n samples . Returns x2d : array , shape ( m , t * n ) Trials are concatenated along the second axis . See also cut _ segments : Cut segme...
x3d = atleast_3d ( x3d ) t = x3d . shape [ 0 ] return np . concatenate ( np . split ( x3d , t , 0 ) , axis = 2 ) . squeeze ( 0 )
def basic_animation ( frames = 100 , interval = 30 ) : """Plot a basic sine wave with oscillating amplitude"""
fig = plt . figure ( ) ax = plt . axes ( xlim = ( 0 , 10 ) , ylim = ( - 2 , 2 ) ) line , = ax . plot ( [ ] , [ ] , lw = 2 ) x = np . linspace ( 0 , 10 , 1000 ) def init ( ) : line . set_data ( [ ] , [ ] ) return line , def animate ( i ) : y = np . cos ( i * 0.02 * np . pi ) * np . sin ( x - i * 0.02 * np . ...
def result_report_class_wise_average ( self ) : """Report class - wise averages Returns str result report in string format"""
results = self . results_class_wise_average_metrics ( ) output = self . ui . section_header ( 'Class-wise average metrics (macro-average)' , indent = 2 ) + '\n' if 'f_measure' in results and results [ 'f_measure' ] : if results [ 'f_measure' ] [ 'f_measure' ] is not None : f_measure = results [ 'f_measure' ...
def set_exp ( self , claim = 'exp' , from_time = None , lifetime = None ) : """Updates the expiration time of a token ."""
if from_time is None : from_time = self . current_time if lifetime is None : lifetime = self . lifetime self . payload [ claim ] = datetime_to_epoch ( from_time + lifetime )
def _proxy ( self ) : """Generate an instance context for the instance , the context is capable of performing various actions . All instance actions are proxied to the context : returns : EngagementContextContext for this EngagementContextInstance : rtype : twilio . rest . studio . v1 . flow . engagement . en...
if self . _context is None : self . _context = EngagementContextContext ( self . _version , flow_sid = self . _solution [ 'flow_sid' ] , engagement_sid = self . _solution [ 'engagement_sid' ] , ) return self . _context
def savefig ( viz , name , gallery = GALLERY ) : """Saves the figure to the gallery directory"""
if not path . exists ( gallery ) : os . makedirs ( gallery ) # Must save as png if len ( name . split ( "." ) ) > 1 : raise ValueError ( "name should not specify extension" ) outpath = path . join ( gallery , name + ".png" ) viz . poof ( outpath = outpath ) print ( "created {}" . format ( outpath ) )
def _get_grad_method ( self , data ) : r"""Get the gradient This method calculates the gradient step from the input data Parameters data : np . ndarray Input data array Notes Implements the following equation : . . math : : \ nabla F ( x ) = \ mathbf { H } ^ T ( \ mathbf { H } \ mathbf { x } - \ mat...
self . grad = self . trans_op ( self . op ( data ) - self . obs_data )
def write_config_files ( self , host , hyperparameters , input_data_config ) : """Write the config files for the training containers . This method writes the hyperparameters , resources and input data configuration files . Args : host ( str ) : Host to write the configuration for hyperparameters ( dict ) : ...
config_path = os . path . join ( self . container_root , host , 'input' , 'config' ) resource_config = { 'current_host' : host , 'hosts' : self . hosts } json_input_data_config = { } for c in input_data_config : channel_name = c [ 'ChannelName' ] json_input_data_config [ channel_name ] = { 'TrainingInputMode' :...
def annotate_rule_violation ( self , rule : ValidationRule ) -> None : """Takes note of a rule validation failure by collecting its error message . : param rule : Rule that failed validation . : type rule : ValidationRule : return : None"""
if self . errors . get ( rule . label ) is None : self . errors [ rule . label ] = [ ] self . errors [ rule . label ] . append ( rule . get_error_message ( ) )
def prepare_cached_fields ( self , flist ) : """Prepare the cached fields of the fields _ desc dict"""
cls_name = self . __class__ # Fields cache initialization if flist : Packet . class_default_fields [ cls_name ] = dict ( ) Packet . class_default_fields_ref [ cls_name ] = list ( ) Packet . class_fieldtype [ cls_name ] = dict ( ) Packet . class_packetfields [ cls_name ] = list ( ) # Fields initializatio...
def _MetaPythonBase ( ) : """Return a metaclass which implements _ _ getitem _ _ , allowing e . g . P [ . . . ] instead of P ( ) [ . . . ]"""
class MagicGetItem ( type ) : def __new__ ( mcs , name , bases , dict ) : klass = type . __new__ ( mcs , name , bases , dict ) mcs . __getitem__ = lambda _ , k : klass ( ) [ k ] return klass return MagicGetItem
def _register_data_plane_account_arguments ( self , command_name ) : """Add parameters required to create a storage client"""
from azure . cli . core . commands . parameters import get_resource_name_completion_list from . _validators import validate_client_parameters command = self . command_loader . command_table . get ( command_name , None ) if not command : return group_name = 'Storage Account' command . add_argument ( 'account_name' ,...
def get_parameter_dd ( self , parameter ) : """This method returns parameters as nested dicts in case of decision diagram parameter ."""
dag = defaultdict ( list ) dag_elem = parameter . find ( 'DAG' ) node = dag_elem . find ( 'Node' ) root = node . get ( 'var' ) def get_param ( node ) : edges = defaultdict ( list ) for edge in node . findall ( 'Edge' ) : if edge . find ( 'Terminal' ) is not None : edges [ edge . get ( 'val' ...
def _read_requirements ( filename , extra_packages ) : """Returns a list of package requirements read from the file ."""
requirements_file = open ( filename ) . read ( ) hard_requirements = [ ] for line in requirements_file . splitlines ( ) : if _is_requirement ( line ) : if line . find ( ';' ) > - 1 : dep , condition = tuple ( line . split ( ';' ) ) extra_packages [ condition . strip ( ) ] . append ( ...
def color_text ( text , color ) : r"""SeeAlso : highlight _ text lexer _ shortnames = sorted ( ut . flatten ( ut . take _ column ( pygments . lexers . LEXERS . values ( ) , 2 ) ) )"""
import utool as ut if color is None or not ENABLE_COLORS : return text elif color == 'python' : return highlight_text ( text , color ) elif color == 'sql' : return highlight_text ( text , 'sql' ) try : import pygments import pygments . console # if color = = ' guess ' : # import linguist # N...
def apps_location_show ( self , id , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / core / app _ locations # show - location"
api_path = "/api/v2/apps/locations/{id}.json" api_path = api_path . format ( id = id ) return self . call ( api_path , ** kwargs )
def item_selection_changed ( self ) : """Item selection has changed"""
is_selection = len ( self . selectedItems ( ) ) > 0 self . expand_selection_action . setEnabled ( is_selection ) self . collapse_selection_action . setEnabled ( is_selection )
def DecompressMessageList ( cls , packed_message_list ) : """Decompress the message data from packed _ message _ list . Args : packed _ message _ list : A PackedMessageList rdfvalue with some data in it . Returns : a MessageList rdfvalue . Raises : DecodingError : If decompression fails ."""
compression = packed_message_list . compression if compression == rdf_flows . PackedMessageList . CompressionType . UNCOMPRESSED : data = packed_message_list . message_list elif ( compression == rdf_flows . PackedMessageList . CompressionType . ZCOMPRESSION ) : try : data = zlib . decompress ( packed_me...
def scalar_summary ( tag , scalar ) : """Outputs a ` Summary ` protocol buffer containing a single scalar value . The generated Summary has a Tensor . proto containing the input Tensor . Adapted from the TensorFlow function ` scalar ( ) ` at https : / / github . com / tensorflow / tensorflow / blob / r1.6 / t...
tag = _clean_tag ( tag ) scalar = _make_numpy_array ( scalar ) assert ( scalar . squeeze ( ) . ndim == 0 ) , 'scalar should be 0D' scalar = float ( scalar ) return Summary ( value = [ Summary . Value ( tag = tag , simple_value = scalar ) ] )
def reset ( self ) : """Reset the environment . Returns : Tensor of the current observation ."""
observ_dtype = self . _parse_dtype ( self . _env . observation_space ) observ = tf . py_func ( self . _env . reset , [ ] , observ_dtype , name = 'reset' ) observ = tf . check_numerics ( observ , 'observ' ) with tf . control_dependencies ( [ self . _observ . assign ( observ ) , self . _reward . assign ( 0 ) , self . _do...
def _make_order ( field_path , direction ) : """Helper for : meth : ` order _ by ` ."""
return query_pb2 . StructuredQuery . Order ( field = query_pb2 . StructuredQuery . FieldReference ( field_path = field_path ) , direction = _enum_from_direction ( direction ) , )
def has_path_sum ( root , sum ) : """: type root : TreeNode : type sum : int : rtype : bool"""
if root is None : return False if root . left is None and root . right is None and root . val == sum : return True sum -= root . val return has_path_sum ( root . left , sum ) or has_path_sum ( root . right , sum )
def _analyze_case ( model_dir , bench_dir , config ) : """Generates statistics from the timing summaries"""
model_timings = set ( glob . glob ( os . path . join ( model_dir , "*" + config [ "timing_ext" ] ) ) ) if bench_dir is not None : bench_timings = set ( glob . glob ( os . path . join ( bench_dir , "*" + config [ "timing_ext" ] ) ) ) else : bench_timings = set ( ) if not len ( model_timings ) : return dict (...
def helical_turbulent_fd_Czop ( Re , Di , Dc ) : r'''Calculates Darcy friction factor for a fluid flowing inside a curved pipe such as a helical coil under turbulent conditions , using the method of Czop [ 1 ] _ , also shown in [ 2 ] _ . . . math : : f _ { curv } = 0.096De ^ { - 0.1517} Parameters Re : ...
De = Dean ( Re = Re , Di = Di , D = Dc ) return 0.096 * De ** - 0.1517
def hash_nt_password_hash ( password_hash ) : """HashNtPasswordHash"""
md4_context = md4 . new ( ) md4_context . update ( password_hash ) return md4_context . digest ( )
def _region_from_key_id ( key_id , default_region = None ) : """Determine the target region from a key ID , falling back to a default region if provided . : param str key _ id : AWS KMS key ID : param str default _ region : Region to use if no region found in key _ id : returns : region name : rtype : str ...
try : region_name = key_id . split ( ":" , 4 ) [ 3 ] except IndexError : if default_region is None : raise UnknownRegionError ( "No default region found and no region determinable from key id: {}" . format ( key_id ) ) region_name = default_region return region_name
def output_markdown ( markdown_cont , output_file ) : """Writes to an output file if ` outfile ` is a valid path ."""
if output_file : with open ( output_file , 'w' ) as out : out . write ( markdown_cont )
def new_rater ( self ) : """Action : add a new rater ."""
if self . annot is None : # remove if buttons are disabled self . parent . statusBar ( ) . showMessage ( 'No score file loaded' ) return newuser = NewUserDialog ( self . parent . value ( 'scoring_window' ) ) answer = newuser . exec_ ( ) if answer == QDialog . Rejected : return rater_name = newuser . rater_n...
def render_data_uri ( self , ** kwargs ) : """Output a base 64 encoded data uri"""
# Force protocol as data uri have none kwargs . setdefault ( 'force_uri_protocol' , 'https' ) return "data:image/svg+xml;charset=utf-8;base64,%s" % ( base64 . b64encode ( self . render ( ** kwargs ) ) . decode ( 'utf-8' ) . replace ( '\n' , '' ) )
def to_dict ( self ) : '''Return a : class : ` dict ` of errors with keys as the type of error and values as a list of errors . : returns dict : a dictionary of errors'''
errors = copy . deepcopy ( self . _errors ) for key , val in iteritems ( self . _errors ) : if not len ( val ) : errors . pop ( key ) return errors
def overrideable_partial ( func , * args , ** default_kwargs ) : """like partial , but given kwargs can be overrideden at calltime"""
import functools @ functools . wraps ( func ) def partial_wrapper ( * given_args , ** given_kwargs ) : kwargs = default_kwargs . copy ( ) kwargs . update ( given_kwargs ) return func ( * ( args + given_args ) , ** kwargs ) return partial_wrapper
def emit ( event , * args , ** kwargs ) : """Emit a SocketIO event . This function emits a SocketIO event to one or more connected clients . A JSON blob can be attached to the event as payload . This is a function that can only be called from a SocketIO event handler , as in obtains some information from th...
if 'namespace' in kwargs : namespace = kwargs [ 'namespace' ] else : namespace = flask . request . namespace callback = kwargs . get ( 'callback' ) broadcast = kwargs . get ( 'broadcast' ) room = kwargs . get ( 'room' ) if room is None and not broadcast : room = flask . request . sid include_self = kwargs ....
def get_seqstarts ( bamfile , N ) : """Go through the SQ headers and pull out all sequences with size greater than the resolution settings , i . e . contains at least a few cells"""
import pysam bamfile = pysam . AlignmentFile ( bamfile , "rb" ) seqsize = { } for kv in bamfile . header [ "SQ" ] : if kv [ "LN" ] < 10 * N : continue seqsize [ kv [ "SN" ] ] = kv [ "LN" ] / N + 1 allseqs = natsorted ( seqsize . keys ( ) ) allseqsizes = np . array ( [ seqsize [ x ] for x in allseqs ] ) ...
def _get_rank_limits ( comm , arrlen ) : """Determine the chunk of the grid that has to be computed per process . The grid has been ' flattened ' and has arrlen length . The chunk assigned to each process depends on its rank in the MPI communicator . Parameters comm : MPI communicator object Describes t...
rank = comm . Get_rank ( ) # Id of this process size = comm . Get_size ( ) # Total number of processes in communicator end = 0 # The scan should be done with ints , not floats ranklen = int ( arrlen / size ) if rank < arrlen % size : ranklen += 1 # Compute upper limit based on the sizes covered by the processes # w...
def dataframe ( self , filtered_dims = { } , unstack = False , df_class = None , add_code = False ) : """Yield rows in a reduced format , with one dimension as an index , one measure column per secondary dimension , and all other dimensions filtered . : param measure : The column names of one or more measures ...
measure = self . table . column ( measure ) p_dim = self . table . column ( p_dim ) assert measure assert p_dim if s_dim : s_dim = self . table . column ( s_dim ) from six import text_type def maybe_quote ( v ) : from six import string_types if isinstance ( v , string_types ) : return '"{}"' . forma...
def map ( cls , obj , mode = 'data' , backend = None ) : """Applies compositor operations to any HoloViews element or container using the map method ."""
from . overlay import CompositeOverlay element_compositors = [ c for c in cls . definitions if len ( c . _pattern_spec ) == 1 ] overlay_compositors = [ c for c in cls . definitions if len ( c . _pattern_spec ) > 1 ] if overlay_compositors : obj = obj . map ( lambda obj : cls . collapse_element ( obj , mode = mode ,...
async def volume ( gc : GroupControl , volume ) : """Adjust volume [ - 100 , 100]"""
click . echo ( "Setting volume to %s" % volume ) click . echo ( await gc . set_group_volume ( volume ) )
def make_varname ( tree ) : """< left > tree < / left >"""
if tree . tag == 'identifier' : return tree . attrib [ 'name' ] if tree . tag in ( 'string' , 'boolean' ) : return tree . text if tree . tag == 'number' : return tree . attrib [ 'value' ] if tree . tag in ( 'property' , 'object' ) : return make_varname ( _xpath_one ( tree , '*' ) ) if tree . tag . endsw...
def get_strings ( soup , tag ) : """Get all the string children from an html tag ."""
tags = soup . find_all ( tag ) strings = [ s . string for s in tags if s . string ] return strings
def plotwrapper ( f ) : """This decorator allows for PyMC arguments of various types to be passed to the plotting functions . It identifies the type of object and locates its trace ( s ) , then passes the data to the wrapped plotting function ."""
def wrapper ( pymc_obj , * args , ** kwargs ) : start = 0 if 'start' in kwargs : start = kwargs . pop ( 'start' ) # Figure out what type of object it is try : # First try Model type for variable in pymc_obj . _variables_to_tally : # Plot object if variable . _plot is not Fals...
def _create_binary_mathfunction ( name , doc = "" ) : """Create a binary mathfunction by name"""
def _ ( col1 , col2 ) : sc = SparkContext . _active_spark_context # For legacy reasons , the arguments here can be implicitly converted into floats , # if they are not columns or strings . if isinstance ( col1 , Column ) : arg1 = col1 . _jc elif isinstance ( col1 , basestring ) : arg...
def init ( ) : """Initialize foreground and background attributes ."""
global _default_foreground , _default_background , _default_style try : attrs = GetConsoleScreenBufferInfo ( ) . wAttributes except ( ArgumentError , WindowsError ) : _default_foreground = GREY _default_background = BLACK _default_style = NORMAL else : _default_foreground = attrs & 7 _default_ba...
def get_app_main_kwargs ( self , kwargs , keep = False ) : """Extract the keyword arguments for the : meth : ` app _ main ` method Parameters kwargs : dict A mapping containing keyword arguments for the : meth : ` app _ main ` method keep : bool If True , the keywords are kept in the ` kwargs ` . Otherw...
if not keep : return { key : kwargs . pop ( key ) for key in list ( kwargs ) if key in inspect . getargspec ( self . app_main ) [ 0 ] } else : return { key : kwargs [ key ] for key in list ( kwargs ) if key in inspect . getargspec ( self . app_main ) [ 0 ] }
def close_sids ( self , rec , trt , mag ) : """: param rec : a record with fields minlon , minlat , maxlon , maxlat : param trt : tectonic region type string : param mag : magnitude : returns : the site indices within the bounding box enlarged by the integration distance for the given TRT and magnit...
if self . sitecol is None : return [ ] elif not self . integration_distance : # do not filter return self . sitecol . sids if hasattr ( rec , 'dtype' ) : bbox = rec [ 'minlon' ] , rec [ 'minlat' ] , rec [ 'maxlon' ] , rec [ 'maxlat' ] else : bbox = rec # assume it is a 4 - tuple maxdist = self . int...
def read_from_file ( self , filename ) : """Read from an existing json file . : param filename : The file to be written to . : type filename : basestring , str : returns : Success status . - 1 for unsuccessful 0 for success : rtype : int"""
if not exists ( filename ) : return - 1 with open ( filename ) as fd : needs_json = fd . read ( ) try : minimum_needs = json . loads ( needs_json ) except ( TypeError , ValueError ) : minimum_needs = None if not minimum_needs : return - 1 return self . update_minimum_needs ( minimum_...
def response ( credentials , password , request ) : """Compile digest auth response If the qop directive ' s value is " auth " or " auth - int " , then compute the response as follows : RESPONSE = MD5 ( HA1 : nonce : nonceCount : clienNonce : qop : HA2) Else if the qop directive is unspecified , then compute ...
response = None algorithm = credentials . get ( 'algorithm' ) HA1_value = HA1 ( credentials . get ( 'realm' ) , credentials . get ( 'username' ) , password , algorithm ) HA2_value = HA2 ( credentials , request , algorithm ) if credentials . get ( 'qop' ) is None : response = H ( b":" . join ( [ HA1_value . encode (...
def png ( contents , kvs ) : """Creates a png if needed ."""
outfile = os . path . join ( IMAGEDIR , sha ( contents + str ( kvs [ 'staffsize' ] ) ) ) src = outfile + '.png' if not os . path . isfile ( src ) : try : os . mkdir ( IMAGEDIR ) stderr . write ( 'Created directory ' + IMAGEDIR + '\n' ) except OSError : pass ly2png ( contents , outfil...
def checkPermissions ( permissions = [ ] , obj = None ) : """Checks if a user has permissions for a given object . Args : permissions : The permissions the current user must be compliant with obj : The object for which the permissions apply Returns : 1 if the user complies with all the permissions for the...
if not obj : return False sm = getSecurityManager ( ) for perm in permissions : if not sm . checkPermission ( perm , obj ) : return '' return True
def engage ( args , password ) : """Construct payloads and POST to Red October"""
if args [ 'create' ] : payload = { 'Name' : args [ '--user' ] , 'Password' : password } goodquit_json ( api_call ( 'create' , args , payload ) ) elif args [ 'delegate' ] : payload = { 'Name' : args [ '--user' ] , 'Password' : password , 'Time' : args [ '--time' ] , 'Uses' : args [ '--uses' ] } goodquit_...
def _get_labels ( self , frequency , subject_id = None , visit_id = None ) : """Returns the labels for the XNAT subject and sessions given the frequency and provided IDs ."""
if frequency == 'per_session' : subj_label = '{}_{}' . format ( self . project_id , subject_id ) sess_label = '{}_{}_{}' . format ( self . project_id , subject_id , visit_id ) elif frequency == 'per_subject' : subj_label = '{}_{}' . format ( self . project_id , subject_id ) sess_label = '{}_{}_{}' . for...
def plot ( network , margin = 0.05 , ax = None , geomap = True , projection = None , bus_colors = 'b' , line_colors = 'g' , bus_sizes = 10 , line_widths = 2 , title = "" , line_cmap = None , bus_cmap = None , boundaries = None , geometry = False , branch_components = [ 'Line' , 'Link' ] , jitter = None , basemap = None...
defaults_for_branches = { 'Link' : dict ( color = "cyan" , width = 2 ) , 'Line' : dict ( color = "b" , width = 2 ) , 'Transformer' : dict ( color = 'green' , width = 2 ) } if not plt_present : logger . error ( "Matplotlib is not present, so plotting won't work." ) return if basemap is not None : logger . wa...
def padded_cross_entropy_loss ( logits , labels , smoothing , vocab_size ) : """Calculate cross entropy loss while ignoring padding . Args : logits : Tensor of size [ batch _ size , length _ logits , vocab _ size ] labels : Tensor of size [ batch _ size , length _ labels ] smoothing : Label smoothing consta...
with tf . name_scope ( "loss" , [ logits , labels ] ) : logits , labels = _pad_tensors_to_same_length ( logits , labels ) # Calculate smoothing cross entropy with tf . name_scope ( "smoothing_cross_entropy" , [ logits , labels ] ) : confidence = 1.0 - smoothing low_confidence = ( 1.0 - confi...
def _mean_dict ( dict_list ) : """Compute the mean value across a list of dictionaries"""
return { k : np . array ( [ d [ k ] for d in dict_list ] ) . mean ( ) for k in dict_list [ 0 ] . keys ( ) }
def _encodeRelativeValidityPeriod ( validityPeriod ) : """Encodes the specified relative validity period timedelta into an integer for use in an SMS PDU ( based on the table in section 9.2.3.12 of GSM 03.40) : param validityPeriod : The validity period to encode : type validityPeriod : datetime . timedelta ...
# Python 2.6 does not have timedelta . total _ seconds ( ) , so compute it manually # seconds = validityPeriod . total _ seconds ( ) seconds = validityPeriod . seconds + ( validityPeriod . days * 24 * 3600 ) if seconds <= 43200 : # 12 hours tpVp = int ( seconds / 300 ) - 1 # divide by 5 minutes , subtract 1 eli...
def AddService ( self , new_service ) : """Add a new service to the list of ones we know about . Args : new _ service ( WindowsService ) : the service to add ."""
for service in self . _services : if new_service == service : # If this service is the same as one we already know about , we # just want to add where it came from . service . sources . append ( new_service . sources [ 0 ] ) return # We only add a new object to our list if we don ' t have # an i...
def close ( self , code : int = None , reason : str = None ) -> None : """Closes the websocket connection . ` ` code ` ` and ` ` reason ` ` are documented under ` WebSocketHandler . close ` . . . versionadded : : 3.2 . . versionchanged : : 4.0 Added the ` ` code ` ` and ` ` reason ` ` arguments ."""
if self . protocol is not None : self . protocol . close ( code , reason ) self . protocol = None
def interpolate_delays ( augmented_stop_times , dist_threshold , delay_threshold = 3600 , delay_cols = None ) : """Given an augment stop times DataFrame as output by the function : func : ` build _ augmented _ stop _ times ` , a distance threshold ( float ) in the same units as the ` ` ' shape _ dist _ traveled...
f = augmented_stop_times . copy ( ) if delay_cols is None or not set ( delay_cols ) <= set ( f . columns ) : delay_cols = [ 'arrival_delay' , 'departure_delay' ] # Return f if nothing to do if 'shape_dist_traveled' not in f . columns or not f [ 'shape_dist_traveled' ] . notnull ( ) . any ( ) or all ( [ f [ col ] . ...
def reset ( self ) : """Reset the value to the default"""
if self . resetable : for i in range ( len ( self ) ) : self [ i ] = self . default
def get_platform_settings ( ) : """Returns the content of ` settings . PLATFORMS ` with a twist . The platforms settings was created to stay compatible with the old way of declaring the FB configuration , in order not to break production bots . This function will convert the legacy configuration into the new ...
s = settings . PLATFORMS if hasattr ( settings , 'FACEBOOK' ) and settings . FACEBOOK : s . append ( { 'class' : 'bernard.platforms.facebook.platform.Facebook' , 'settings' : settings . FACEBOOK , } ) return s
def _compute_f0_factor ( self , rrup ) : """Compute and return factor f0 - see equation ( 5 ) , 6th term , p . 2191."""
# f0 = max ( log10 ( R0 / rrup ) , 0) f0 = np . log10 ( self . COEFFS_IMT_INDEPENDENT [ 'R0' ] / rrup ) f0 [ f0 < 0 ] = 0.0 return f0
def auto_close ( self , state = None ) : """Get or set automatic TCP close mode ( after each request ) : param state : auto _ close state or None for get value : type state : bool or None : returns : auto _ close state or None if set fail : rtype : bool or None"""
if state is None : return self . __auto_close self . __auto_close = bool ( state ) return self . __auto_close
def get_queryset ( self ) : """Returns a custom : class : ` QuerySet ` which provides the CTE functionality for all queries concerning : class : ` CTENode ` objects . This method overrides the default : meth : ` get _ queryset ` method of the : class : ` Manager ` class . : returns : a custom : class : ` Qu...
# The CTEQuerySet uses _ cte _ node _ * attributes from the Model , so ensure # they exist . self . _ensure_parameters ( ) return CTEQuerySet ( self . model , using = self . _db )
def _set_get_mpls_ldp_session_brief ( self , v , load = False ) : """Setter method for get _ mpls _ ldp _ session _ brief , mapped from YANG variable / brocade _ mpls _ rpc / get _ mpls _ ldp _ session _ brief ( rpc ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ get ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = get_mpls_ldp_session_brief . get_mpls_ldp_session_brief , is_leaf = True , yang_name = "get-mpls-ldp-session-brief" , rest_name = "get-mpls-ldp-session-brief" , parent = self , path_helper = self . _path_helper , extmethods =...
def sumai ( array ) : """Return the sum of the elements of an integer array . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / sumai _ c . html : param array : Input Array . : type array : Array of ints : return : The sum of the array . : rtype : int"""
n = ctypes . c_int ( len ( array ) ) array = stypes . toIntVector ( array ) return libspice . sumai_c ( array , n )
def parse_MML ( self , mml ) : '''parse the MML structure'''
hashes_c = [ ] mentions_c = [ ] soup = BeautifulSoup ( mml , "lxml" ) hashes = soup . find_all ( 'hash' , { "tag" : True } ) for hashe in hashes : hashes_c . append ( hashe [ 'tag' ] ) mentions = soup . find_all ( 'mention' , { "uid" : True } ) for mention in mentions : mentions_c . append ( mention [ 'uid' ] )...
def get_gateway_addr ( ) : """Use netifaces to get the gateway address , if we can ' t import it then fall back to a hack to obtain the current gateway automatically , since Python has no interface to sysctl ( ) . This may or may not be the gateway we should be contacting . It does not guarantee correct res...
try : import netifaces return netifaces . gateways ( ) [ "default" ] [ netifaces . AF_INET ] [ 0 ] except ImportError : shell_command = 'netstat -rn' if os . name == "posix" : pattern = re . compile ( '(?:default|0\.0\.0\.0|::/0)\s+([\w\.:]+)\s+.*UG' ) elif os . name == "nt" : if pla...
def get_turbine_types ( print_out = True ) : r"""Get the names of all possible wind turbine types for which the power coefficient curve or power curve is provided in the OpenEnergy Data Base ( oedb ) . Parameters print _ out : boolean Directly prints a tabular containing the turbine types in column ' tu...
df = load_turbine_data_from_oedb ( ) cp_curves_df = df . iloc [ df . loc [ df [ 'has_cp_curve' ] ] . index ] [ [ 'manufacturer' , 'turbine_type' , 'has_cp_curve' ] ] p_curves_df = df . iloc [ df . loc [ df [ 'has_power_curve' ] ] . index ] [ [ 'manufacturer' , 'turbine_type' , 'has_power_curve' ] ] curves_df = pd . mer...
def symbol_bollinger ( symbol = 'GOOG' , start = datetime . datetime ( 2008 , 1 , 1 ) , end = datetime . datetime ( 2009 , 12 , 31 ) , price_type = 'close' , cleaner = clean_dataframe , window = 20 , sigma = 1. ) : """Calculate the Bolinger indicator value > > > symbol _ bollinger ( " goog " , ' 2008-1-1 ' , ' 20...
symbols = normalize_symbols ( symbol ) prices = price_dataframe ( symbols , start = start , end = end , price_type = price_type , cleaner = cleaner ) return series_bollinger ( prices [ symbols [ 0 ] ] , window = window , sigma = sigma , plot = False )
def chain ( args ) : """% prog chain bedfile Chain BED segments together ."""
p = OptionParser ( chain . __doc__ ) p . add_option ( "--dist" , default = 100000 , help = "Chaining distance" ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) bedfile , = args cmd = "sort -k4,4 -k1,1 -k2,2n -k3,3n {0} -o {0}" . format ( bedfil...
def _resolve_process_count ( self ) : """Calculate amount of process resources . : return : Nothing , adds results to self . _ process _ count"""
length = len ( [ d for d in self . _dut_requirements if d . get ( "type" ) == "process" ] ) self . _process_count = length
def get_model_config_value ( self , obj , name ) : """Get config value for given model"""
config = models_config . get_config ( obj ) return getattr ( config , name )
def _reset_syslog_config_params ( host , username , password , cmd , resets , valid_resets , protocol = None , port = None , esxi_host = None , credstore = None ) : '''Helper function for reset _ syslog _ config that resets the config and populates the return dictionary .'''
ret_dict = { } all_success = True if not isinstance ( resets , list ) : resets = [ resets ] for reset_param in resets : if reset_param in valid_resets : ret = salt . utils . vmware . esxcli ( host , username , password , cmd + reset_param , protocol = protocol , port = port , esxi_host = esxi_host , cre...
def time_average_vel ( self , depth ) : """Calculate the time - average velocity . Parameters depth : float Depth over which the average velocity is computed . Returns avg _ vel : float Time averaged velocity ."""
depths = [ l . depth for l in self ] # Final layer is infinite and is treated separately travel_times = [ 0 ] + [ l . travel_time for l in self [ : - 1 ] ] # If needed , add the final layer to the required depth if depths [ - 1 ] < depth : depths . append ( depth ) travel_times . append ( ( depth - self [ - 1 ]...
def process ( self , quoted = False ) : '''Parse an URL'''
self . p = urlparse ( self . raw ) self . scheme = self . p . scheme self . netloc = self . p . netloc self . opath = self . p . path if not quoted else quote ( self . p . path ) self . path = [ x for x in self . opath . split ( '/' ) if x ] self . params = self . p . params self . query = parse_qs ( self . p . query ,...