signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def double ( self ) :
"""Return a new point that is twice the old .""" | if self == INFINITY :
return INFINITY
# X9.62 B . 3:
p = self . __curve . p ( )
a = self . __curve . a ( )
l = ( ( 3 * self . __x * self . __x + a ) * numbertheory . inverse_mod ( 2 * self . __y , p ) ) % p
x3 = ( l * l - 2 * self . __x ) % p
y3 = ( l * ( self . __x - x3 ) - self . __y ) % p
return Point ( self . _... |
def is_gauge ( md_type ) :
"""Whether a given MetricDescriptorType value is a gauge .
: type md _ type : int
: param md _ type : A MetricDescriptorType enum value .""" | if md_type not in metric_descriptor . MetricDescriptorType :
raise ValueError
# pragma : NO COVER
return md_type in { metric_descriptor . MetricDescriptorType . GAUGE_INT64 , metric_descriptor . MetricDescriptorType . GAUGE_DOUBLE , metric_descriptor . MetricDescriptorType . GAUGE_DISTRIBUTION } |
def _send_breakpoint_condition_exception ( self , thread , conditional_breakpoint_exception_tuple ) :
"""If conditional breakpoint raises an exception during evaluation
send exception details to java""" | thread_id = get_thread_id ( thread )
# conditional _ breakpoint _ exception _ tuple - should contain 2 values ( exception _ type , stacktrace )
if conditional_breakpoint_exception_tuple and len ( conditional_breakpoint_exception_tuple ) == 2 :
exc_type , stacktrace = conditional_breakpoint_exception_tuple
int_c... |
def console_width ( kwargs ) :
"""" Determine console _ width .""" | if sys . platform . startswith ( 'win' ) :
console_width = _find_windows_console_width ( )
else :
console_width = _find_unix_console_width ( )
_width = kwargs . get ( 'width' , None )
if _width :
console_width = _width
else :
if not console_width :
console_width = 80
return console_width |
def const_return ( func ) :
"""> > > from Redy . Magic . Classic import const _ return
> > > @ const _ return
> > > def f ( x ) :
> > > return x
> > > r1 = f ( 1)
> > > assert r1 is 1 and r1 is f ( 2)""" | result = _undef
def ret_call ( * args , ** kwargs ) :
nonlocal result
if result is _undef :
result = func ( * args , ** kwargs )
return result
return ret_call |
def check_sockets ( self ) :
'''Check for new messages on sockets and respond accordingly .
. . versionchanged : : 0.11.3
Update routes table by setting ` ` df _ routes ` ` property of
: attr : ` parent . canvas _ slave ` .
. . versionchanged : : 0.12
Update ` ` dynamic _ electrode _ state _ shapes ` ` la... | try :
msg_frames = ( self . command_socket . recv_multipart ( zmq . NOBLOCK ) )
except zmq . Again :
pass
else :
self . on_command_recv ( msg_frames )
try :
msg_frames = ( self . subscribe_socket . recv_multipart ( zmq . NOBLOCK ) )
source , target , msg_type , msg_json = msg_frames
if ( ( sourc... |
def load_directory ( self , top_path , followlinks ) :
"""Traverse top _ path directory and save patterns in any . ddsignore files found .
: param top _ path : str : directory name we should traverse looking for ignore files
: param followlinks : boolean : should we traverse symbolic links""" | for dir_name , child_dirs , child_files in os . walk ( top_path , followlinks = followlinks ) :
for child_filename in child_files :
if child_filename == DDS_IGNORE_FILENAME :
pattern_lines = self . _read_non_empty_lines ( dir_name , child_filename )
self . add_patterns ( dir_name , p... |
def analysis_provenance_details_extractor ( impact_report , component_metadata ) :
"""Extracting provenance details of layers .
This extractor would be the main provenance details extractor which produce
tree view provenance details .
: param impact _ report : the impact report that acts as a proxy to fetch
... | context = { }
extra_args = component_metadata . extra_args
provenance_format_args = resolve_from_dictionary ( extra_args , 'provenance_format' )
keywords_order = [ 'title' , 'source' , 'layer_purpose' , 'layer_geometry' , 'hazard' , 'exposure' , 'hazard_category' , 'exposure_unit' , 'value_map' , 'value_maps' , 'inasaf... |
def wrap ( function , * args , ** kwargs ) :
'''Wrap a function that returns a request with some exception handling''' | try :
req = function ( * args , ** kwargs )
logger . debug ( 'Got %s: %s' , req . status_code , req . content )
if req . status_code == 200 :
return req
else :
raise ClientException ( req . reason , req . content )
except ClientException :
raise
except Exception as exc :
raise Cl... |
def to_rfc3339 ( timestamp ) :
"""Converts ` ` timestamp ` ` to an RFC 3339 date string format .
` ` timestamp ` ` can be either a ` ` datetime . datetime ` ` or a
` ` datetime . timedelta ` ` . Instances of the later are assumed to be a delta
with the beginining of the unix epoch , 1st of January , 1970
Th... | if isinstance ( timestamp , datetime . datetime ) :
timestamp = timestamp - _EPOCH_START
if not isinstance ( timestamp , datetime . timedelta ) :
_logger . error ( u'Could not convert %s to a rfc3339 time,' , timestamp )
raise ValueError ( u'Invalid timestamp type' )
return strict_rfc3339 . timestamp_to_rfc... |
def compute_curl ( self , vector_field ) :
"""Computes the curl of a vector field over the mesh . While the vector
field is point - based , the curl will be cell - based . The approximation is
based on
. . math : :
n \\ cdot curl ( F ) = \\ lim _ { A \\ to 0 } | A | ^ { - 1 } < \\ int _ { dGamma } , F > dr ... | # Compute the projection of A on the edge at each edge midpoint .
# Take the average of ` vector _ field ` at the endpoints to get the
# approximate value at the edge midpoint .
A = 0.5 * numpy . sum ( vector_field [ self . idx_hierarchy ] , axis = 0 )
# sum of < edge , A > for all three edges
sum_edge_dot_A = numpy . ... |
def main ( self , ignored_argv = ( '' , ) ) :
"""Blocking main function for TensorBoard .
This method is called by ` tensorboard . main . run _ main ` , which is the
standard entrypoint for the tensorboard command line program . The
configure ( ) method must be called first .
Args :
ignored _ argv : Do no... | self . _install_signal_handler ( signal . SIGTERM , "SIGTERM" )
if self . flags . inspect :
logger . info ( 'Not bringing up TensorBoard, but inspecting event files.' )
event_file = os . path . expanduser ( self . flags . event_file )
efi . inspect ( self . flags . logdir , event_file , self . flags . tag )... |
def log_predictive_density ( self , x_test , y_test , Y_metadata = None ) :
"""Calculation of the log predictive density . Notice we add
the jacobian of the warping function here .
. . math :
p ( y _ { * } | D ) = p ( y _ { * } | f _ { * } ) p ( f _ { * } | \ mu _ { * } \\ sigma ^ { 2 } _ { * } )
: param x ... | mu_star , var_star = self . _raw_predict ( x_test )
fy = self . warping_function . f ( y_test )
ll_lpd = self . likelihood . log_predictive_density ( fy , mu_star , var_star , Y_metadata = Y_metadata )
return ll_lpd + np . log ( self . warping_function . fgrad_y ( y_test ) ) |
async def restore_storage_configuration ( self ) :
"""Restore machine ' s storage configuration to its initial state .""" | self . _data = await self . _handler . restore_storage_configuration ( system_id = self . system_id ) |
def _convertNonZeroToFailure ( self , res ) :
"utility method to handle the result of getProcessOutputAndValue" | ( stdout , stderr , code ) = res
if code != 0 :
raise EnvironmentError ( 'command failed with exit code %d: %s' % ( code , stderr ) )
return ( stdout , stderr , code ) |
def add ( zpool , * vdevs , ** kwargs ) :
'''Add the specified vdev \' s to the given storage pool
zpool : string
Name of storage pool
vdevs : string
One or more devices
force : boolean
Forces use of device
CLI Example :
. . code - block : : bash
salt ' * ' zpool . add myzpool / path / to / vdev1 ... | # # Configure pool
# NOTE : initialize the defaults
flags = [ ]
target = [ ]
# NOTE : set extra config based on kwargs
if kwargs . get ( 'force' , False ) :
flags . append ( '-f' )
# NOTE : append the pool name and specifications
target . append ( zpool )
target . extend ( vdevs )
# # Update storage pool
res = __sa... |
def from_object ( self , obj ) :
"""Update the values from the given object .
Objects are usually either modules or classes .
Just the uppercase variables in that object are stored in the config .
Example usage : :
from yourapplication import default _ config
app . config . from _ object ( default _ confi... | for key in dir ( obj ) :
if key . isupper ( ) :
self [ key ] = getattr ( obj , key ) |
def build ( self ) :
"""Creates the objects from the JSON response""" | if self . json [ 'sys' ] [ 'type' ] == 'Array' :
if any ( k in self . json for k in [ 'nextSyncUrl' , 'nextPageUrl' ] ) :
return SyncPage ( self . json , default_locale = self . default_locale , localized = True )
return self . _build_array ( )
return self . _build_single ( ) |
async def set_discovery_enabled ( self ) :
"""Enable bluetooth discoverablility .""" | endpoint = '/setup/bluetooth/discovery'
data = { "enable_discovery" : True }
url = API . format ( ip = self . _ipaddress , endpoint = endpoint )
try :
async with async_timeout . timeout ( 5 , loop = self . _loop ) :
response = await self . _session . post ( url , headers = HEADERS , data = json . dumps ( da... |
def push ( self , targets , jobs = None , remote = None , show_checksums = False ) :
"""Push data items in a cloud - agnostic way .
Args :
targets ( list ) : list of targets to push to the cloud .
jobs ( int ) : number of jobs that can be running simultaneously .
remote ( dvc . remote . base . RemoteBase ) ... | return self . repo . cache . local . push ( targets , jobs = jobs , remote = self . _get_cloud ( remote , "push" ) , show_checksums = show_checksums , ) |
def wait_for_logs_matching ( container , matcher , timeout = 10 , encoding = 'utf-8' , ** logs_kwargs ) :
"""Wait for matching log line ( s ) from the given container by streaming the
container ' s stdout and / or stderr outputs .
Each log line is decoded and any trailing whitespace is stripped before the
lin... | try :
for line in stream_logs ( container , timeout = timeout , ** logs_kwargs ) : # Drop the trailing newline
line = line . decode ( encoding ) . rstrip ( )
if matcher ( line ) :
return line
except TimeoutError :
raise TimeoutError ( '\n' . join ( [ ( 'Timeout ({}s) waiting for logs... |
def delete_all_possible_task_files ( self , courseid , taskid ) :
"""Deletes all possibles task files in directory , to allow to change the format""" | if not id_checker ( courseid ) :
raise InvalidNameException ( "Course with invalid name: " + courseid )
if not id_checker ( taskid ) :
raise InvalidNameException ( "Task with invalid name: " + taskid )
task_fs = self . get_task_fs ( courseid , taskid )
for ext in self . get_available_task_file_extensions ( ) :
... |
def return_an_error ( * args ) :
'''List of errors
Put all errors into a list of errors
ref : http : / / jsonapi . org / format / # errors
Args :
* args : A tuple contain errors
Returns :
A dictionary contains a list of errors''' | list_errors = [ ]
list_errors . extend ( list ( args ) )
errors = { 'errors' : list_errors }
return errors |
def is_horz_aligned ( c ) :
"""Return True if all the components of c are horizontally aligned .
Horizontal alignment means that the bounding boxes of each Mention of c
shares a similar y - axis value in the visual rendering of the document .
: param c : The candidate to evaluate
: rtype : boolean""" | return all ( [ _to_span ( c [ i ] ) . sentence . is_visual ( ) and bbox_horz_aligned ( bbox_from_span ( _to_span ( c [ i ] ) ) , bbox_from_span ( _to_span ( c [ 0 ] ) ) ) for i in range ( len ( c ) ) ] ) |
def listen_error_messages_raylet ( worker , task_error_queue , threads_stopped ) :
"""Listen to error messages in the background on the driver .
This runs in a separate thread on the driver and pushes ( error , time )
tuples to the output queue .
Args :
worker : The worker class that this thread belongs to ... | worker . error_message_pubsub_client = worker . redis_client . pubsub ( ignore_subscribe_messages = True )
# Exports that are published after the call to
# error _ message _ pubsub _ client . subscribe and before the call to
# error _ message _ pubsub _ client . listen will still be processed in the loop .
# Really we ... |
def request_spot_instances ( self , price , image_id , count = 1 , type = 'one-time' , valid_from = None , valid_until = None , launch_group = None , availability_zone_group = None , key_name = None , security_groups = None , user_data = None , addressing_type = None , instance_type = 'm1.small' , placement = None , ke... | params = { 'LaunchSpecification.ImageId' : image_id , 'Type' : type , 'SpotPrice' : price }
if count :
params [ 'InstanceCount' ] = count
if valid_from :
params [ 'ValidFrom' ] = valid_from
if valid_until :
params [ 'ValidUntil' ] = valid_until
if launch_group :
params [ 'LaunchGroup' ] = launch_group
i... |
def _get_host_switches ( self , host_id ) :
"""Get switch IPs from configured host mapping .
This method is used to extract switch information
from transactions where VNIC _ TYPE is normal .
Information is extracted from ini file which
is stored in _ nexus _ switches .
: param host _ id : host _ name from... | all_switches = set ( )
active_switches = set ( )
try :
host_list = nxos_db . get_host_mappings ( host_id )
for mapping in host_list :
all_switches . add ( mapping . switch_ip )
if self . is_switch_active ( mapping . switch_ip ) :
active_switches . add ( mapping . switch_ip )
except e... |
def det_residual ( model , guess , start , final , shocks , diff = True , jactype = 'sparse' ) :
'''Computes the residuals , the derivatives of the stacked - time system .
: param model : an fga model
: param guess : the guess for the simulated values . An ` ( n _ s . n _ x ) x N ` array ,
where n _ s is the ... | # TODO : compute a sparse derivative and ensure the solvers can deal with it
n_s = len ( model . symbols [ 'states' ] )
n_x = len ( model . symbols [ 'controls' ] )
# n _ e = len ( model . symbols [ ' shocks ' ] )
N = guess . shape [ 0 ]
p = model . calibration [ 'parameters' ]
f = model . functions [ 'arbitrage' ]
g =... |
def GetNextWrittenEventSource ( self ) :
"""Retrieves the next event source that was written after open .
Returns :
EventSource : event source or None if there are no newly written ones .
Raises :
IOError : when the storage writer is closed .
OSError : when the storage writer is closed .""" | if not self . _storage_file :
raise IOError ( 'Unable to read from closed storage writer.' )
event_source = self . _storage_file . GetEventSourceByIndex ( self . _written_event_source_index )
if event_source :
self . _written_event_source_index += 1
return event_source |
def issue ( self , issue_instance_id ) :
"""Select an issue .
Parameters :
issue _ instance _ id : int id of the issue instance to select
Note : We are selecting issue instances , even though the command is called
issue .""" | with self . db . make_session ( ) as session :
selected_issue = ( session . query ( IssueInstance ) . filter ( IssueInstance . id == issue_instance_id ) . scalar ( ) )
if selected_issue is None :
self . warning ( f"Issue {issue_instance_id} doesn't exist. " "Type 'issues' for available issues." )
... |
def has_credentials_stored ( ) :
"""Return ' auth token ' string , if the user credentials are already stored""" | try :
with open ( credentials_file , 'r' ) as f :
token = f . readline ( ) . strip ( )
id = f . readline ( ) . strip ( )
return token
except Exception , e :
return False |
def _set_alarm_sample ( self , v , load = False ) :
"""Setter method for alarm _ sample , mapped from YANG variable / rmon / alarm _ entry / alarm _ sample ( alarm - sample - type )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ alarm _ sample is considered as a privat... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'delta' : { 'value' : 2 } , u'absolute' : { 'value' : 1 } } , ) , is_leaf = True , yang_name = "alarm-sample" , rest_name = "typ... |
def run_analyze_dimension_and_radius ( data , rmin , rmax , nradii , adjacency_method = 'brute' , adjacency_kwds = { } , fit_range = None , savefig = False , plot_name = 'dimension_plot.png' ) :
"""This function is used to estimate the doubling dimension ( approximately equal to the intrinsic
dimension ) by compu... | n , D = data . shape
radii = 10 ** ( np . linspace ( np . log10 ( rmin ) , np . log10 ( rmax ) , nradii ) )
dists = compute_largest_radius_distance ( data , rmax , adjacency_method , adjacency_kwds )
results = neighborhood_analysis ( dists , radii )
avg_neighbors = results [ 'avg_neighbors' ] . flatten ( )
radii = resu... |
def as_dict ( self ) :
"""returns a dictionary representation of the block and of all
component options""" | # TODO / FIXME : add selected information
if self . hidden :
rdict = { }
else :
def_selected = self . selected ( )
comps = [ { 'name' : comp . name , 'default' : comp . name in self . defaults , 'options' : comp . get_ordered_options ( ) if isinstance ( comp , Optionable ) else None } for comp in self ]
... |
def _derive_distinct_intervals ( self , rows ) :
"""Returns the set of distinct intervals in a row set .
: param list [ dict [ str , T ] ] rows : The rows set .
: rtype : set [ ( int , int ) ]""" | ret = set ( )
for row in rows :
self . _add_interval ( ret , ( row [ self . _key_start_date ] , row [ self . _key_end_date ] ) )
return ret |
def is_valid_matrix ( matrix ) :
"""Determines if a given n x n matrix is valid . A valid matrix is defined as a matrix in which every row
and every column contains all the integers from 1 to n ( inclusive ) .
Args :
matrix ( list of list of int ) : The input n x n matrix to be checked for validity .
Return... | m = len ( matrix )
n = len ( matrix [ 0 ] )
for i in range ( m ) :
s = set ( )
for j in range ( n ) :
s . add ( matrix [ i ] [ j ] )
if len ( s ) != n :
return False
for j in range ( n ) :
s = set ( )
for i in range ( m ) :
s . add ( matrix [ i ] [ j ] )
if len ( s ) != m... |
def findAll ( self , strSeq ) :
"""Same as find but returns a list of all occurences""" | arr = self . encode ( strSeq )
lst = [ ]
lst = self . _kmp_find ( arr [ 0 ] , self , lst )
return lst |
def AddAsMessage ( self , rdfvalue_in , source , mutation_pool = None ) :
"""Helper method to add rdfvalues as GrrMessages for testing .""" | self . Add ( rdf_flows . GrrMessage ( payload = rdfvalue_in , source = source ) , mutation_pool = mutation_pool ) |
def get_changelog_date_packager ( self ) :
"""Returns part of the changelog entry , containing date and packager .""" | try :
packager = subprocess . Popen ( 'rpmdev-packager' , stdout = subprocess . PIPE ) . communicate ( ) [ 0 ] . strip ( )
except OSError : # Hi John Doe , you should install rpmdevtools
packager = "John Doe <john@doe.com>"
logger . warn ( "Package rpmdevtools is missing, using default " "name: {0}." . form... |
def format_body ( self , description , sys_info = None , traceback = None ) :
"""Formats the body in plain text . ( add a series of ' - ' under each section
title ) .
: param description : Description of the issue , written by the user .
: param sys _ info : Optional system information string
: param log : ... | name = 'Description'
delim = '-' * 40
body = BODY_ITEM_TEMPLATE % { 'name' : name , 'value' : description , 'delim' : delim }
if traceback :
name = 'Traceback'
traceback = '\n' . join ( traceback . splitlines ( ) [ - NB_LINES_MAX : ] )
body += BODY_ITEM_TEMPLATE % { 'name' : name , 'value' : traceback , 'de... |
def reverse ( self ) :
"""Reverse the order of all items in the dictionary .
Example :
omd = omdict ( [ ( 1,1 ) , ( 1,11 ) , ( 1,111 ) , ( 2,2 ) , ( 3,3 ) ] )
omd . reverse ( )
omd . allitems ( ) = = [ ( 3,3 ) , ( 2,2 ) , ( 1,111 ) , ( 1,11 ) , ( 1,1 ) ]
Returns : < self > .""" | for key in six . iterkeys ( self . _map ) :
self . _map [ key ] . reverse ( )
self . _items . reverse ( )
return self |
def send ( self , * sender , ** kwargs ) :
"""Emit this signal on behalf of ` sender ` , passing on kwargs .
This is an extension of ` Signal . send ` that changes one thing :
Exceptions raised in calling the receiver are logged but do not fail""" | if len ( sender ) == 0 :
sender = None
elif len ( sender ) > 1 :
raise TypeError ( 'send() accepts only one positional argument, ' '%s given' % len ( sender ) )
else :
sender = sender [ 0 ]
if not self . receivers :
return [ ]
rv = list ( )
for receiver in self . receivers_for ( sender ) :
try :
... |
def tob ( data , enc = 'utf8' ) :
"""Convert anything to bytes""" | return data . encode ( enc ) if isinstance ( data , six . text_type ) else bytes ( data ) |
def extract_table ( self , source , destination_uris , job_id = None , job_id_prefix = None , location = None , project = None , job_config = None , retry = DEFAULT_RETRY , ) :
"""Start a job to extract a table into Cloud Storage files .
See
https : / / cloud . google . com / bigquery / docs / reference / rest ... | job_id = _make_job_id ( job_id , job_id_prefix )
if project is None :
project = self . project
if location is None :
location = self . location
job_ref = job . _JobReference ( job_id , project = project , location = location )
source = _table_arg_to_table_ref ( source , default_project = self . project )
if isi... |
def make_vertical_bar ( percentage , width = 1 ) :
"""Draws a vertical bar made of unicode characters .
: param value : A value between 0 and 100
: param width : How many characters wide the bar should be .
: returns : Bar as a String""" | bar = ' _▁▂▃▄▅▆▇█'
percentage //= 10
percentage = int ( percentage )
if percentage < 0 :
output = bar [ 0 ]
elif percentage >= len ( bar ) :
output = bar [ - 1 ]
else :
output = bar [ percentage ]
return output * width |
def WriteFileFooter ( self ) :
"""Writes file footer ( finishes the file ) .""" | if self . cur_file_size != self . cur_info . size :
raise IOError ( "Incorrect file size: st_size=%d, but written %d bytes." % ( self . cur_info . size , self . cur_file_size ) )
# TODO ( user ) : pytype : BLOCKSIZE / NUL constants are not visible to type
# checker .
# pytype : disable = module - attr
blocks , rema... |
def send_meta_data ( socket , conf , name ) :
'''Sends the config via ZeroMQ to a specified socket . Is called at the beginning of a run and when the config changes . Conf can be any config dictionary .''' | meta_data = dict ( name = name , conf = conf )
try :
socket . send_json ( meta_data , flags = zmq . NOBLOCK )
except zmq . Again :
pass |
def remover ( self , id_divisiondc ) :
"""Remove Division Dc from by the identifier .
: param id _ divisiondc : Identifier of the Division Dc . Integer value and greater than zero .
: return : None
: raise InvalidParameterError : The identifier of Division Dc is null and invalid .
: raise DivisaoDcNaoExiste... | if not is_valid_int_param ( id_divisiondc ) :
raise InvalidParameterError ( u'The identifier of Division Dc is invalid or was not informed.' )
url = 'divisiondc/' + str ( id_divisiondc ) + '/'
code , xml = self . submit ( None , 'DELETE' , url )
return self . response ( code , xml ) |
def create ( self , ** kwargs ) :
"""Creates a new statement matching the keyword arguments specified .
Returns the created statement .""" | Statement = self . get_model ( 'statement' )
Tag = self . get_model ( 'tag' )
tags = kwargs . pop ( 'tags' , [ ] )
if 'search_text' not in kwargs :
kwargs [ 'search_text' ] = self . tagger . get_bigram_pair_string ( kwargs [ 'text' ] )
if 'search_in_response_to' not in kwargs :
if kwargs . get ( 'in_response_to... |
def read ( self , size ) :
"""read size bytes and return them""" | done = 0
# number of bytes that have been read so far
v = ''
while True :
if size - done < len ( self . _buffer [ 'data' ] ) - self . _buffer_pos :
v += self . _buffer [ 'data' ] [ self . _buffer_pos : self . _buffer_pos + ( size - done ) ]
self . _buffer_pos += ( size - done )
# self . poin... |
def get_upper_triangle ( correlation_matrix ) :
'''Extract upper triangle from a square matrix . Negative values are
set to 0.
Args :
correlation _ matrix ( pandas df ) : Correlations between all replicates
Returns :
upper _ tri _ df ( pandas df ) : Upper triangle extracted from
correlation _ matrix ; r... | upper_triangle = correlation_matrix . where ( np . triu ( np . ones ( correlation_matrix . shape ) , k = 1 ) . astype ( np . bool ) )
# convert matrix into long form description
upper_tri_df = upper_triangle . stack ( ) . reset_index ( level = 1 )
upper_tri_df . columns = [ 'rid' , 'corr' ]
# Index at this point is cid... |
def schedule_from_proto_dicts ( device : 'xmon_device.XmonDevice' , ops : Iterable [ Dict ] , ) -> Schedule :
"""Convert proto dictionaries into a Schedule for the given device .""" | scheduled_ops = [ ]
last_time_picos = 0
for op in ops :
delay_picos = 0
if 'incremental_delay_picoseconds' in op :
delay_picos = op [ 'incremental_delay_picoseconds' ]
time_picos = last_time_picos + delay_picos
last_time_picos = time_picos
xmon_op = xmon_op_from_proto_dict ( op )
schedul... |
def menu_clean ( menu_config ) :
"""Make sure that only the menu item with the largest weight is active .
If a child of a menu item is active , the parent should be active too .
: param menu :
: return :""" | max_weight = - 1
for _ , value in list ( menu_config . items ( ) ) :
if value [ "submenu" ] :
for _ , v in list ( value [ "submenu" ] . items ( ) ) :
if v [ "active" ] : # parent inherits the weight of the axctive child
value [ "active" ] = True
value [ "active_we... |
def get_times_from_utterance ( utterance : str , char_offset_to_token_index : Dict [ int , int ] , indices_of_approximate_words : Set [ int ] ) -> Dict [ str , List [ int ] ] :
"""Given an utterance , we get the numbers that correspond to times and convert them to
values that may appear in the query . For example... | pm_linking_dict = _time_regex_match ( r'\d+pm' , utterance , char_offset_to_token_index , pm_map_match_to_query_value , indices_of_approximate_words )
am_linking_dict = _time_regex_match ( r'\d+am' , utterance , char_offset_to_token_index , am_map_match_to_query_value , indices_of_approximate_words )
oclock_linking_dic... |
def simplify_expression ( txt ) :
"""Remove all unecessary whitespace and some very usual space""" | minimal = re . sub ( r'\s' , ' ' , re . sub ( r'\s(?=\W)' , '' , re . sub ( r'(?<=\W)\s' , '' , txt . strip ( ) ) ) )
# add space before some " ( " and after some " ) "
return re . sub ( r'\)(?=\w)' , ') ' , re . sub ( r'(,|\b(?:{}))\(' . format ( '|' . join ( RESERVED_WORDS ) ) , '\\1 (' , minimal ) ) |
def _style_to_basic_html_attributes ( self , element , style_content , force = False ) :
"""given an element and styles like
' background - color : red ; font - family : Arial ' turn some of that into HTML
attributes . like ' bgcolor ' , etc .
Note , the style _ content can contain pseudoclasses like :
' { ... | if style_content . count ( "}" ) and style_content . count ( "{" ) == style_content . count ( "}" ) :
style_content = style_content . split ( "}" ) [ 0 ] [ 1 : ]
attributes = OrderedDict ( )
for key , value in [ x . split ( ":" ) for x in style_content . split ( ";" ) if len ( x . split ( ":" ) ) == 2 ] :
key =... |
def update_data ( ) :
"""Update data sent by background process to global allData""" | global allData
while not q . empty ( ) :
allData = q . get ( )
for key , value in tags . items ( ) :
if key in allData :
allData [ key ] [ 'name' ] = value |
def sort_recursive ( data ) :
"""Recursively sorts all elements in a dictionary
Args :
data ( dict ) : The dictionary to sort
Returns :
sorted _ dict ( OrderedDict ) : The sorted data dict""" | newdict = { }
for i in data . items ( ) :
if type ( i [ 1 ] ) is dict :
newdict [ i [ 0 ] ] = sort_recursive ( i [ 1 ] )
else :
newdict [ i [ 0 ] ] = i [ 1 ]
return OrderedDict ( sorted ( newdict . items ( ) , key = lambda item : ( compare_type ( type ( item [ 1 ] ) ) , item [ 0 ] ) ) ) |
def download ( cls , filename , input_dir , dl_dir = None ) :
"""Download the resource from the storage .""" | file_info = cls . parse_remote ( filename )
if not dl_dir :
dl_dir = os . path . join ( input_dir , file_info . container , os . path . dirname ( file_info . blob ) )
utils . safe_makedir ( dl_dir )
out_file = os . path . join ( dl_dir , os . path . basename ( file_info . blob ) )
if not utils . file_exists ( o... |
def set_stop_handler ( self ) :
"""Initializes functions that are invoked when the user or OS wants to kill this process .
: return :""" | signal . signal ( signal . SIGTERM , self . graceful_stop )
signal . signal ( signal . SIGABRT , self . graceful_stop )
signal . signal ( signal . SIGINT , self . graceful_stop ) |
async def field ( self , elem = None , elem_type = None , params = None ) :
"""Archive field
: param elem :
: param elem _ type :
: param params :
: return :""" | elem_type = elem_type if elem_type else elem . __class__
fvalue = None
src = elem
if issubclass ( elem_type , x . UVarintType ) :
fvalue = await self . uvarint ( x . get_elem ( src ) )
elif issubclass ( elem_type , x . IntType ) :
fvalue = await self . uint ( elem = x . get_elem ( src ) , elem_type = elem_type ... |
def cygpath ( filename ) :
"""Convert a cygwin path into a windows style path""" | if sys . platform == 'cygwin' :
proc = Popen ( [ 'cygpath' , '-am' , filename ] , stdout = PIPE )
return proc . communicate ( ) [ 0 ] . strip ( )
else :
return filename |
def _update_state_from_response ( self , response_json ) :
""": param response _ json : the json obj returned from query
: return :""" | _response_json = response_json . get ( 'data' )
if _response_json is not None :
self . json_state = _response_json
return True
return False |
def edges_to_path ( edges ) :
"""Connect edges and return a path .""" | if not edges :
return None
G = edges_to_graph ( edges )
path = nx . topological_sort ( G )
return path |
def ex ( mt , x ) :
"""ex : Returns the curtate expectation of life . Life expectancy""" | sum1 = 0
for j in mt . lx [ x + 1 : - 1 ] :
sum1 += j
# print sum1
try :
return sum1 / mt . lx [ x ] + 0.5
except :
return 0 |
def trace_symlink_target ( link ) :
"""Given a file that is known to be a symlink , trace it to its ultimate
target .
Raises TargetNotPresent when the target cannot be determined .
Raises ValueError when the specified link is not a symlink .""" | if not is_symlink ( link ) :
raise ValueError ( "link must point to a symlink on the system" )
while is_symlink ( link ) :
orig = os . path . dirname ( link )
link = readlink ( link )
link = resolve_path ( link , orig )
return link |
def afx_adafactor ( ) :
"""Adafactor with recommended learning rate schedule .""" | hparams = afx_adam ( )
hparams . optimizer = "Adafactor"
hparams . learning_rate_schedule = "rsqrt_decay"
hparams . learning_rate_warmup_steps = 10000
return hparams |
def record_entering ( self , time , code , frame_key , parent_stats ) :
"""Entered to a function call .""" | stats = parent_stats . ensure_child ( code , RecordingStatistics )
self . _times_entered [ ( code , frame_key ) ] = time
stats . own_hits += 1 |
def certs ( self ) :
"""List of the certificates contained in the structure""" | certstack = libcrypto . CMS_get1_certs ( self . ptr )
if certstack is None :
raise CMSError ( "getting certs" )
return StackOfX509 ( ptr = certstack , disposable = True ) |
def ExtractEvents ( self , parser_mediator , registry_key , ** kwargs ) :
"""Extracts events from a Windows Registry key .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
registry _ key ( dfwinreg . WinRegistryKey ) : Win... | self . _ParseLogonApplications ( parser_mediator , registry_key )
self . _ParseRegisteredDLLs ( parser_mediator , registry_key ) |
def _find_field_generator_templates ( self ) :
"""Return a dictionary of the form { name : field _ generator } containing
all tohu generators defined in the class and instance namespace
of this custom generator .""" | field_gen_templates = { }
# Extract field generators from class dict
for name , g in self . __class__ . __dict__ . items ( ) :
if isinstance ( g , TohuBaseGenerator ) :
field_gen_templates [ name ] = g . set_tohu_name ( f'{name} (TPL)' )
# Extract field generators from instance dict
for name , g in self . _... |
def workflow_script_import ( self ) :
"""Create objects from valid ARImport""" | bsc = getToolByName ( self , 'bika_setup_catalog' )
client = self . aq_parent
title = _ ( 'Submitting Sample Import' )
description = _ ( 'Creating and initialising objects' )
bar = ProgressBar ( self , self . REQUEST , title , description )
notify ( InitialiseProgressBar ( bar ) )
profiles = [ x . getObject ( ) for x i... |
def get_date_range ( year = None , month = None , day = None ) :
"""Return a start . . end range to query for a specific month , day or year .""" | if year is None :
return None
if month is None : # year only
start = datetime ( year , 1 , 1 , 0 , 0 , 0 , tzinfo = utc )
end = datetime ( year , 12 , 31 , 23 , 59 , 59 , 999 , tzinfo = utc )
return ( start , end )
if day is None : # year + month only
start = datetime ( year , month , 1 , 0 , 0 , 0 ... |
def _parse_ethtool_opts ( opts , iface ) :
'''Filters given options and outputs valid settings for ETHTOOLS _ OPTS
If an option has a value that is not expected , this
function will log what the Interface , Setting and what it was
expecting .''' | config = { }
if 'autoneg' in opts :
if opts [ 'autoneg' ] in _CONFIG_TRUE :
config . update ( { 'autoneg' : 'on' } )
elif opts [ 'autoneg' ] in _CONFIG_FALSE :
config . update ( { 'autoneg' : 'off' } )
else :
_raise_error_iface ( iface , 'autoneg' , _CONFIG_TRUE + _CONFIG_FALSE )
if ... |
def _set_fcoe_get_interface ( self , v , load = False ) :
"""Setter method for fcoe _ get _ interface , mapped from YANG variable / brocade _ fcoe _ ext _ rpc / fcoe _ get _ interface ( rpc )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ fcoe _ get _ interface is cons... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = fcoe_get_interface . fcoe_get_interface , is_leaf = True , yang_name = "fcoe-get-interface" , rest_name = "fcoe-get-interface" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_p... |
def get_threshold ( self ) :
"""Return threshold based on current state .""" | value_map = dict ( )
for key , value in list ( self . threshold_classes . items ( ) ) :
value_map [ key ] = [ value [ 0 ] . value ( ) , value [ 1 ] . value ( ) , ]
return value_map |
def loadInputs ( self , filename , cols = None , everyNrows = 1 , delim = ' ' , checkEven = 1 ) :
"""Loads inputs from file . Patterning is lost .""" | self . loadInputsFromFile ( filename , cols , everyNrows , delim , checkEven ) |
def get ( self ) :
"""Get the highest priority Processing Block from the queue .""" | with self . _mutex :
entry = self . _queue . pop ( )
del self . _block_map [ entry [ 2 ] ]
return entry [ 2 ] |
def _set_affected_target_count_in_runtracker ( self ) :
"""Sets the realized target count in the run tracker ' s daemon stats object .""" | target_count = len ( self . build_graph )
self . run_tracker . pantsd_stats . set_affected_targets_size ( target_count )
return target_count |
def fetchone ( self , query , * args ) :
"""Returns the first result of the given query .
: param query : The query to be executed as a ` str ` .
: param params : A ` tuple ` of parameters that will be replaced for
placeholders in the query .
: return : The retrieved row with each field being one element in... | cursor = self . connection . cursor ( )
try :
cursor . execute ( query , args )
return cursor . fetchone ( )
finally :
cursor . close ( ) |
def Match ( self , registry_key ) :
"""Determines if a Windows Registry key matches the filter .
Args :
registry _ key ( dfwinreg . WinRegistryKey ) : Windows Registry key .
Returns :
bool : True if the keys match .""" | value_names = frozenset ( [ registry_value . name for registry_value in registry_key . GetValues ( ) ] )
return self . _value_names . issubset ( value_names ) |
def get_string ( self , betas : List [ float ] , gammas : List [ float ] , samples : int = 100 ) :
"""Compute the most probable string .
The method assumes you have passed init _ betas and init _ gammas with your
pre - computed angles or you have run the VQE loop to determine the
angles . If you have not done... | if samples <= 0 and not isinstance ( samples , int ) :
raise ValueError ( "samples variable must be positive integer" )
param_prog = self . get_parameterized_program ( )
stacked_params = np . hstack ( ( betas , gammas ) )
sampling_prog = Program ( )
ro = sampling_prog . declare ( 'ro' , 'BIT' , len ( self . qubits ... |
def isValid ( self ) :
"""Returns if the current Reference Sample is valid . This is , the sample
hasn ' t neither been expired nor disposed .""" | today = DateTime ( )
expiry_date = self . getExpiryDate ( )
if expiry_date and today > expiry_date :
return False
# TODO : Do We really need ExpiryDate + DateExpired ? Any difference ?
date_expired = self . getDateExpired ( )
if date_expired and today > date_expired :
return False
date_disposed = self . getDate... |
def knn_impute_reference ( X , missing_mask , k , verbose = False , print_interval = 100 ) :
"""Reference implementation of kNN imputation logic .""" | n_rows , n_cols = X . shape
X_result , D , effective_infinity = knn_initialize ( X , missing_mask , verbose = verbose )
for i in range ( n_rows ) :
for j in np . where ( missing_mask [ i , : ] ) [ 0 ] :
distances = D [ i , : ] . copy ( )
# any rows that don ' t have the value we ' re currently tryin... |
def get_default_jvm_opts ( tmp_dir = None , parallel_gc = False ) :
"""Retrieve default JVM tuning options
Avoids issues with multiple spun up Java processes running into out of memory errors .
Parallel GC can use a lot of cores on big machines and primarily helps reduce task latency
and responsiveness which ... | opts = [ "-XX:+UseSerialGC" ] if not parallel_gc else [ ]
if tmp_dir :
opts . append ( "-Djava.io.tmpdir=%s" % tmp_dir )
return opts |
def _tabulate ( rows , headers , spacing = 5 ) :
"""Prepare simple table with spacing based on content""" | if len ( rows ) == 0 :
return "None\n"
assert len ( rows [ 0 ] ) == len ( headers )
count = len ( rows [ 0 ] )
widths = [ 0 for _ in range ( count ) ]
rows = [ headers ] + rows
for row in rows :
for index , field in enumerate ( row ) :
if len ( str ( field ) ) > widths [ index ] :
widths [ i... |
def generate_wakeword_pieces ( self , volume ) :
"""Generates chunks of audio that represent the wakeword stream""" | while True :
target = 1 if random ( ) > 0.5 else 0
it = self . pos_files_it if target else self . neg_files_it
sample_file = next ( it )
yield self . layer_with ( self . normalize_volume_to ( load_audio ( sample_file ) , volume ) , target )
yield self . layer_with ( np . zeros ( int ( pr . sample_ra... |
def _init_or_update_registered_service_if_needed ( self ) :
'''similar to _ init _ or _ update _ service _ if _ needed but we get service _ registraion from registry ,
so we can update only registered services''' | if ( self . is_service_initialized ( ) ) :
old_reg = self . _read_service_info ( self . args . org_id , self . args . service_id )
# metadataURI will be in old _ reg only for service which was initilized from registry ( not from metadata )
# we do nothing for services which were initilized from metadata
... |
def add_quota ( self , quota ) :
"""Adds an internal tracking reference for the given quota .""" | if quota . limit in ( None , - 1 , float ( 'inf' ) ) : # Handle " unlimited " quotas .
self . usages [ quota . name ] [ 'quota' ] = float ( "inf" )
self . usages [ quota . name ] [ 'available' ] = float ( "inf" )
else :
self . usages [ quota . name ] [ 'quota' ] = int ( quota . limit ) |
def gen_pager_purecss ( cat_slug , page_num , current ) :
'''Generate pager of purecss .''' | if page_num == 1 :
return ''
pager_shouye = '''<li class="pure-menu-item {0}">
<a class="pure-menu-link" href="{1}"><< 首页</a></li>''' . format ( 'hidden' if current <= 1 else '' , cat_slug )
pager_pre = '''<li class="pure-menu-item {0}">
<a class="pure-menu-link" href="{1}/{2}">< 前页</a>... |
def _rpartition ( entity , sep ) :
"""Python2.4 doesn ' t have an rpartition method so we provide
our own that mimics str . rpartition from later releases .
Split the string at the last occurrence of sep , and return a
3 - tuple containing the part before the separator , the separator
itself , and the part ... | idx = entity . rfind ( sep )
if idx == - 1 :
return '' , '' , entity
return entity [ : idx ] , sep , entity [ idx + 1 : ] |
def batch_step ( self , batch_idx = None ) :
"""Updates the learning rate for the batch index : ` ` batch _ idx ` ` .
If ` ` batch _ idx ` ` is None , ` ` CyclicLR ` ` will use an internal
batch index to keep track of the index .""" | if batch_idx is None :
batch_idx = self . last_batch_idx + 1
self . last_batch_idx = batch_idx
for param_group , lr in zip ( self . optimizer . param_groups , self . get_lr ( ) ) :
param_group [ 'lr' ] = lr |
def set_metadata_value ( metadata_source , key : str , value : typing . Any ) -> None :
"""Set the metadata value for the given key .
There are a set of predefined keys that , when used , will be type checked and be interoperable with other
applications . Please consult reference documentation for valid keys . ... | desc = session_key_map . get ( key )
if desc is not None :
d0 = getattr ( metadata_source , "session_metadata" , dict ( ) )
d = d0
for k in desc [ 'path' ] [ : - 1 ] :
d = d . setdefault ( k , dict ( ) ) if d is not None else None
if d is not None :
d [ desc [ 'path' ] [ - 1 ] ] = value
... |
def main ( handwriting_datasets_file , analyze_features ) :
"""Start the creation of the wanted metric .""" | # Load from pickled file
logging . info ( "Start loading data '%s' ..." , handwriting_datasets_file )
loaded = pickle . load ( open ( handwriting_datasets_file ) )
raw_datasets = loaded [ 'handwriting_datasets' ]
logging . info ( "%i datasets loaded." , len ( raw_datasets ) )
logging . info ( "Start analyzing..." )
if ... |
def function_parser ( function , parser ) :
"""This function parses a function and adds its arguments to the supplied parser""" | # Store the function pointer on the parser for later use
parser . set_defaults ( func = function )
# Get the help text and parse it for params
help_text = inspect . getdoc ( function )
main_text , params_help = parser_help_text ( help_text )
# Get the function information
args , varargs , keywords , defaults = inspect ... |
async def reset_type_codec ( self , typename , * , schema = 'public' ) :
"""Reset * typename * codec to the default implementation .
: param typename :
Name of the data type the codec is for .
: param schema :
Schema name of the data type the codec is for
( defaults to ` ` ' public ' ` ` )
. . versionad... | typeinfo = await self . fetchrow ( introspection . TYPE_BY_NAME , typename , schema )
if not typeinfo :
raise ValueError ( 'unknown type: {}.{}' . format ( schema , typename ) )
oid = typeinfo [ 'oid' ]
self . _protocol . get_settings ( ) . remove_python_codec ( oid , typename , schema )
# Statement cache is no lon... |
def help_function ( self , command = None ) :
"""Show help for all available commands or just a single one""" | if command :
return self . registered [ command ] . get ( 'description' , 'No help available' )
return ', ' . join ( sorted ( self . registered ) ) |
def getOverlayDualAnalogTransform ( self , ulOverlay , eWhich ) :
"""Gets the analog input to Dual Analog coordinate scale for the specified overlay .""" | fn = self . function_table . getOverlayDualAnalogTransform
pvCenter = HmdVector2_t ( )
pfRadius = c_float ( )
result = fn ( ulOverlay , eWhich , byref ( pvCenter ) , byref ( pfRadius ) )
return result , pvCenter , pfRadius . value |
def _index_audio_ibm ( self , basename = None , replace_already_indexed = False , continuous = True , model = "en-US_BroadbandModel" , word_confidence = True , word_alternatives_threshold = 0.9 , profanity_filter_for_US_results = False ) :
"""Implements a search - suitable interface for Watson speech API .
Some e... | params = { 'continuous' : continuous , 'model' : model , 'word_alternatives_threshold' : word_alternatives_threshold , 'word_confidence' : word_confidence , 'timestamps' : True , 'inactivity_timeout' : str ( - 1 ) , 'profanity_filter' : profanity_filter_for_US_results }
self . _prepare_audio ( basename = basename , rep... |
def del_calculation ( job_id , confirmed = False ) :
"""Delete a calculation and all associated outputs .""" | if logs . dbcmd ( 'get_job' , job_id ) is None :
print ( 'There is no job %d' % job_id )
return
if confirmed or confirm ( 'Are you sure you want to (abort and) delete this calculation and ' 'all associated outputs?\nThis action cannot be undone. (y/n): ' ) :
try :
abort ( job_id )
resp = log... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.