signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def insertSaneDefaults ( self ) : """Add sane defaults rules to the raw and filter tables"""
self . raw . insert ( 0 , '-A OUTPUT -o lo -j NOTRACK' ) self . raw . insert ( 1 , '-A PREROUTING -i lo -j NOTRACK' ) self . filters . insert ( 0 , '-A INPUT -i lo -j ACCEPT' ) self . filters . insert ( 1 , '-A OUTPUT -o lo -j ACCEPT' ) self . filters . insert ( 2 , '-A INPUT -m conntrack --ctstate ESTABLISHED,RELATED ...
def set_resource_attribute ( self , attr , value ) : """Sets attributes on resource . Resource attributes are top - level entries of a CloudFormation resource that exist outside of the Properties dictionary : param attr : Attribute name : param value : Attribute value : return : None : raises KeyError if ...
if attr not in self . _supported_resource_attributes : raise KeyError ( "Unsupported resource attribute specified: %s" % attr ) self . resource_attributes [ attr ] = value
def parsed_event_detail ( self ) : """Parse and return our PREMIS eventDetail string value like : : ' program = " 7z " ; version = " 9.20 " ; algorithm = " bzip2 " ' and return a dict like : : { ' algorithm ' : ' bzip2 ' , ' version ' : ' 9.20 ' , ' program ' : ' 7z ' }"""
attr = ( "event_detail_information__event_detail" if self . premis_version == utils . PREMIS_3_0_VERSION else "event_detail" ) return dict ( [ tuple ( [ x . strip ( ' "' ) for x in kv . strip ( ) . split ( "=" , 1 ) ] ) for kv in getattr ( self , attr ) . split ( ";" ) ] )
def run_zone ( self , minutes , zone = None ) : """Run or stop a zone or all zones for an amount of time . : param minutes : The number of minutes to run . : type minutes : int : param zone : The zone number to run . If no zone is specified then run all zones . : type zone : int or None : returns : The ...
if zone is None : zone_cmd = 'runall' relay_id = None else : if zone < 0 or zone > ( len ( self . relays ) - 1 ) : return None else : zone_cmd = 'run' relay_id = self . relays [ zone ] [ 'relay_id' ] if minutes <= 0 : time_cmd = 0 if zone is None : zone_cmd = 'sto...
def pad_to_same_length ( x , y , final_length_divisible_by = 1 , axis = 1 ) : """Pad tensors x and y on axis 1 so that they have the same length ."""
if axis not in [ 1 , 2 ] : raise ValueError ( "Only axis=1 and axis=2 supported for now." ) with tf . name_scope ( "pad_to_same_length" , values = [ x , y ] ) : x_length = shape_list ( x ) [ axis ] y_length = shape_list ( y ) [ axis ] if ( isinstance ( x_length , int ) and isinstance ( y_length , int ) ...
def _PreparedData ( self , order_by = ( ) ) : """Prepares the data for enumeration - sorting it by order _ by . Args : order _ by : Optional . Specifies the name of the column ( s ) to sort by , and ( optionally ) which direction to sort in . Default sort direction is asc . Following formats are accepted : ...
if not order_by : return self . __data sorted_data = self . __data [ : ] if isinstance ( order_by , six . string_types ) or ( isinstance ( order_by , tuple ) and len ( order_by ) == 2 and order_by [ 1 ] . lower ( ) in [ "asc" , "desc" ] ) : order_by = ( order_by , ) for key in reversed ( order_by ) : if isi...
def router_main ( self ) : '''Main method for router ; we stay in a loop in this method , receiving packets until the end of time .'''
while True : gotpkt = True try : timestamp , dev , pkt = self . net . recv_packet ( timeout = 1.0 ) except NoPackets : log_debug ( "No packets available in recv_packet" ) gotpkt = False except Shutdown : log_debug ( "Got shutdown signal" ) break if gotpkt : ...
def point_eval ( M , C , x ) : """Evaluates M ( x ) and C ( x ) . Minimizes computation ; evaluating M ( x ) and C ( x ) separately would evaluate the off - diagonal covariance term twice , but callling point _ eval ( M , C , x ) would only evaluate it once . Also chunks the evaluations if the off - diagona...
x_ = regularize_array ( x ) M_out = empty ( x_ . shape [ 0 ] ) V_out = empty ( x_ . shape [ 0 ] ) if isinstance ( C , pymc . gp . BasisCovariance ) : y_size = len ( C . basis ) elif C . obs_mesh is not None : y_size = C . obs_mesh . shape [ 0 ] else : y_size = 1 n_chunks = ceil ( y_size * x_ . shape [ 0 ] /...
def set_fresh_watermark ( game_queue , count_from , window_size , fresh_fraction = 0.05 , minimum_fresh = 20000 ) : """Sets the metadata cell used to block until some quantity of games have been played . This sets the ' freshness mark ' on the ` game _ queue ` , used to block training until enough new games hav...
already_played = game_queue . latest_game_number - count_from print ( "== already_played: " , already_played , flush = True ) if window_size > count_from : # How to handle the case when the window is not yet ' full ' game_queue . require_fresh_games ( int ( minimum_fresh * .9 ) ) else : num_to_play = max ( 0 , ...
def ellipse ( n = 1000 , adaptive = False ) : """Get a parameterized set of vectors defining ellipse for a major and minor axis length . Resulting vector bundle has major axes along axes given ."""
u = N . linspace ( 0 , 2 * N . pi , n ) # Get a bundle of vectors defining # a full rotation around the unit circle return N . array ( [ N . cos ( u ) , N . sin ( u ) ] ) . T
def calc_pell_number ( n : int ) -> int : """This function calculates the nth Pell number . Args : n : An integer representing the position of the Pell number Returns : The nth Pell number Examples : > > > calc _ pell _ number ( 4) 12 > > > calc _ pell _ number ( 7) 169 > > > calc _ pell _ numbe...
if n <= 2 : return n num1 , num2 = 1 , 2 for _ in range ( 3 , n + 1 ) : num1 , num2 = num2 , 2 * num2 + num1 return num2
def sponsor_image_url ( sponsor , name ) : """Returns the corresponding url from the sponsors images"""
if sponsor . files . filter ( name = name ) . exists ( ) : # We avoid worrying about multiple matches by always # returning the first one . return sponsor . files . filter ( name = name ) . first ( ) . item . url return ''
def reply ( self ) : """Captures reply message within email"""
reply = [ ] for f in self . fragments : if not ( f . hidden or f . quoted ) : reply . append ( f . content ) return '\n' . join ( reply )
def defract ( self ) : """Returns the underlying ( unrefracted ) value of element > > > Element ( content = ' Hello ' ) . defract ' Hello ' > > > Element ( content = Element ( content = ' Hello ' ) ) . defract ' Hello ' > > > Element ( content = [ Element ( content = ' Hello ' ) ] ) . defract [ ' Hello ...
from refract . elements . object import Object def get_value ( item ) : if isinstance ( item , KeyValuePair ) : return ( get_value ( item . key ) , get_value ( item . value ) ) elif isinstance ( item , list ) : return [ get_value ( element ) for element in item ] elif isinstance ( item , Ele...
def add_filter ( self , table , cols , condition ) : """Add a filter . When reading * table * , rows in * table * will be filtered by filter _ rows ( ) . Args : table : The table the filter applies to . cols : The columns in * table * to filter on . condition : The filter function ."""
if table is not None and table not in self . relations : raise ItsdbError ( 'Cannot add filter; table "{}" is not defined ' 'by the relations file.' . format ( table ) ) # this is a hack , though perhaps well - motivated if cols is None : cols = [ None ] self . filters [ table ] . append ( ( cols , condition ) ...
def tick ( self , filename ) : """Try to connect and display messages in queue ."""
if self . connection_attempts < 10 : # Trick to connect ASAP when # plugin is started without # user interaction ( CursorMove ) self . setup ( True , False ) self . connection_attempts += 1 self . unqueue_and_display ( filename )
def fix_ofiles ( self ) : """Note that ABINIT produces lots of out _ TIM1 _ DEN files for each step . Here we list all TIM * _ DEN files , we select the last one and we rename it in out _ DEN This change is needed so that we can specify dependencies with the syntax { node : " DEN " } without having to know th...
super ( ) . fix_ofiles ( ) # Find the last TIM ? _ DEN file . last_timden = self . outdir . find_last_timden_file ( ) if last_timden is None : logger . warning ( "Cannot find TIM?_DEN files" ) return # Rename last TIMDEN with out _ DEN . ofile = self . outdir . path_in ( "out_DEN" ) if last_timden . path . ends...
def _call_and_format ( self , req , props = None ) : """Invokes a single request against a handler using _ call ( ) and traps any errors , formatting them using _ err ( ) . If the request is successful it is wrapped in a JSON - RPC 2.0 compliant dict with keys : ' jsonrpc ' , ' id ' , ' result ' . : Parameter...
if not isinstance ( req , dict ) : return err_response ( None , ERR_INVALID_REQ , "Invalid Request. %s is not an object." % str ( req ) ) reqid = None if req . has_key ( "id" ) : reqid = req [ "id" ] if props == None : props = { } context = RequestContext ( props , req ) if self . filters : for f in sel...
def sequential_spherical ( xyz ) : """Converts sequence of cartesian coordinates into a sequence of line segments defined by spherical coordinates . Args : xyz = 2d numpy array , each row specifies a point in cartesian coordinates ( x , y , z ) tracing out a path in 3D space . Returns : r = lengths of...
d_xyz = np . diff ( xyz , axis = 0 ) r = np . linalg . norm ( d_xyz , axis = 1 ) theta = np . arctan2 ( d_xyz [ : , 1 ] , d_xyz [ : , 0 ] ) hyp = d_xyz [ : , 0 ] ** 2 + d_xyz [ : , 1 ] ** 2 phi = np . arctan2 ( np . sqrt ( hyp ) , d_xyz [ : , 2 ] ) return ( r , theta , phi )
def pars_in_groups ( self ) : """return a dictionary of parameter names in each parameter group . Returns : dictionary"""
pargp = self . par_groups allpars = dict ( ) for cpg in pargp : allpars [ cpg ] = [ i for i in self . parameter_data . loc [ self . parameter_data . pargp == cpg , 'parnme' ] ] return allpars
def _get_linked_entities ( self ) -> Dict [ str , Dict [ str , Tuple [ str , str , List [ int ] ] ] ] : """This method gets entities from the current utterance finds which tokens they are linked to . The entities are divided into two main groups , ` ` numbers ` ` and ` ` strings ` ` . We rely on these entities ...
current_tokenized_utterance = [ ] if not self . tokenized_utterances else self . tokenized_utterances [ - 1 ] # We generate a dictionary where the key is the type eg . ` ` number ` ` or ` ` string ` ` . # The value is another dictionary where the key is the action and the value is a tuple # of the nonterminal , the str...
def get_ticket_results ( mgr , ticket_id , update_count = 1 ) : """Get output about a ticket . : param integer id : the ticket ID : param integer update _ count : number of entries to retrieve from ticket : returns : a KeyValue table containing the details of the ticket"""
ticket = mgr . get_ticket ( ticket_id ) table = formatting . KeyValueTable ( [ 'name' , 'value' ] ) table . align [ 'name' ] = 'r' table . align [ 'value' ] = 'l' table . add_row ( [ 'id' , ticket [ 'id' ] ] ) table . add_row ( [ 'title' , ticket [ 'title' ] ] ) table . add_row ( [ 'priority' , PRIORITY_MAP [ ticket . ...
def _find_by_sha1 ( self , sha1 ) : """Return an | ImagePart | object belonging to this package or | None | if no matching image part is found . The image part is identified by the SHA1 hash digest of the image binary it contains ."""
for image_part in self : # - - - skip unknown / unsupported image types , like SVG - - - if not hasattr ( image_part , 'sha1' ) : continue if image_part . sha1 == sha1 : return image_part return None
def resolve_import_alias ( name , import_names ) : """Resolve a name from an aliased import to its original name . : param name : The potentially aliased name to resolve . : type name : str : param import _ names : The pairs of original names and aliases from the import . : type import _ names : iterable ...
resolved_name = name for import_name , imported_as in import_names : if import_name == name : break if imported_as == name : resolved_name = import_name break return resolved_name
def _bind ( self ) : """Create socket and bind"""
credentials = pika . PlainCredentials ( self . user , self . password ) params = pika . ConnectionParameters ( credentials = credentials , host = self . server , virtual_host = self . vhost , port = self . port ) self . connection = pika . BlockingConnection ( params ) self . channel = self . connection . channel ( ) #...
def squash_sequence ( input_layer ) : """" Squashes a sequence into a single Tensor with dim 1 being time * batch . A sequence is an array of Tensors , which is not appropriate for most operations , this squashes them together into Tensor . Defaults are assigned such that cleave _ sequence requires no args . ...
timesteps = len ( input_layer . sequence ) if not timesteps : raise ValueError ( 'Empty tensor sequence.' ) elif timesteps == 1 : result = input_layer . sequence [ 0 ] else : result = tf . concat ( input_layer . sequence , 0 ) return input_layer . with_tensor ( result ) . with_defaults ( unroll = timesteps ...
def get_service_health ( service_id : str ) -> str : """Get the health of a service using service _ id . Args : service _ id Returns : str , health status"""
# Check if the current and actual replica levels are the same if DC . get_replicas ( service_id ) != DC . get_actual_replica ( service_id ) : health_status = "Unhealthy" else : health_status = "Healthy" return health_status
def update ( runas = None , path = None ) : '''Updates the current versions of rbenv and ruby - build runas The user under which to run rbenv . If not specified , then rbenv will be run as the user under which Salt is running . CLI Example : . . code - block : : bash salt ' * ' rbenv . update'''
path = path or _rbenv_path ( runas ) path = os . path . expanduser ( path ) return _update_rbenv ( path , runas ) and _update_ruby_build ( path , runas )
def PauseHunt ( hunt_id , reason = None ) : """Pauses a hunt with a given id ."""
hunt_obj = data_store . REL_DB . ReadHuntObject ( hunt_id ) if hunt_obj . hunt_state != hunt_obj . HuntState . STARTED : raise OnlyStartedHuntCanBePausedError ( hunt_obj ) data_store . REL_DB . UpdateHuntObject ( hunt_id , hunt_state = hunt_obj . HuntState . PAUSED , hunt_state_comment = reason ) data_store . REL_D...
def year ( columns , name = None ) : """Creates the grammar for a field containing a year . : param columns : the number of columns for the year : param name : the name of the field : return :"""
if columns < 0 : # Can ' t have negative size raise BaseException ( ) field = numeric ( columns , name ) # Parse action field . addParseAction ( _to_year ) return field
def sanitize_strings_for_openshift ( str1 , str2 = '' , limit = LABEL_MAX_CHARS , separator = '-' , label = True ) : """OpenShift requires labels to be no more than 64 characters and forbids any characters other than alphanumerics , . , and - . BuildConfig names are similar , but cannot contain / . Sanitize and...
filter_chars = VALID_LABEL_CHARS if label else VALID_BUILD_CONFIG_NAME_CHARS str1_san = '' . join ( filter ( filter_chars . match , list ( str1 ) ) ) str2_san = '' . join ( filter ( filter_chars . match , list ( str2 ) ) ) str1_chars = [ ] str2_chars = [ ] groups = ( ( str1_san , str1_chars ) , ( str2_san , str2_chars ...
def mask ( name , runtime = False , root = None ) : '''. . versionadded : : 2015.5.0 . . versionchanged : : 2015.8.12,2016.3.3,2016.11.0 On minions running systemd > = 205 , ` systemd - run ( 1 ) ` _ is now used to isolate commands run by this function from the ` ` salt - minion ` ` daemon ' s control group...
_check_for_unit_changes ( name ) cmd = 'mask --runtime' if runtime else 'mask' out = __salt__ [ 'cmd.run_all' ] ( _systemctl_cmd ( cmd , name , systemd_scope = True , root = root ) , python_shell = False , redirect_stderr = True ) if out [ 'retcode' ] != 0 : raise CommandExecutionError ( 'Failed to mask service \'%...
def covalent_bonds ( atoms , threshold = 1.1 ) : """Returns all the covalent bonds in a list of ` Atom ` pairs . Notes Uses information ` element _ data ` , which can be accessed directly through this module i . e . ` isambard . ampal . interactions . element _ data ` . Parameters atoms : [ ( ` Atom ` , `...
bonds = [ ] for a , b in atoms : bond_distance = ( element_data [ a . element . title ( ) ] [ 'atomic radius' ] + element_data [ b . element . title ( ) ] [ 'atomic radius' ] ) / 100 dist = distance ( a . _vector , b . _vector ) if dist <= bond_distance * threshold : bonds . append ( CovalentBond ( ...
def view ( grid ) : "Show a grid human - readably ."
p_mark , q_mark = player_marks ( grid ) return grid_format % tuple ( p_mark if by_p else q_mark if by_q else '.' for by_p , by_q in zip ( * map ( player_bits , grid ) ) )
def extend_left_to ( self , window , max_size ) : """Adjust the offset to start where the given window on our left ends if possible , but don ' t make yourself larger than max _ size . The resize will assure that the new window still contains the old window area"""
rofs = self . ofs - window . ofs_end ( ) nsize = rofs + self . size rofs -= nsize - min ( nsize , max_size ) self . ofs = self . ofs - rofs self . size += rofs
def Copy ( self , field_number = None ) : """Returns descriptor copy , optionally changing field number ."""
new_args = self . _kwargs . copy ( ) if field_number is not None : new_args [ "field_number" ] = field_number return ProtoRDFValue ( rdf_type = self . original_proto_type_name , default = getattr ( self , "default" , None ) , ** new_args )
def is_public ( self ) : """` ` True ` ` if this is a public key , otherwise ` ` False ` `"""
return isinstance ( self . _key , Public ) and not isinstance ( self . _key , Private )
def fetch_libzmq ( savedir ) : """download and extract libzmq"""
dest = pjoin ( savedir , 'zeromq' ) if os . path . exists ( dest ) : info ( "already have %s" % dest ) return path = fetch_archive ( savedir , libzmq_url , fname = libzmq , checksum = libzmq_checksum ) tf = tarfile . open ( path ) with_version = pjoin ( savedir , tf . firstmember . path ) tf . extractall ( save...
def update ( self , old , new ) : """Replace an element in the heap"""
i = self . rank [ old ] # change value at index i del self . rank [ old ] self . heap [ i ] = new self . rank [ new ] = i if old < new : # maintain heap order self . down ( i ) else : self . up ( i )
def ticket_tags_delete ( self , id , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / core / tags # remove - tags"
api_path = "/api/v2/tickets/{id}/tags.json" api_path = api_path . format ( id = id ) return self . call ( api_path , method = "DELETE" , ** kwargs )
def get_subtree ( self , tree , xpath_str ) : """Return a subtree given an lxml XPath ."""
return tree . xpath ( xpath_str , namespaces = self . namespaces )
def tanh_warp ( x , n , l1 , l2 , lw , x0 ) : r"""Implements a tanh warping function and its derivative . . . math : : l = \ frac { l _ 1 + l _ 2 } { 2 } - \ frac { l _ 1 - l _ 2 } { 2 } \ tanh \ frac { x - x _ 0 } { l _ w } Parameters x : float or array of float Locations to evaluate the function at . ...
if n == 0 : return ( l1 + l2 ) / 2.0 - ( l1 - l2 ) / 2.0 * scipy . tanh ( ( x - x0 ) / lw ) elif n == 1 : return - ( l1 - l2 ) / ( 2.0 * lw ) * ( scipy . cosh ( ( x - x0 ) / lw ) ) ** ( - 2.0 ) else : raise NotImplementedError ( "Only derivatives up to order 1 are supported!" )
def package_info ( self , package , abspath = True ) : """Return a dictionary with package information ."""
return self . _call_and_parse ( [ 'info' , package , '--json' ] , abspath = abspath )
def list_contacts ( self , ** kwargs ) : """List all contacts , optionally filtered by a query . Specify filters as query keyword argument , such as : query = email is abc @ xyz . com , query = mobile is 1234567890, query = phone is 1234567890, contacts can be filtered by name such as ; letter = Prenit ...
url = 'contacts.json?' if 'query' in kwargs . keys ( ) : filter_query = kwargs . pop ( 'query' ) url = url + "query={}" . format ( filter_query ) if 'state' in kwargs . keys ( ) : state_query = kwargs . pop ( 'state' ) url = url + "state={}" . format ( state_query ) if 'letter' in kwargs . keys ( ) : ...
def get_uri ( self , curie ) : '''Get a URI from a CURIE'''
if curie is None : return None parts = curie . split ( ':' ) if len ( parts ) == 1 : if curie != '' : LOG . error ( "Not a properly formed curie: \"%s\"" , curie ) return None prefix = parts [ 0 ] if prefix in self . curie_map : return '%s%s' % ( self . curie_map . get ( prefix ) , curie [ ( cur...
def load_from_json ( db_file , language = DEFAULT_LANG ) : """Parses the JSON data and returns it : param db _ file : File and path pointing to the JSON file to parse : param language : The user ' s language ( en , es , etc . ) : raises : All kind of exceptions if the file doesn ' t exist or JSON is invalid...
# There are a couple of things I don ' t do here , and are on purpose : # - I want to fail if the file doesn ' t exist # - I want to fail if the file doesn ' t contain valid JSON raw = json . loads ( file ( db_file ) . read ( ) ) # Here I don ' t do any error handling either , I expect the JSON files to # be valid data...
def error ( self ) : """Return an instance of Exception if any , else None . Actually check for a : class : ` TimeoutError ` or a : class : ` ExitCodeError ` ."""
if self . __timed_out : return TimeoutError ( self . session , self , "timeout" ) if self . __exit_code is not None and self . __expected_exit_code is not None and self . __exit_code != self . __expected_exit_code : return ExitCodeError ( self . session , self , 'bad exit code: Got %s' % self . __exit_code )
def reset_all ( self ) : """Resets all parameters to None"""
for item in self . inputs : setattr ( self , "_%s" % item , None ) self . stack = [ ]
def levelize_strength_or_aggregation ( to_levelize , max_levels , max_coarse ) : """Turn parameter into a list per level . Helper function to preprocess the strength and aggregation parameters passed to smoothed _ aggregation _ solver and rootnode _ solver . Parameters to _ levelize : { string , tuple , lis...
if isinstance ( to_levelize , tuple ) : if to_levelize [ 0 ] == 'predefined' : to_levelize = [ to_levelize ] max_levels = 2 max_coarse = 0 else : to_levelize = [ to_levelize for i in range ( max_levels - 1 ) ] elif isinstance ( to_levelize , str ) : if to_levelize == 'predefi...
def certify_printable ( value , nonprintable = False , required = True ) : """Certifier for human readable ( printable ) values . : param unicode value : The string to be certified . : param nonprintable : Whether the string can contain non - printable characters . Non - printable characters are allowed b...
certify_params ( ( certify_bool , 'nonprintable' , nonprintable ) , ) if certify_required ( value = value , required = required , ) : return _certify_printable ( value = value , nonprintable = nonprintable , required = required , )
def cell_key_val_gen ( iterable , shape , topleft = ( 0 , 0 ) ) : """Generator of row , col , value tuple from iterable of iterables it : Iterable of iterables \t Matrix that shall be mapped on target grid shape : Tuple of Integer \t Shape of target grid topleft : 2 - tuple of Integer \t Top left cell f...
top , left = topleft for __row , line in enumerate ( iterable ) : row = top + __row if row >= shape [ 0 ] : break for __col , value in enumerate ( line ) : col = left + __col if col >= shape [ 1 ] : break yield row , col , value
def install_requirements ( self , requires ) : """Install the listed requirements"""
# Temporarily install dependencies required by setup . py before trying to import them . sys . path [ 0 : 0 ] = [ 'setup-requires' ] pkg_resources . working_set . add_entry ( 'setup-requires' ) to_install = list ( self . missing_requirements ( requires ) ) if to_install : cmd = [ sys . executable , "-m" , "pip" , "...
def get_qpimage_raw ( self , idx = 0 ) : """Return QPImage without background correction"""
qpi = qpimage . QPImage ( h5file = self . path , h5mode = "r" , h5dtype = self . as_type , ) . copy ( ) # Remove previously performed background correction qpi . set_bg_data ( None ) # Force meta data for key in self . meta_data : qpi [ key ] = self . meta_data [ key ] # set identifier qpi [ "identifier" ] = self ....
def execute ( self ) : """Executes ` ` ansible - playbook ` ` and returns a string . : return : str"""
if self . _ansible_command is None : self . bake ( ) try : self . _config . driver . sanity_checks ( ) cmd = util . run_command ( self . _ansible_command , debug = self . _config . debug ) return cmd . stdout . decode ( 'utf-8' ) except sh . ErrorReturnCode as e : out = e . stdout . decode ( 'utf-8'...
def make_scratch_dirs ( file_mapping , dry_run = True ) : """Make any directories need in the scratch area"""
scratch_dirs = { } for value in file_mapping . values ( ) : scratch_dirname = os . path . dirname ( value ) scratch_dirs [ scratch_dirname ] = True for scratch_dirname in scratch_dirs : if dry_run : print ( "mkdir -f %s" % ( scratch_dirname ) ) else : try : os . makedirs ( sc...
def pref_update ( self , key , new_val ) : """Changes a preference value and saves it to disk"""
print ( 'Update and save pref from: %s=%r, to: %s=%r' % ( key , six . text_type ( self [ key ] ) , key , six . text_type ( new_val ) ) ) self . __setattr__ ( key , new_val ) return self . save ( )
def iterrowproxy ( self , cls = RowProxy ) : """Iterate over the resource as row proxy objects , which allow acessing colums as attributes . Like iterrows , but allows for setting a specific RowProxy class ."""
row_proxy = None headers = None for row in self : if not headers : headers = row row_proxy = cls ( headers ) continue yield row_proxy . set_row ( row )
def update ( self , updates = { } ) : """update csp _ default . json with dict if file empty add default - src and create dict"""
try : csp = self . read ( ) except : csp = { 'default-src' : "'self'" } self . write ( csp ) csp . update ( updates ) self . write ( csp )
def mime_type ( instance ) : """Ensure the ' mime _ type ' property of file objects comes from the Template column in the IANA media type registry ."""
mime_pattern = re . compile ( r'^(application|audio|font|image|message|model' '|multipart|text|video)/[a-zA-Z0-9.+_-]+' ) for key , obj in instance [ 'objects' ] . items ( ) : if ( 'type' in obj and obj [ 'type' ] == 'file' and 'mime_type' in obj ) : if enums . media_types ( ) : if obj [ 'mime_t...
def f_string_check ( self , original , loc , tokens ) : """Handle Python 3.6 format strings ."""
return self . check_py ( "36" , "format string" , original , loc , tokens )
def requestAvatar ( self , avatarId , mind , * interfaces ) : """Create Adder avatars for any IBoxReceiver request ."""
if IBoxReceiver in interfaces : return ( IBoxReceiver , Adder ( avatarId ) , lambda : None ) raise NotImplementedError ( )
def to_representation ( self , instance ) : """Serialize objects - > primitives ."""
# prepare OrderedDict geojson structure feature = OrderedDict ( ) # the list of fields that will be processed by get _ properties # we will remove fields that have been already processed # to increase performance on large numbers fields = list ( self . fields . values ( ) ) # optional id attribute if self . Meta . id_f...
def truncated_pareto_expval ( alpha , m , b ) : """Expected value of truncated Pareto distribution ."""
if alpha <= 1 : return inf part1 = ( m ** alpha ) / ( 1. - ( m / b ) ** alpha ) part2 = 1. * alpha / ( alpha - 1 ) part3 = ( 1. / ( m ** ( alpha - 1 ) ) - 1. / ( b ** ( alpha - 1. ) ) ) return part1 * part2 * part3
def _line_2_pair ( line ) : '''Return bash variable declaration as name - value pair . Name as lower case str . Value itself only without surrounding ' " ' ( if any ) . For example , _ line _ 2 _ pair ( ' NAME = " Ubuntu " ' ) will return ( ' name ' , ' Ubuntu ' )'''
key , val = line . split ( '=' ) return key . lower ( ) , val . strip ( '"' )
def get_fields ( Model , parent_field = "" , model_stack = None , stack_limit = 2 , excludes = [ 'permissions' , 'comment' , 'content_type' ] ) : """Given a Model , return a list of lists of strings with important stuff : [ ' test _ user _ _ user _ _ customuser ' , ' customuser ' , ' User ' , ' RelatedObject ' ] ...
out_fields = [ ] if model_stack is None : model_stack = [ ] # github . com / omab / python - social - auth / commit / d8637cec02422374e4102231488481170dc51057 if isinstance ( Model , basestring ) : app_label , model_name = Model . split ( '.' ) Model = models . get_model ( app_label , model_name ) fields = ...
def expr ( self ) : """expr : term ( ( ' + ' | ' - ' ) term ) *"""
node = self . term ( ) while self . token . nature in ( Nature . PLUS , Nature . MINUS ) : token = self . token if token . nature == Nature . PLUS : self . _process ( Nature . PLUS ) elif token . nature == Nature . MINUS : self . _process ( Nature . MINUS ) else : self . _error (...
def run_migrations_online ( config ) : """Run migrations in ' online ' mode . In this scenario we need to create an Engine and associate a connection with the context ."""
connectable = engine_from_config ( config . get_section ( config . config_ini_section ) , prefix = 'sqlalchemy.' , poolclass = pool . NullPool ) with connectable . connect ( ) as connection : alembic . context . configure ( connection = connection ) with alembic . context . begin_transaction ( ) : alemb...
def doFind ( self , WHAT = { } , SORT = [ ] , SKIP = None , MAX = None , LOP = 'AND' , ** params ) : """This function will perform the command - find ."""
self . _preFind ( WHAT , SORT , SKIP , MAX , LOP ) for key in params : self . _addDBParam ( key , params [ key ] ) try : return self . _doAction ( '-find' ) except FMServerError as e : if e . args [ 0 ] in [ 401 , 8 ] : return [ ]
def read_by_indexes ( table_name , index_name_values = None ) : """Index reader ."""
req = datastore . RunQueryRequest ( ) query = req . query query . kind . add ( ) . name = table_name if not index_name_values : index_name_values = [ ] for name , val in index_name_values : queryFilter = query . filter . property_filter queryFilter . property . name = name queryFilter . operator = datas...
def is_compatible_space ( space , base_space ) : """Check compatibility of a ( power ) space with a base space . Compatibility here means that the spaces are equal or ` ` space ` ` is a non - empty power space of ` ` base _ space ` ` up to different data types . Parameters space , base _ space : ` LinearS...
if isinstance ( base_space , ProductSpace ) : return False if isinstance ( space , ProductSpace ) : if not space . is_power_space : return False elif len ( space ) == 0 : return False else : return is_compatible_space ( space [ 0 ] , base_space ) else : if hasattr ( space , '...
def _decorate ( flush = True , attempts = 1 , only_authenticate = False ) : """Wraps the given function such that conn . login ( ) or conn . authenticate ( ) is executed . Doing the real work for autologin and autoauthenticate to minimize code duplication . : type flush : bool : param flush : Whether to f...
def decorator ( function ) : def decorated ( job , host , conn , * args , ** kwargs ) : failed = 0 while True : try : if only_authenticate : conn . authenticate ( flush = flush ) else : conn . login ( flush = flush )...
def set_selection ( self , time , freqs , blarr , calname = '' , radec = ( ) , dist = 0 , spwind = [ ] , pols = [ 'XX' , 'YY' ] ) : """Set select parameter that defines spectral window , time , or any other selection . time ( in mjd ) defines the time to find solutions near for given calname . freqs ( in Hz ) i...
self . freqs = freqs self . chansize = freqs [ 1 ] - freqs [ 0 ] self . select = self . complete # use only complete solution sets ( set during parse ) self . blarr = blarr if spwind : self . logger . warn ( 'spwind option not used for telcal_sol. Applied based on freqs.' ) if radec : self . logger . warn ( 'ra...
def _num_values ( self , zVar , varNum ) : '''Determines the number of values in a record . Set zVar = True if this is a zvariable .'''
values = 1 if ( zVar == True ) : numDims = self . zvarsinfo [ varNum ] [ 2 ] dimSizes = self . zvarsinfo [ varNum ] [ 3 ] dimVary = self . zvarsinfo [ varNum ] [ 4 ] else : numDims = self . rvarsinfo [ varNum ] [ 2 ] dimSizes = self . rvarsinfo [ varNum ] [ 3 ] dimVary = self . rvarsinfo [ varNu...
def base_path ( self ) : """Base absolute path of container ."""
return os . path . join ( self . conn . abs_root , self . name )
def _axis_levels ( self , axis ) : """Return the number of levels in the labels taking into account the axis . Get the number of levels for the columns ( 0 ) or rows ( 1 ) ."""
ax = self . _axis ( axis ) return 1 if not hasattr ( ax , 'levels' ) else len ( ax . levels )
def delete_user ( username , token_manager = None , app_url = defaults . APP_URL ) : """delete a user by its account _ id and with the access _ token from that same user as only a user may delete him / her - self"""
account_id = get_account_id ( username , token_manager = token_manager , app_url = app_url ) headers = token_manager . get_access_token_headers ( ) auth_url = environment . get_auth_url ( app_url = app_url ) url = "%s/api/v1/accounts/%s" % ( auth_url , account_id ) response = requests . delete ( url , headers = headers...
def import_formulas ( self ) : """Import formulas specified in : attr : ` parameters ` . : returns : formulas : rtype : dict"""
# TODO : unit tests ! # TODO : move this to somewhere else and call it " importy " , maybe # core . _ _ init _ _ . py since a lot of modules might use it . module = self . meta . module # module read from parameters package = getattr ( self . meta , 'package' , None ) # package read from meta name = package + module if...
def merge_tree ( cwd , ref1 , ref2 , base = None , user = None , password = None , ignore_retcode = False , output_encoding = None ) : '''. . versionadded : : 2015.8.0 Interface to ` git - merge - tree ( 1 ) ` _ , shows the merge results and conflicts from a 3 - way merge without touching the index . cwd Th...
cwd = _expand_path ( cwd , user ) command = [ 'git' , 'merge-tree' ] if base is None : try : base = merge_base ( cwd , refs = [ ref1 , ref2 ] , output_encoding = output_encoding ) except ( SaltInvocationError , CommandExecutionError ) : raise CommandExecutionError ( 'Unable to determine merge ba...
def load_ssl_context ( cert_file , pkey_file = None , protocol = None ) : """Loads SSL context from cert / private key files and optional protocol . Many parameters are directly taken from the API of : py : class : ` ssl . SSLContext ` . : param cert _ file : Path of the certificate to use . : param pkey _ ...
if protocol is None : protocol = ssl . PROTOCOL_SSLv23 ctx = _SSLContext ( protocol ) ctx . load_cert_chain ( cert_file , pkey_file ) return ctx
def from_csv ( cls , filename ) : """Create gyro stream from CSV data Load data from a CSV file . The data must be formatted with three values per line : ( x , y , z ) where x , y , z is the measured angular velocity ( in radians ) of the specified axis . Parameters filename : str Path to the CSV file ...
instance = cls ( ) instance . data = np . loadtxt ( filename , delimiter = ',' ) return instance
def get_all_filters ( self , server_id ) : """Return all indication filters in a WBEM server . This function contacts the WBEM server and retrieves the indication filters by enumerating the instances of CIM class " CIM _ IndicationFilter " in the Interop namespace of the WBEM server . Parameters : server ...
# Validate server _ id server = self . _get_server ( server_id ) return server . conn . EnumerateInstances ( 'CIM_IndicationFilter' , namespace = server . interop_ns )
def get_filename ( response ) : """Derive a filename from the given response . > > > import requests > > > from planet . api import utils > > > response = requests . Response ( ) > > > response . headers = { . . . ' date ' : ' Thu , 14 Feb 2019 16:13:26 GMT ' , . . . ' last - modified ' : ' Wed , 22 Nov...
name = ( get_filename_from_headers ( response . headers ) or get_filename_from_url ( response . url ) or get_random_filename ( response . headers . get ( 'content-type' ) ) ) return name
def _regex_from_encoded_pattern ( s ) : """' foo ' - > re . compile ( re . escape ( ' foo ' ) ) ' / foo / ' - > re . compile ( ' foo ' ) ' / foo / i ' - > re . compile ( ' foo ' , re . I )"""
if s . startswith ( '/' ) and s . rfind ( '/' ) != 0 : # Parse it : / PATTERN / FLAGS idx = s . rfind ( '/' ) pattern , flags_str = s [ 1 : idx ] , s [ idx + 1 : ] flag_from_char = { "i" : re . IGNORECASE , "l" : re . LOCALE , "s" : re . DOTALL , "m" : re . MULTILINE , "u" : re . UNICODE , } flags = 0 ...
def positive_float ( s ) : """Ensure argument is a positive real number and return it as float . To be used as type in argparse arguments ."""
err_msg = "must be a positive number, not %r" % s try : value = float ( s ) except ValueError : raise argparse . ArgumentTypeError ( err_msg ) if value <= 0 : raise argparse . ArgumentTypeError ( err_msg ) return value
def convert_cmd_scl ( self , scl , cmd ) : """wrapping command in " scl enable " call and adds proper PATH"""
# load default SCL prefix to PATH prefix = self . policy . get_default_scl_prefix ( ) # read prefix from / etc / scl / prefixes / $ { scl } and strip trailing ' \ n ' try : prefix = open ( '/etc/scl/prefixes/%s' % scl , 'r' ) . read ( ) . rstrip ( '\n' ) except Exception as e : self . _log_error ( "Failed to fi...
def list_catalogs ( results = 30 , start = 0 ) : """Returns list of all catalogs created on this API key Args : Kwargs : results ( int ) : An integer number of results to return start ( int ) : An integer starting value for the result set Returns : A list of catalog objects Example : > > > catalog ....
result = util . callm ( "%s/%s" % ( 'catalog' , 'list' ) , { 'results' : results , 'start' : start } ) cats = [ Catalog ( ** util . fix ( d ) ) for d in result [ 'response' ] [ 'catalogs' ] ] start = result [ 'response' ] [ 'start' ] total = result [ 'response' ] [ 'total' ] return ResultList ( cats , start , total )
def refresh_content ( self , order = None , name = None ) : """Re - download all subscriptions and reset the page index"""
# reddit . get _ my _ subreddits ( ) does not support sorting by order if order : self . term . flash ( ) return with self . term . loader ( ) : self . content = SubscriptionContent . from_user ( self . reddit , self . term . loader , self . content_type ) if not self . term . loader . exception : self ...
def read_fcs_data_segment ( buf , begin , end , datatype , num_events , param_bit_widths , big_endian , param_ranges = None ) : """Read DATA segment of FCS file . Parameters buf : file - like object Buffer containing data to interpret as DATA segment . begin : int Offset ( in bytes ) to first byte of DATA...
num_params = len ( param_bit_widths ) if ( param_ranges is not None and len ( param_ranges ) != num_params ) : raise ValueError ( "param_bit_widths and param_ranges must have same" + " length" ) shape = ( int ( num_events ) , num_params ) if datatype == 'I' : # Check if all parameters fit into preexisting data type...
def _compute_anelastic_attenuation_term ( self , C , rrup , mag ) : """Compute magnitude - distance scaling term as defined in equation 21, page 2291 ( Tavakoli and Pezeshk , 2005)"""
r = ( rrup ** 2. + ( C [ 'c5' ] * np . exp ( C [ 'c6' ] * mag + C [ 'c7' ] * ( 8.5 - mag ) ** 2.5 ) ) ** 2. ) ** .5 f3 = ( ( C [ 'c4' ] + C [ 'c13' ] * mag ) * np . log ( r ) + ( C [ 'c8' ] + C [ 'c12' ] * mag ) * r ) return f3
def getRejecter ( self ) : """If the Analysis Request has been rejected , returns the user who did the rejection . If it was not rejected or the current user has not enough privileges to access to this information , returns None ."""
wtool = getToolByName ( self , 'portal_workflow' ) mtool = getToolByName ( self , 'portal_membership' ) # noinspection PyBroadException try : review_history = wtool . getInfoFor ( self , 'review_history' ) except : # noqa FIXME : remove blind except ! return None for items in review_history : action = items...
def set_property ( self , ** kwargs ) : """set any property of the underlying nparray object"""
if not isinstance ( self . _value , nparray . ndarray ) : raise ValueError ( "value is not a nparray object" ) for property , value in kwargs . items ( ) : setattr ( self . _value , property , value )
def stat_print ( classes , class_stat , overall_stat , digit = 5 , overall_param = None , class_param = None ) : """Return printable statistics table . : param classes : classes list : type classes : list : param class _ stat : statistic result for each class : type class _ stat : dict : param overall _ s...
shift = max ( map ( len , PARAMS_DESCRIPTION . values ( ) ) ) + 5 classes_len = len ( classes ) overall_stat_keys = sorted ( overall_stat . keys ( ) ) result = "" if isinstance ( overall_param , list ) : if set ( overall_param ) <= set ( overall_stat_keys ) : overall_stat_keys = sorted ( overall_param ) if ...
def _convert_to_identifier_json ( self , address_data ) : """Convert input address data into json format"""
if isinstance ( address_data , str ) : # allow just passing a slug string . return { "slug" : address_data } if isinstance ( address_data , tuple ) and len ( address_data ) > 0 : address_json = { "address" : address_data [ 0 ] } if len ( address_data ) > 1 : address_json [ "zipcode" ] = address_data...
def fit ( self , data ) : """Fits a transformer using the SFrame ` data ` . Parameters data : SFrame The data used to fit the transformer . Returns self ( A fitted object ) See Also transform , fit _ transform"""
self . _setup_from_data ( data ) self . transform_chain . fit ( data ) self . __proxy__ . update ( { "fitted" : True } ) return self
def powered_up ( self ) : """Returns True whether the card is " powered up " ."""
if not self . data . scripts . powered_up : return False for script in self . data . scripts . powered_up : if not script . check ( self ) : return False return True
def init_log_file ( self ) : """redirects stdout to a log file to prevent printing to a hanging terminal when dealing with the compiled binary ."""
# redirect terminal output self . old_stdout = sys . stdout sys . stdout = open ( os . path . join ( self . WD , "demag_gui.log" ) , 'w+' )
def validate_args ( f ) : """Ensures that * args consist of a consistent type : param f : any client method with * args parameter : return : function f"""
def wrapper ( self , args ) : arg_types = set ( [ type ( arg ) for arg in args ] ) if len ( arg_types ) > 1 : raise TypeError ( "Mixed input types are not allowed" ) elif list ( arg_types ) [ 0 ] not in ( dict , str ) : raise TypeError ( "Only dict and str types accepted" ) return f ( se...
def _pre_commit ( files , options ) : """Run the check on files of the added version . They might be different than the one on disk . Equivalent than doing a git stash , check , and git stash pop ."""
errors = [ ] tmpdir = mkdtemp ( ) files_to_check = [ ] try : for ( file_ , content ) in files : # write staged version of file to temporary directory dirname , filename = os . path . split ( os . path . abspath ( file_ ) ) prefix = os . path . commonprefix ( [ dirname , tmpdir ] ) dirname = ...
def pipe_wait ( popens ) : """Given an array of Popen objects returned by the pipe method , wait for all processes to terminate and return the array with their return values . Taken from http : / / www . enricozini . org / 2009 / debian / python - pipes /"""
# Avoid mutating the passed copy popens = copy . copy ( popens ) results = [ 0 ] * len ( popens ) while popens : last = popens . pop ( - 1 ) results [ len ( popens ) ] = last . wait ( ) return results
def dbscan ( points , eps , minpts ) : """Implementation of [ DBSCAN ] _ ( * A density - based algorithm for discovering clusters in large spatial databases with noise * ) . It accepts a list of points ( lat , lon ) and returns the labels associated with the points . References . . [ DBSCAN ] Ester , M . , ...
next_label = 0 n = len ( points ) labels = [ None ] * n distance_matrix = compute_distance_matrix ( points ) neighbors = [ get_neighbors ( distance_matrix , i , eps ) for i in range ( n ) ] for i in range ( n ) : if labels [ i ] is not None : continue if len ( neighbors [ i ] ) < minpts : contin...