signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def file ( value , ** kwarg ) : """value should be a path to file in the filesystem . returns a file object"""
# a bit weird , but I don ' t want to hard code default values try : f = open ( value , ** kwarg ) except IOError as e : raise ValueError ( "unable to open %s : %s" % ( path . abspath ( value ) , e ) ) return f
def get_model_by_name ( model_name ) : """Get model by its name . : param str model _ name : name of model . : return django . db . models . Model : Example : get _ concrete _ model _ by _ name ( ' auth . User ' ) django . contrib . auth . models . User"""
if isinstance ( model_name , six . string_types ) and len ( model_name . split ( '.' ) ) == 2 : app_name , model_name = model_name . split ( '.' ) if django . VERSION [ : 2 ] < ( 1 , 8 ) : model = models . get_model ( app_name , model_name ) else : from django . apps import apps mode...
def list_folders ( location = '\\' ) : r'''List all folders located in a specific location in the task scheduler . : param str location : A string value representing the folder from which you want to list tasks . Default is ' \ \ ' which is the root for the task scheduler ( C : \ Windows \ System32 \ tasks ) ...
# Create the task service object with salt . utils . winapi . Com ( ) : task_service = win32com . client . Dispatch ( "Schedule.Service" ) task_service . Connect ( ) # Get the folder to list folders from task_folder = task_service . GetFolder ( location ) folders = task_folder . GetFolders ( 0 ) ret = [ ] for folde...
async def get_device_info ( self , custom_attributes = None ) : """Get the local installed version ."""
await self . get_geofences ( ) await self . get_devices ( ) await self . get_positions ( ) devinfo = { } try : # pylint : disable = too - many - nested - blocks for dev in self . _devices or [ ] : for pos in self . _positions or [ ] : if pos [ "deviceId" ] == dev . get ( "id" ) : ...
def _get_grid_files ( self ) : """Get the files holding grid data for an aospy object ."""
grid_file_paths = self . grid_file_paths datasets = [ ] if isinstance ( grid_file_paths , str ) : grid_file_paths = [ grid_file_paths ] for path in grid_file_paths : try : ds = xr . open_dataset ( path , decode_times = False ) except ( TypeError , AttributeError ) : ds = xr . open_mfdataset ...
def parse ( code , filename = '<unknown>' , mode = 'exec' , tree = None ) : """Parse the source into an AST node with PyPosAST . Enhance nodes with positions Arguments : code - - code text Keyword Arguments : filename - - code path mode - - execution mode ( exec , eval , single ) tree - - current tree...
visitor = Visitor ( code , filename , mode , tree = tree ) return visitor . tree
def _add_referencer ( registry ) : """Gets the Referencer from config and adds it to the registry ."""
referencer = registry . queryUtility ( IReferencer ) if referencer is not None : return referencer ref = registry . settings [ 'urireferencer.referencer' ] url = registry . settings [ 'urireferencer.registry_url' ] r = DottedNameResolver ( ) registry . registerUtility ( r . resolve ( ref ) ( url ) , IReferencer ) r...
def get ( self , pattern ) : '''Get a compiled regular expression object based on pattern and cache it when it is not in the cache already'''
try : self . cache [ pattern ] [ 0 ] += 1 return self . cache [ pattern ] [ 1 ] except KeyError : pass if len ( self . cache ) > self . size : self . sweep ( ) regex = re . compile ( '{0}{1}{2}' . format ( self . prepend , pattern , self . append ) ) self . cache [ pattern ] = [ 1 , regex , pattern , ti...
def _process_stdin ( self ) : """Received data on stdin . Read and send to server ."""
with nonblocking ( sys . stdin . fileno ( ) ) : data = self . _stdin_reader . read ( ) # Send input in chunks of 4k . step = 4056 for i in range ( 0 , len ( data ) , step ) : self . _send_packet ( { 'cmd' : 'in' , 'data' : data [ i : i + step ] , } )
def get_companies ( ) : """: return : all knows companies"""
LOGGER . debug ( "CompanyService.get_companies" ) args = { 'http_operation' : 'GET' , 'operation_path' : '' } response = CompanyService . requester . call ( args ) ret = None if response . rc == 0 : ret = [ ] for company in response . response_content [ 'companies' ] : ret . append ( Company . json_2_co...
def id2word ( self , xs ) : """Map id ( s ) to word ( s ) Parameters xs : int id or a list of ids Returns str or list word or a list of words"""
if isinstance ( xs , list ) : return [ self . _id2word [ x ] for x in xs ] return self . _id2word [ xs ]
def login ( username , password , development_mode = False ) : """Return the user if successful , None otherwise"""
retval = None try : user = User . fetch_by ( username = username ) if user and ( development_mode or user . verify_password ( password ) ) : retval = user except OperationalError : pass return retval
def register ( xmlstream , query_xso , timeout = 60 , ) : """Create a new account on the server . : param query _ xso : XSO with the information needed for the registration . : type query _ xso : : class : ` ~ aioxmpp . ibr . Query ` : param xmlstream : Specifies the stream connected to the server where the...
iq = aioxmpp . IQ ( to = aioxmpp . JID . fromstr ( xmlstream . _to ) , type_ = aioxmpp . IQType . SET , payload = query_xso ) iq . autoset_id ( ) yield from aioxmpp . protocol . send_and_wait_for ( xmlstream , [ iq ] , [ aioxmpp . IQ ] , timeout = timeout )
def boto_resource ( self , service , * args , ** kwargs ) : """A wrapper to apply configuration options to boto resources"""
return self . boto_session . resource ( service , * args , ** self . configure_boto_session_method_kwargs ( service , kwargs ) )
def add_dos ( self , label , dos ) : """Adds a dos for plotting . Args : label : label for the DOS . Must be unique . dos : PhononDos object"""
densities = dos . get_smeared_densities ( self . sigma ) if self . sigma else dos . densities self . _doses [ label ] = { 'frequencies' : dos . frequencies , 'densities' : densities }
def B ( self , params ) : """B label Unconditional branch to the address at label"""
label = self . get_one_parameter ( self . ONE_PARAMETER , params ) self . check_arguments ( label_exists = ( label , ) ) # TODO check if label is within + - 2 KB # B label def B_func ( ) : if label == '.' : raise iarm . exceptions . EndOfProgram ( "You have reached an infinite loop" ) self . register [ ...
def angmom ( x ) : """returns angular momentum vector of phase - space point x"""
return np . array ( [ x [ 1 ] * x [ 5 ] - x [ 2 ] * x [ 4 ] , x [ 2 ] * x [ 3 ] - x [ 0 ] * x [ 5 ] , x [ 0 ] * x [ 4 ] - x [ 1 ] * x [ 3 ] ] )
def parse_args ( ) : """Parse command line arguments ."""
parser = argparse . ArgumentParser ( ) parser . add_argument ( '--lint' , help = 'Path to the ADT lint tool. If not specified it assumes lint tool is in your path' , default = 'lint' ) parser . add_argument ( '--app' , help = 'Path to the Android app. If not specifies it assumes current directory is your Android ' 'app...
def press_by_tooltip ( step , tooltip ) : """Press a button having a given tooltip ."""
with AssertContextManager ( step ) : for button in world . browser . find_elements_by_xpath ( str ( '//*[@title="%(tooltip)s" or @data-original-title="%(tooltip)s"]' % dict ( tooltip = tooltip ) ) ) : try : button . click ( ) break except Exception : pass else...
def _align ( x , y , local = False ) : """https : / / medium . com / towards - data - science / pairwise - sequence - alignment - using - biopython - d1a9d0ba861f"""
if local : aligned_x = pairwise2 . align . localxx ( x , y ) else : aligned_x = pairwise2 . align . globalms ( x , y , 1 , - 1 , - 1 , - 0.5 ) if aligned_x : sorted_alignments = sorted ( aligned_x , key = operator . itemgetter ( 2 ) ) e = enumerate ( sorted_alignments [ 0 ] [ 0 ] ) nts = [ i for i ,...
def convert_images_to_pil ( self , images , dither , nq = 0 , images_info = None ) : """convert _ images _ to _ pil ( images , nq = 0) Convert images to Paletted PIL images , which can then be written to a single animaged GIF ."""
# Convert to PIL images images2 = [ ] for im in images : if isinstance ( im , Image . Image ) : images2 . append ( im ) elif np and isinstance ( im , np . ndarray ) : if im . ndim == 3 and im . shape [ 2 ] == 3 : im = Image . fromarray ( im , 'RGB' ) elif im . ndim == 3 and i...
def publish_minions ( self ) : '''Publishes minions as a list of dicts .'''
log . debug ( 'in publish minions' ) minions = { } log . debug ( 'starting loop' ) for minion , minion_info in six . iteritems ( self . minions ) : log . debug ( minion ) # log . debug ( minion _ info ) curr_minion = { } curr_minion . update ( minion_info ) curr_minion . update ( { 'id' : minion } )...
def get_best_match ( text_log_error ) : """Get the best TextLogErrorMatch for a given TextLogErrorMatch . Matches are further filtered by the score cut off ."""
score_cut_off = 0.7 return ( text_log_error . matches . filter ( score__gt = score_cut_off ) . order_by ( "-score" , "-classified_failure_id" ) . select_related ( 'classified_failure' ) . first ( ) )
def fixed_inputs ( model , non_fixed_inputs , fix_routine = 'median' , as_list = True , X_all = False ) : """Convenience function for returning back fixed _ inputs where the other inputs are fixed using fix _ routine : param model : model : type model : Model : param non _ fixed _ inputs : dimensions of non...
from . . . inference . latent_function_inference . posterior import VariationalPosterior f_inputs = [ ] if hasattr ( model , 'has_uncertain_inputs' ) and model . has_uncertain_inputs ( ) : X = model . X . mean . values . copy ( ) elif isinstance ( model . X , VariationalPosterior ) : X = model . X . values . co...
def convert_prediction_values ( values , serving_bundle , model_spec = None ) : """Converts tensor values into ClassificationResponse or RegressionResponse . Args : values : For classification , a 2D list of numbers . The first dimension is for each example being predicted . The second dimension are the proba...
if serving_bundle . model_type == 'classification' : response = classification_pb2 . ClassificationResponse ( ) for example_index in range ( len ( values ) ) : classification = response . result . classifications . add ( ) for class_index in range ( len ( values [ example_index ] ) ) : ...
def _on_event ( self , event ) : """Returns the referential action for a given database operation on the referenced table the foreign key constraint is associated with . : param event : Name of the database operation / event to return the referential action for . : type event : str : rtype : str or None"""
if self . has_option ( event ) : on_event = self . get_option ( event ) . upper ( ) if on_event not in [ "NO ACTION" , "RESTRICT" ] : return on_event return False
def annotate ( args ) : """% prog annotate agpfile gaps . linkage . bed assembly . fasta Annotate AGP file with linkage info of ` paired - end ` or ` map ` . File ` gaps . linkage . bed ` is generated by assembly . gaps . estimate ( ) ."""
from jcvi . formats . agp import AGP , bed , tidy p = OptionParser ( annotate . __doc__ ) p . add_option ( "--minsize" , default = 200 , help = "Smallest component size [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) agpfile , linkagebed , as...
def quote_value ( value ) : """return the value ready to be used as a value in a SQL string . For example you can safely do this : cursor . execute ( ' select * from table where key = % s ' % quote _ value ( val ) ) and you don ' t have to worry about possible SQL injections ."""
adapted = adapt ( value ) if hasattr ( adapted , 'getquoted' ) : adapted = adapted . getquoted ( ) return adapted
def list_jobs ( ext_source = None , outputter = None , search_metadata = None , search_function = None , search_target = None , start_time = None , end_time = None , display_progress = False ) : '''List all detectable jobs and associated functions ext _ source If provided , specifies which external job cache to...
returner = _get_returner ( ( __opts__ [ 'ext_job_cache' ] , ext_source , __opts__ [ 'master_job_cache' ] ) ) if display_progress : __jid_event__ . fire_event ( { 'message' : 'Querying returner {0} for jobs.' . format ( returner ) } , 'progress' ) mminion = salt . minion . MasterMinion ( __opts__ ) ret = mminion . r...
async def add ( self , key , value , ttl = SENTINEL , dumps_fn = None , namespace = None , _conn = None ) : """Stores the value in the given key with ttl if specified . Raises an error if the key already exists . : param key : str : param value : obj : param ttl : int the expiration time in seconds . Due to...
start = time . monotonic ( ) dumps = dumps_fn or self . _serializer . dumps ns_key = self . build_key ( key , namespace = namespace ) await self . _add ( ns_key , dumps ( value ) , ttl = self . _get_ttl ( ttl ) , _conn = _conn ) logger . debug ( "ADD %s %s (%.4f)s" , ns_key , True , time . monotonic ( ) - start ) retur...
def from_post_response ( post_response , content ) : '''Convenience method for creating a new OutcomeResponse from a response object .'''
response = OutcomeResponse ( ) response . post_response = post_response response . response_code = post_response . status response . process_xml ( content ) return response
def construct_ctcp ( * parts ) : """Construct CTCP message ."""
message = ' ' . join ( parts ) message = message . replace ( '\0' , CTCP_ESCAPE_CHAR + '0' ) message = message . replace ( '\n' , CTCP_ESCAPE_CHAR + 'n' ) message = message . replace ( '\r' , CTCP_ESCAPE_CHAR + 'r' ) message = message . replace ( CTCP_ESCAPE_CHAR , CTCP_ESCAPE_CHAR + CTCP_ESCAPE_CHAR ) return CTCP_DELI...
def index ( self , row , column = 0 , parent = QModelIndex ( ) ) : """Reimplements the : meth : ` QAbstractItemModel . index ` method . : param row : Row . : type row : int : param column : Column . : type column : int : param parent : Parent . : type parent : QModelIndex : return : Index . : rtype ...
parent_node = self . get_node ( parent ) child = parent_node . child ( row ) if child : return self . createIndex ( row , column , child ) else : return QModelIndex ( )
def export_csv ( self , table , output = None , columns = "*" , ** kwargs ) : """Export a table to a CSV file . If an output path is provided , write to file . Else , return a string . Wrapper around pandas . sql . to _ csv ( ) . See : http : / / pandas . pydata . org / pandas - docs / stable / io . html # ...
import pandas . io . sql as panda # Determine if we ' re writing to a file or returning a string . isfile = output is not None output = output or StringIO ( ) if table not in self . tables : raise SchemaError ( "Cannot find table '{table}'" . format ( table = table ) ) # Don ' t print row indexes by default . if "i...
def _read_frame ( self , length ) : """Read a response frame from the PN532 of at most length bytes in size . Returns the data inside the frame if found , otherwise raises an exception if there is an error parsing the frame . Note that less than length bytes might be returned !"""
# Read frame with expected length of data . response = self . _read_data ( length + 8 ) logger . debug ( 'Read frame: 0x{0}' . format ( binascii . hexlify ( response ) ) ) # Check frame starts with 0x01 and then has 0x00FF ( preceeded by optional # zeros ) . if response [ 0 ] != 0x01 : raise RuntimeError ( 'Respons...
def parse_qs ( qs , keep_blank_values = False , strict_parsing = False , encoding = 'utf-8' , errors = 'replace' ) : """Parse a query given as a string argument . Arguments : qs : percent - encoded query string to be parsed keep _ blank _ values : flag indicating whether blank values in percent - encoded qu...
parsed_result = { } pairs = parse_qsl ( qs , keep_blank_values , strict_parsing , encoding = encoding , errors = errors ) for name , value in pairs : if name in parsed_result : parsed_result [ name ] . append ( value ) else : parsed_result [ name ] = [ value ] return parsed_result
def GetBEDnarrowPeakgz ( URL_or_PATH_TO_file ) : """Reads a gz compressed BED narrow peak file from a web address or local file : param URL _ or _ PATH _ TO _ file : web address of path to local file : returns : a Pandas dataframe"""
if os . path . isfile ( URL_or_PATH_TO_file ) : response = open ( URL_or_PATH_TO_file , "r" ) compressedFile = StringIO . StringIO ( response . read ( ) ) else : response = urllib2 . urlopen ( URL_or_PATH_TO_file ) compressedFile = StringIO . StringIO ( response . read ( ) ) decompressedFile = gzip . Gz...
def fillout_factor ( b , component , solve_for = None , ** kwargs ) : """Create a constraint to determine the fillout factor of a contact envelope . : parameter b : the : class : ` phoebe . frontend . bundle . Bundle ` : parameter str component : the label of the star in which this constraint should be built ...
hier = b . get_hierarchy ( ) if not len ( hier . get_value ( ) ) : # TODO : change to custom error type to catch in bundle . add _ component # TODO : check whether the problem is 0 hierarchies or more than 1 raise NotImplementedError ( "constraint for requiv_contact_max requires hierarchy" ) component_ps = _get_sys...
def OnWidget ( self , event ) : """Update the dialect widget to ' user '"""
self . choice_dialects . SetValue ( len ( self . choices [ 'dialects' ] ) - 1 ) event . Skip ( )
def _filter ( msgdata , mailparser , mdfolder , mailfilters ) : """Filter msgdata by mailfilters"""
if mailfilters : for f in mailfilters : msg = mailparser . parse ( StringIO ( msgdata ) ) rule = f ( msg , folder = mdfolder ) if rule : yield rule return
def main ( argv = None ) : # suppress ( unused - function ) """Entry point for jobstamp command . This will parse arguments and run the specified command in a subprocess . If the command has already been run , then the last captured stdout and stderr of the command will be printed on the command line ."""
argv = argv or sys . argv if "--" not in argv : sys . stderr . write ( """Must specify command after '--'.\n""" ) return 1 cmd_index = argv . index ( "--" ) args , cmd = ( argv [ 1 : cmd_index ] , argv [ cmd_index + 1 : ] ) parser = argparse . ArgumentParser ( description = """Cache results from jobs""" ) parse...
def url_for ( self , * subgroups , ** groups ) : """Build URL ."""
parsed = re . sre_parse . parse ( self . _pattern . pattern ) subgroups = { n : str ( v ) for n , v in enumerate ( subgroups , 1 ) } groups_ = dict ( parsed . pattern . groupdict ) subgroups . update ( { groups_ [ k0 ] : str ( v0 ) for k0 , v0 in groups . items ( ) if k0 in groups_ } ) path = '' . join ( str ( val ) fo...
async def configuration ( self , * , dc = None , consistency = None ) : """Inspects the Raft configuration Parameters : dc ( str ) : Specify datacenter that will be used . Defaults to the agent ' s local datacenter . consistency ( str ) : Read the Raft configuration from any of the Consul servers , otherw...
response = await self . _api . get ( "/v1/operator/raft/configuration" , params = { "dc" : dc } , consistency = consistency ) return response . body
def list_columns ( self , table = None , verbose = None ) : """Returns the list of columns in the table . : param table ( string , optional ) : Specifies a table by table name . If the pr efix SUID : is used , the table corresponding the SUID will be returne : returns : list of columns in the table ."""
PARAMS = set_param ( [ 'table' ] , [ table ] ) response = api ( url = self . __url + "/list columns" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response
def call_checkout_api ( self , request_data , action , ** kwargs ) : """This will call the checkout adyen api . xapi key merchant _ account , and platform are pulled from root module level and or self object . AdyenResult will be returned on 200 response . Otherwise , an exception is raised . Args : reque...
if not self . http_init : self . http_client = HTTPClient ( self . app_name , self . USER_AGENT_SUFFIX , self . LIB_VERSION , self . http_force ) self . http_init = True # xapi at self object has highest priority . fallback to root module # and ensure that it is set . if self . xapikey : xapikey = self . xa...
def update ( self , td ) : """Update state of ball"""
self . sprite . last_position = self . sprite . position self . sprite . last_velocity = self . sprite . velocity if self . particle_group != None : self . update_particle_group ( td )
def add_root_repository ( self , repository_id ) : """Adds a root repository . arg : repository _ id ( osid . id . Id ) : the ` ` Id ` ` of a repository raise : AlreadyExists - ` ` repository _ id ` ` is already in hierarchy raise : NotFound - ` ` repository _ id ` ` not found raise : NullArgument - ` ` r...
# Implemented from template for # osid . resource . BinHierarchyDesignSession . add _ root _ bin _ template if self . _catalog_session is not None : return self . _catalog_session . add_root_catalog ( catalog_id = repository_id ) return self . _hierarchy_session . add_root ( id_ = repository_id )
def browser ( request , path = '' , template = "cloud_browser/browser.html" ) : """View files in a file path . : param request : The request . : param path : Path to resource , including container as first part of path . : param template : Template to render ."""
from itertools import islice try : # pylint : disable = redefined - builtin from future_builtins import filter except ImportError : # pylint : disable = import - error from builtins import filter # Inputs . container_path , object_path = path_parts ( path ) incoming = request . POST or request . GET or { } mark...
def force_seek ( fd , offset , chunk = CHUNK ) : """Force adjustment of read cursort to specified offset This function takes a file descriptor ` ` fd ` ` and tries to seek to position specified by ` ` offset ` ` argument . If the descriptor does not support the ` ` seek ( ) ` ` method , it will fall back to `...
try : fd . seek ( offset ) except ( AttributeError , io . UnsupportedOperation ) : # This file handle probably has no seek ( ) emulate_seek ( fd , offset , chunk )
def _validate_in_port ( self ) : """Validate in _ port attribute . A valid port is either : * Greater than 0 and less than or equals to Port . OFPP _ MAX * One of the valid virtual ports : Port . OFPP _ LOCAL , Port . OFPP _ CONTROLLER or Port . OFPP _ NONE Raises : ValidationError : If in _ port is an ...
is_valid_range = self . in_port > 0 and self . in_port <= Port . OFPP_MAX is_valid_virtual_in_ports = self . in_port in _VIRT_IN_PORTS if ( is_valid_range or is_valid_virtual_in_ports ) is False : raise ValidationError ( f'{self.in_port} is not a valid input port.' )
def display_widgets ( self ) : """Displays all the widgets associated with this Container . Should be called when the widgets need to be " re - packed / gridded " ."""
# All widgets are removed and then recreated to ensure the order they # were created is the order they are displayed . for child in self . children : if child . displayable : # forget the widget if self . layout != "grid" : child . tk . pack_forget ( ) else : child . tk . gri...
def create_issue ( self , issue_field_dict , assign_current_user = False ) : """Creates a new JIRA issue . Arguments : | issue _ field _ dict ( string ) | A dictionary in the form of a string that the user can specify the issues fields and field values | | assign _ current _ user ( string / bool ) | ( Optiona...
issue_field_dict = eval ( str ( issue_field_dict ) ) print issue_field_dict new_issue = self . jira . create_issue ( issue_field_dict ) if assign_current_user is True : self . assign_user_to_issue ( new_issue , self . jira . current_user ( ) ) return new_issue
def _add_missing_jwt_permission_classes ( self , view_class ) : """Adds permissions classes that should exist for Jwt based authentication , if needed ."""
view_permissions = list ( getattr ( view_class , 'permission_classes' , [ ] ) ) # Not all permissions are classes , some will be ConditionalPermission # objects from the rest _ condition library . So we have to crawl all those # and expand them to see if our target classes are inside the # conditionals somewhere . perm...
def from_text ( text ) : """Convert text into a DNS rdata type value . @ param text : the text @ type text : string @ raises dns . rdatatype . UnknownRdatatype : the type is unknown @ raises ValueError : the rdata type value is not > = 0 and < = 65535 @ rtype : int"""
value = _by_text . get ( text . upper ( ) ) if value is None : match = _unknown_type_pattern . match ( text ) if match == None : raise UnknownRdatatype value = int ( match . group ( 1 ) ) if value < 0 or value > 65535 : raise ValueError ( "type must be between >= 0 and <= 65535" ) return...
def sparse_message_pass_batched ( node_states , adjacency_matrices , num_edge_types , hidden_size , use_bias = True , average_aggregation = False , name = "sparse_ggnn_batched" ) : """Identical to sparse _ ggnn except that each input has a batch dimension . B = The batch size . N = The number of nodes in each b...
b , n = tf . shape ( node_states ) [ 0 ] , tf . shape ( node_states ) [ 1 ] # Flatten the batch dimension of the node states . node_states = tf . reshape ( node_states , [ b * n , hidden_size ] ) # Flatten the batch dimension of the adjacency matrices . indices = adjacency_matrices . indices new_index2 = indices [ : , ...
def get_all_subnets ( self , subnet_ids = None , filters = None ) : """Retrieve information about your Subnets . You can filter results to return information only about those Subnets that match your search parameters . Otherwise , all Subnets associated with your account are returned . : type subnet _ ids :...
params = { } if subnet_ids : self . build_list_params ( params , subnet_ids , 'SubnetId' ) if filters : i = 1 for filter in filters : params [ ( 'Filter.%d.Name' % i ) ] = filter [ 0 ] params [ ( 'Filter.%d.Value.1' % i ) ] = filter [ 1 ] i += 1 return self . get_list ( 'DescribeSubn...
def install_host ( use_threaded_wrapper ) : """Install required components into supported hosts An unsupported host will still run , but may encounter issues , especially with threading ."""
for install in ( _install_maya , _install_houdini , _install_nuke , _install_nukeassist , _install_hiero , _install_nukestudio , _install_blender ) : try : install ( use_threaded_wrapper ) except ImportError : pass else : break
def send_from ( self , asset_id , addr_from , to_addr , value , fee = None , change_addr = None , id = None , endpoint = None ) : """Transfer from the specified address to the destination address . Args : asset _ id : ( str ) asset identifier ( for NEO : ' c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a...
params = [ asset_id , addr_from , to_addr , value ] if fee : params . append ( fee ) if fee and change_addr : params . append ( change_addr ) elif not fee and change_addr : params . append ( 0 ) params . append ( change_addr ) return self . _call_endpoint ( SEND_FROM , params = params , id = id , endpoi...
def get_asset_composition_design_session ( self ) : """Gets the session for creating asset compositions . return : ( osid . repository . AssetCompositionDesignSession ) - an AssetCompositionDesignSession raise : OperationFailed - unable to complete request raise : Unimplemented - supports _ asset _ composit...
if not self . supports_asset_composition_design ( ) : raise Unimplemented ( ) try : from . import sessions except ImportError : raise OperationFailed ( 'import error' ) try : session = sessions . AssetCompositionDesignSession ( proxy = self . _proxy , runtime = self . _runtime ) except AttributeError : ...
def form_valid ( self , form ) : """Praise be , someone has spammed us ."""
form . send_email ( to = self . to_addr ) return super ( EmailView , self ) . form_valid ( form )
def is_running ( self ) : """Check if the command is currently running Returns : bool : True if running , else False"""
if self . block : return False return self . thread . is_alive ( ) or self . process . poll ( ) is None
def _read_pug_fixed_grid ( projection , distance_multiplier = 1.0 ) : """Read from recent PUG format , where axes are in meters"""
a = projection . semi_major_axis h = projection . perspective_point_height b = projection . semi_minor_axis lon_0 = projection . longitude_of_projection_origin sweep_axis = projection . sweep_angle_axis [ 0 ] proj_dict = { 'a' : float ( a ) * distance_multiplier , 'b' : float ( b ) * distance_multiplier , 'lon_0' : flo...
def parse_type_signature ( sig ) : """Parse a type signature"""
match = TYPE_SIG_RE . match ( sig . strip ( ) ) if not match : raise RuntimeError ( 'Type signature invalid, got ' + sig ) groups = match . groups ( ) typ = groups [ 0 ] generic_types = groups [ 1 ] if not generic_types : generic_types = [ ] else : generic_types = split_sig ( generic_types [ 1 : - 1 ] ) is_...
def priorfactors ( self ) : """Combinartion of priorfactors from all populations"""
priorfactors = { } for pop in self . poplist : for f in pop . priorfactors : if f in priorfactors : if pop . priorfactors [ f ] != priorfactors [ f ] : raise ValueError ( 'prior factor %s is inconsistent!' % f ) else : priorfactors [ f ] = pop . priorfactors [...
def auto_idlepc ( self , vm ) : """Try to find the best possible idle - pc value . : param vm : VM instance"""
yield from vm . set_idlepc ( "0x0" ) was_auto_started = False try : status = yield from vm . get_status ( ) if status != "running" : yield from vm . start ( ) was_auto_started = True yield from asyncio . sleep ( 20 ) # leave time to the router to boot validated_idlepc = None ...
def get_all_tags_of_letter ( self , letter_id ) : """Get all tags of letter This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing : param letter _ id : the letter id : return : list"""
return self . _iterate_through_pages ( get_function = self . get_tags_of_letter_per_page , resource = LETTER_TAGS , ** { 'letter_id' : letter_id } )
def Beggs_Brill ( m , x , rhol , rhog , mul , mug , sigma , P , D , angle , roughness = 0.0 , L = 1.0 , g = g , acceleration = True ) : r'''Calculates the two - phase pressure drop according to the Beggs - Brill correlation ( [ 1 ] _ , [ 2 ] _ , [ 3 ] _ ) . Parameters m : float Mass flow rate of fluid , [ k...
qg = x * m / rhog ql = ( 1.0 - x ) * m / rhol A = 0.25 * pi * D * D Vsg = qg / A Vsl = ql / A Vm = Vsg + Vsl Fr = Vm * Vm / ( g * D ) lambda_L = Vsl / Vm # no slip liquid holdup L1 = 316.0 * lambda_L ** 0.302 L2 = 0.0009252 * lambda_L ** - 2.4684 L3 = 0.1 * lambda_L ** - 1.4516 L4 = 0.5 * lambda_L ** - 6.738 if ( lambd...
def run_work ( self ) : """Run attacks and defenses"""
if os . path . exists ( LOCAL_EVAL_ROOT_DIR ) : sudo_remove_dirtree ( LOCAL_EVAL_ROOT_DIR ) self . run_attacks ( ) self . run_defenses ( )
def invert ( self ) : """Inverts the DFA final states"""
for state in self . states : if state . final : state . final = False else : state . final = True
def validate_unique ( self , exclude = None ) : """Also validate the unique _ together of the translated model ."""
# This is called from ModelForm . _ post _ clean ( ) or Model . full _ clean ( ) errors = { } try : super ( TranslatableModelMixin , self ) . validate_unique ( exclude = exclude ) except ValidationError as e : errors = e . message_dict for local_cache in six . itervalues ( self . _translations_cache ) : for...
def login_in_terminal ( self , need_captcha = False , use_getpass = True ) : """不使用cookies , 在终端中根据提示登陆知乎 : param bool need _ captcha : 是否要求输入验证码 , 如果登录失败请设为 True : param bool use _ getpass : 是否使用安全模式输入密码 , 默认为 True , 如果在某些 Windows IDE 中无法正常输入密码 , 请把此参数设置为 False 试试 : return : 如果成功返回cookies字符串 : rtype : st...
print ( '====== zhihu login =====' ) email = input ( 'email: ' ) if use_getpass : password = getpass . getpass ( 'password: ' ) else : password = input ( "password: " ) if need_captcha : captcha_data = self . get_captcha ( ) with open ( 'captcha.gif' , 'wb' ) as f : f . write ( captcha_data ) ...
def _initsocket ( self ) : """bind to the datagram socket ( UDP ) , and enable BROADCAST mode"""
self . send_socket = socket ( AF_INET , SOCK_DGRAM ) self . send_socket . setblocking ( 0 ) self . send_socket . setsockopt ( SOL_SOCKET , SO_BROADCAST , 1 ) self . recv_socket = socket ( AF_INET , SOCK_DGRAM ) self . recv_socket . setblocking ( 0 ) if IS_BSD : self . recv_socket . setsockopt ( SOL_SOCKET , SO_REUS...
def add_station ( self , lv_station ) : """Adds a LV station to _ station and grid graph if not already existing"""
if not isinstance ( lv_station , LVStationDing0 ) : raise Exception ( 'Given LV station is not a LVStationDing0 object.' ) if self . _station is None : self . _station = lv_station self . graph_add_node ( lv_station ) self . grid_district . lv_load_area . mv_grid_district . mv_grid . graph_add_node ( lv...
def _get_site_scaling ( self , C , pga_rock , sites , period , rjb ) : """Returns the site - scaling term ( equation 5 ) , broken down into a linear scaling , a nonlinear scaling and a basin scaling term"""
flin = self . _get_linear_site_term ( C , sites . vs30 ) fnl = self . _get_nonlinear_site_term ( C , sites . vs30 , pga_rock ) fbd = self . _get_basin_depth_term ( C , sites , period ) return flin + fnl + fbd
def revert ( self ) : """Revert changes made by the module to the process environment . This must always run , as some modules ( e . g . git . py ) set variables like GIT _ SSH that must be cleared out between runs ."""
os . environ . clear ( ) os . environ . update ( self . original )
def drop_invalid_columns ( feed : "Feed" ) -> "Feed" : """Drop all DataFrame columns of the given " Feed " that are not listed in the GTFS . Return the resulting new " Feed " ."""
feed = feed . copy ( ) for table , group in cs . GTFS_REF . groupby ( "table" ) : f = getattr ( feed , table ) if f is None : continue valid_columns = group [ "column" ] . values for col in f . columns : if col not in valid_columns : print ( f"{table}: dropping invalid column...
def powerset ( iterable ) -> FrozenSet : "powerset ( [ 1,2,3 ] ) - - > ( ) ( 1 , ) ( 2 , ) ( 3 , ) ( 1,2 ) ( 1,3 ) ( 2,3 ) ( 1,2,3)"
combs = _powerset ( iterable ) res = frozenset ( frozenset ( x ) for x in combs ) # res = map ( frozenset , combs ) return res
def get_cached_credentials_filename ( role_name , role_arn ) : """Construct filepath for cached credentials ( AWS CLI scheme ) : param role _ name : : param role _ arn : : return :"""
filename_p1 = role_name . replace ( '/' , '-' ) filename_p2 = role_arn . replace ( '/' , '-' ) . replace ( ':' , '_' ) return os . path . join ( os . path . join ( os . path . expanduser ( '~' ) , '.aws' ) , 'cli/cache/%s--%s.json' % ( filename_p1 , filename_p2 ) )
def isExploitable ( self ) : """Guess how likely is it that the bug causing the crash can be leveraged into an exploitable vulnerability . @ note : Don ' t take this as an equivalent of a real exploitability analysis , that can only be done by a human being ! This is only a guideline , useful for example to...
# Terminal rules if self . eventCode != win32 . EXCEPTION_DEBUG_EVENT : return ( "Not an exception" , "NotAnException" , "The event is not an exception." ) if self . stackRange and self . pc is not None and self . stackRange [ 0 ] <= self . pc < self . stackRange [ 1 ] : return ( "Exploitable" , "StackCodeExecu...
def Akmaev_adjustment ( theta , q , beta , n_k , theta_k , s_k , t_k ) : '''Single column only .'''
L = q . size # number of vertical levels # Akmaev step 1 k = 1 n_k [ k - 1 ] = 1 theta_k [ k - 1 ] = theta [ k - 1 ] l = 2 while True : # Akmaev step 2 n = 1 thistheta = theta [ l - 1 ] while True : # Akmaev step 3 if theta_k [ k - 1 ] <= thistheta : # Akmaev step 6 k += 1 br...
def destroy_cloudwatch_event ( app = '' , env = 'dev' , region = '' ) : """Destroy Cloudwatch event subscription . Args : app ( str ) : Spinnaker Application name . env ( str ) : Deployment environment . region ( str ) : AWS region . Returns : bool : True upon successful completion ."""
session = boto3 . Session ( profile_name = env , region_name = region ) cloudwatch_client = session . client ( 'events' ) event_rules = get_cloudwatch_event_rule ( app_name = app , account = env , region = region ) for rule in event_rules : cloudwatch_client . remove_targets ( Rule = rule , Ids = [ app ] ) return T...
def extendMarkdown ( self , md , md_globals ) : """Add an instance of FigcaptionProcessor to BlockParser ."""
# def _ list = ' def _ list ' in md . registeredExtensions md . parser . blockprocessors . add ( 'figcaption' , FigcaptionProcessor ( md . parser ) , '<ulist' )
def _lemmatize_token ( self , token , best_guess = True , return_frequencies = False ) : """Lemmatize a single token . If best _ guess is true , then take the most frequent lemma when a form has multiple possible lemmatizations . If the form is not found , just return it . If best _ guess is false , then always...
lemmas = self . lemma_dict . get ( token . lower ( ) , None ) if best_guess == True : if lemmas == None : lemma = token elif len ( lemmas ) > 1 : counts = [ self . type_counts [ word ] for word in lemmas ] lemma = lemmas [ argmax ( counts ) ] else : lemma = lemmas [ 0 ] i...
def save ( self , * args , ** kwargs ) : """creates the slug , queues up for indexing and saves the instance : param args : inline arguments ( optional ) : param kwargs : keyword arguments : return : ` bulbs . content . Content `"""
if not self . slug : self . slug = slugify ( self . build_slug ( ) ) [ : self . _meta . get_field ( "slug" ) . max_length ] if not self . is_indexed : if kwargs is None : kwargs = { } kwargs [ "index" ] = False content = super ( Content , self ) . save ( * args , ** kwargs ) index_content_contributi...
def submit_status_external_cmd ( cmd_file , status_file ) : '''Submits the status lines in the status _ file to Nagios ' external cmd file .'''
try : with open ( cmd_file , 'a' ) as cmd_file : cmd_file . write ( status_file . read ( ) ) except IOError : exit ( "Fatal error: Unable to write to Nagios external command file '%s'.\n" "Make sure that the file exists and is writable." % ( cmd_file , ) )
def fit_model ( ts , sc = None ) : """Fits an EWMA model to a time series . Uses the first point in the time series as a starting value . Uses sum squared error as an objective function to optimize to find smoothing parameter The model for EWMA is recursively defined as S _ t = ( 1 - a ) * X _ t + a * S _ { t -...
assert sc != None , "Missing SparkContext" jvm = sc . _jvm jmodel = jvm . com . cloudera . sparkts . models . EWMA . fitModel ( _py2java ( sc , Vectors . dense ( ts ) ) ) return EWMAModel ( jmodel = jmodel , sc = sc )
def alpha_aligned ( returns , factor_returns , risk_free = 0.0 , period = DAILY , annualization = None , out = None , _beta = None ) : """Calculates annualized alpha . If they are pd . Series , expects returns and factor _ returns have already been aligned on their labels . If np . ndarray , these arguments sho...
allocated_output = out is None if allocated_output : out = np . empty ( returns . shape [ 1 : ] , dtype = 'float64' ) if len ( returns ) < 2 : out [ ( ) ] = np . nan if returns . ndim == 1 : out = out . item ( ) return out ann_factor = annualization_factor ( period , annualization ) if _beta is ...
def ajModeles ( self ) : """Lecture des modèles , et enregistrement de leurs désinences"""
sl = [ ] lines = [ line for line in lignesFichier ( self . path ( "modeles.la" ) ) ] max = len ( lines ) - 1 for i , l in enumerate ( lines ) : if l . startswith ( '$' ) : varname , value = tuple ( l . split ( "=" ) ) self . lemmatiseur . _variables [ varname ] = value continue eclats = ...
def cli ( ctx , pattern ) : """Searches for a saved command ."""
matches = utils . grep_commands ( pattern ) if matches : for cmd , desc in matches : click . secho ( "$ {} :: {}" . format ( cmd , desc ) , fg = 'green' ) elif matches == [ ] : click . echo ( 'No saved commands matches the pattern {}' . format ( pattern ) ) else : click . echo ( 'No commands to show...
def __cleanup_breakpoint ( self , event , bp ) : "Auxiliary method ."
try : process = event . get_process ( ) thread = event . get_thread ( ) bp . disable ( process , thread ) # clear the debug regs / trap flag except Exception : pass bp . set_condition ( True ) # break possible circular reference bp . set_action ( None )
def process_satellites ( self , helper , sess ) : """check and show the good satellites"""
good_satellites = helper . get_snmp_value ( sess , helper , self . oids [ 'oid_gps_satellites_good' ] ) # Show the summary and add the metric and afterwards check the metric helper . add_summary ( "Good satellites: {}" . format ( good_satellites ) ) helper . add_metric ( label = 'satellites' , value = good_satellites )
def find_entry ( self , entry , exact = True ) : """Return the full path to the first entry whose file name equals the given ` ` entry ` ` path . Return ` ` None ` ` if the entry cannot be found . If ` ` exact ` ` is ` ` True ` ` , the path must be exact , otherwise the comparison is done only on the file n...
if exact : self . log ( [ u"Finding entry '%s' with exact=True" , entry ] ) if entry in self . entries : self . log ( [ u"Found entry '%s'" , entry ] ) return entry else : self . log ( [ u"Finding entry '%s' with exact=False" , entry ] ) for ent in self . entries : if os . path ....
def parse_JSON ( self , JSON_string ) : """Parses a * Forecast * instance out of raw JSON data . Only certain properties of the data are used : if these properties are not found or cannot be parsed , an error is issued . : param JSON _ string : a raw JSON string : type JSON _ string : str : returns : a * ...
if JSON_string is None : raise parse_response_error . ParseResponseError ( 'JSON data is None' ) d = json . loads ( JSON_string ) # Check if server returned errors : this check overcomes the lack of use # of HTTP error status codes by the OWM API 2.5 . This mechanism is # supposed to be deprecated as soon as the AP...
def get_question_answer_id ( self , question , fast = False , bust_questions_cache = False ) : """Get the index of the answer that was given to ` question ` See the documentation for : meth : ` ~ . get _ user _ question ` for important caveats about the use of this function . : param question : The question w...
if hasattr ( question , 'answer_id' ) : # Guard to handle incoming user _ question . return question . answer_id user_question = self . get_user_question ( question , fast = fast , bust_questions_cache = bust_questions_cache ) # Look at recently answered questions return user_question . get_answer_id_for_question (...
def _set_port_sec_max ( self , v , load = False ) : """Setter method for port _ sec _ max , mapped from YANG variable / interface / port _ channel / switchport / port _ security / port _ sec _ max ( uint32) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ port _ sec _ ma...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = RestrictedClassType ( base_type = RestrictedClassType ( base_type = long , restriction_dict = { 'range' : [ '0..4294967295' ] } , int_size = 32 ) , restriction_dict = { 'range' : [ u'0..8192' ] } ) , is_leaf = True , yang_nam...
def _merge_config ( self , config_override ) : """overrides and / or adds data to the current configuration file . * * This has not been implemented yet . : param config _ override : A : string : config data to add to or override the current config ."""
if not isinstance ( config_override , dict ) : raise TypeError ( "config override must be a dict" ) def recursion ( config_value , override_value ) : for key , value in override_value . items ( ) : if key in config_value : if isinstance ( value , dict ) and isinstance ( config_value [ key ] ...
def pop_frame ( self ) : """Pops the current contextual frame off of the stack and returns the cursor to the frame ' s return position ."""
try : offset , return_pos = self . _frames . pop ( ) except IndexError : raise IndexError ( 'no frames to pop' ) self . _total_offset -= offset self . seek ( return_pos )
def _LoadArtifactsFromDatastore ( self ) : """Load artifacts from the data store ."""
loaded_artifacts = [ ] # TODO ( hanuszczak ) : Why do we have to remove anything ? If some artifact # tries to shadow system artifact shouldn ' t we just ignore them and perhaps # issue some warning instead ? The datastore being loaded should be read - only # during upload . # A collection of artifacts that shadow syst...
def _start ( self ) : """Start process ."""
if not self . _fired : self . _partial_ouput = None self . _process . start ( self . _cmd_list [ 0 ] , self . _cmd_list [ 1 : ] ) self . _timer . start ( )
def style_factory ( name , cli_style ) : """Create a Pygments Style class based on the user ' s preferences . : param str name : The name of a built - in Pygments style . : param dict cli _ style : The user ' s token - type style preferences ."""
try : style = pygments . styles . get_style_by_name ( name ) except ClassNotFound : style = pygments . styles . get_style_by_name ( 'native' ) style_tokens = { } style_tokens . update ( style . styles ) custom_styles = { string_to_tokentype ( x ) : y for x , y in cli_style . items ( ) } style_tokens . update ( ...