signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _get_cols ( fields , schema ) :
"""Get column metadata for Google Charts based on field list and schema .""" | typemap = { 'STRING' : 'string' , 'INT64' : 'number' , 'INTEGER' : 'number' , 'FLOAT' : 'number' , 'FLOAT64' : 'number' , 'BOOL' : 'boolean' , 'BOOLEAN' : 'boolean' , 'DATE' : 'date' , 'TIME' : 'timeofday' , 'DATETIME' : 'datetime' , 'TIMESTAMP' : 'datetime' }
cols = [ ]
for col in fields :
if schema :
f = ... |
def _load_local_tzinfo ( ) :
"""Load zoneinfo from local disk .""" | tzdir = os . environ . get ( "TZDIR" , "/usr/share/zoneinfo/posix" )
localtzdata = { }
for dirpath , _ , filenames in os . walk ( tzdir ) :
for filename in filenames :
filepath = os . path . join ( dirpath , filename )
name = os . path . relpath ( filepath , tzdir )
f = open ( filepath , "rb... |
def map_statements ( self ) :
"""Run the ontology mapping on the statements .""" | for stmt in self . statements :
for agent in stmt . agent_list ( ) :
if agent is None :
continue
all_mappings = [ ]
for db_name , db_id in agent . db_refs . items ( ) :
if isinstance ( db_id , list ) :
db_id = db_id [ 0 ] [ 0 ]
mappings = s... |
def _get_perf ( text , msg_id ) :
"""Return a request message for a given text .""" | msg = KQMLPerformative ( 'REQUEST' )
msg . set ( 'receiver' , 'READER' )
content = KQMLList ( 'run-text' )
content . sets ( 'text' , text )
msg . set ( 'content' , content )
msg . set ( 'reply-with' , msg_id )
return msg |
def get_first_properties ( elt , keys = None , ctx = None ) :
"""Get first properties related to one input key .
: param elt : first property elt . Not None methods .
: param list keys : property keys to get .
: param ctx : elt ctx from where get properties . Equals elt if None . It
allows to get function p... | # ensure keys is an iterable if not None
if isinstance ( keys , string_types ) :
keys = ( keys , )
result = _get_properties ( elt , keys = keys , first = True , ctx = ctx )
return result |
def get_logger ( cls ) :
"""Initializes and returns our logger instance .""" | if cls . logger is None :
cls . logger = logging . getLogger ( "django_auth_ldap" )
cls . logger . addHandler ( logging . NullHandler ( ) )
return cls . logger |
def create_shipment ( self , data = None ) :
"""Create a shipment for an order . When no data arg is given , a shipment for all order lines is assumed .""" | if data is None :
data = { 'lines' : [ ] }
return Shipments ( self . client ) . on ( self ) . create ( data ) |
def set_guest_access ( self , allow_guests ) :
"""Set whether guests can join the room and return True if successful .""" | guest_access = "can_join" if allow_guests else "forbidden"
try :
self . client . api . set_guest_access ( self . room_id , guest_access )
self . guest_access = allow_guests
return True
except MatrixRequestError :
return False |
def order_manually ( sub_commands ) :
"""Order sub - commands for display""" | order = [ "start" , "projects" , ]
ordered = [ ]
commands = dict ( zip ( [ cmd for cmd in sub_commands ] , sub_commands ) )
for k in order :
ordered . append ( commands . get ( k , "" ) )
if k in commands :
del commands [ k ]
# Add commands not present in ` order ` above
for k in commands :
ordered ... |
def _parse_sheet ( workbook , sheet ) :
"""The universal spreadsheet parser . Parse chron or paleo tables of type ensemble / model / summary .
: param str name : Filename
: param obj workbook : Excel Workbook
: param dict sheet : Sheet path and naming info
: return dict dict : Table metadata and numeric dat... | logger_excel . info ( "enter parse_sheet: {}" . format ( sheet [ "old_name" ] ) )
# Markers to track where we are on the sheet
ensemble_on = False
var_header_done = False
metadata_on = False
metadata_done = False
data_on = False
notes = False
# Open the sheet from the workbook
temp_sheet = workbook . sheet_by_name ( sh... |
def get_deffacts ( self ) :
"""Return the existing deffacts sorted by the internal order""" | return sorted ( self . _get_by_type ( DefFacts ) , key = lambda d : d . order ) |
def import_path ( self ) :
"""The full remote import path as used in import statements in ` . go ` source files .""" | return os . path . join ( self . remote_root , self . pkg ) if self . pkg else self . remote_root |
def chunkify ( chunksize ) :
"""Very stupid " chunk vectorizer " which keeps memory use down .
This version requires all inputs to have the same number of elements ,
although it shouldn ' t be that hard to implement simple broadcasting .""" | def chunkifier ( func ) :
def wrap ( * args ) :
assert len ( args ) > 0
assert all ( len ( a . flat ) == len ( args [ 0 ] . flat ) for a in args )
nelements = len ( args [ 0 ] . flat )
nchunks , remain = divmod ( nelements , chunksize )
out = np . ndarray ( args [ 0 ] . shape... |
def from_string ( cls , line , ignore_bad_cookies = False , ignore_bad_attributes = True ) :
"Construct a Cookie object from a line of Set - Cookie header data ." | cookie_dict = parse_one_response ( line , ignore_bad_cookies = ignore_bad_cookies , ignore_bad_attributes = ignore_bad_attributes )
if not cookie_dict :
return None
return cls . from_dict ( cookie_dict , ignore_bad_attributes = ignore_bad_attributes ) |
def from_dict ( data , ctx ) :
"""Instantiate a new Trade from a dict ( generally from loading a JSON
response ) . The data used to instantiate the Trade is a shallow copy of
the dict passed in , with any complex child types instantiated
appropriately .""" | data = data . copy ( )
if data . get ( 'price' ) is not None :
data [ 'price' ] = ctx . convert_decimal_number ( data . get ( 'price' ) )
if data . get ( 'initialUnits' ) is not None :
data [ 'initialUnits' ] = ctx . convert_decimal_number ( data . get ( 'initialUnits' ) )
if data . get ( 'initialMarginRequired... |
def enable_chimera ( verbose = False , nogui = True ) :
"""Bypass script loading and initialize Chimera correctly , once
the env has been properly patched .
Parameters
verbose : bool , optional , default = False
If True , let Chimera speak freely . It can be _ very _ verbose .
nogui : bool , optional , de... | if os . getenv ( 'CHIMERA_ENABLED' ) :
return
import chimera
_pre_gui_patches ( )
if not nogui :
chimera . registerPostGraphicsFunc ( _post_gui_patches )
try :
import chimeraInit
if verbose :
chimera . replyobj . status ( 'initializing pychimera' )
except ImportError as e :
sys . exit ( str ... |
def validate ( self , instance , value ) :
"""Check if value is a valid datetime object or JSON datetime string""" | if isinstance ( value , datetime . datetime ) :
return value
if not isinstance ( value , string_types ) :
self . error ( instance = instance , value = value , extra = 'Cannot convert non-strings to datetime.' , )
try :
return self . from_json ( value )
except ValueError :
self . error ( instance = insta... |
def unitcheck ( u , nonperiodic = None ) :
"""Check whether ` u ` is inside the unit cube . Given a masked array
` nonperiodic ` , also allows periodic boundaries conditions to exceed
the unit cube .""" | if nonperiodic is None : # No periodic boundary conditions provided .
return np . all ( u > 0. ) and np . all ( u < 1. )
else : # Alternating periodic and non - periodic boundary conditions .
return ( np . all ( u [ nonperiodic ] > 0. ) and np . all ( u [ nonperiodic ] < 1. ) and np . all ( u [ ~ nonperiodic ] ... |
def get_constrained_fc2 ( supercell , dataset_second_atoms , atom1 , reduced_site_sym , symprec ) :
"""dataset _ second _ atoms : [ { ' number ' : 7,
' displacement ' : [ ] ,
' delta _ forces ' : [ ] } , . . . ]""" | lattice = supercell . get_cell ( ) . T
positions = supercell . get_scaled_positions ( )
num_atom = supercell . get_number_of_atoms ( )
fc2 = np . zeros ( ( num_atom , num_atom , 3 , 3 ) , dtype = 'double' )
atom_list = np . unique ( [ x [ 'number' ] for x in dataset_second_atoms ] )
for atom2 in atom_list :
disps2 ... |
def check_authorization ( self , access_token ) :
"""OAuth applications can use this method to check token validity
without hitting normal rate limits because of failed login attempts .
If the token is valid , it will return True , otherwise it will return
False .
: returns : bool""" | p = self . _session . params
auth = ( p . get ( 'client_id' ) , p . get ( 'client_secret' ) )
if access_token and auth :
url = self . _build_url ( 'applications' , str ( auth [ 0 ] ) , 'tokens' , str ( access_token ) )
resp = self . _get ( url , auth = auth , params = { 'client_id' : None , 'client_secret' : No... |
def computePhase2 ( self , doLearn = False ) :
"""This is the phase 2 of learning , inference and multistep prediction . During
this phase , all the cell with lateral support have their predictedState
turned on and the firing segments are queued up for updates .
Parameters :
doLearn : Boolean flag to queue ... | # Phase 2 : compute predicted state for each cell
# - if a segment has enough horizontal connections firing because of
# bottomUpInput , it ' s set to be predicting , and we queue up the segment
# for reinforcement ,
# - if pooling is on , try to find the best weakly activated segment to
# reinforce it , else create a ... |
def connect ( self , address ) :
"""Equivalent to socket . connect ( ) , but sends an client handshake request
after connecting .
` address ` is a ( host , port ) tuple of the server to connect to .""" | self . sock . connect ( address )
ClientHandshake ( self ) . perform ( )
self . handshake_sent = True |
def deprecate ( message ) :
"""Loudly prints warning .""" | warnings . simplefilter ( 'default' )
warnings . warn ( message , category = DeprecationWarning )
warnings . resetwarnings ( ) |
def call_id_function ( opts ) :
'''Evaluate the function that determines the ID if the ' id _ function '
option is set and return the result''' | if opts . get ( 'id' ) :
return opts [ 'id' ]
# Import ' salt . loader ' here to avoid a circular dependency
import salt . loader as loader
if isinstance ( opts [ 'id_function' ] , six . string_types ) :
mod_fun = opts [ 'id_function' ]
fun_kwargs = { }
elif isinstance ( opts [ 'id_function' ] , dict ) :
... |
def h_boiling_Yan_Lin ( m , x , Dh , rhol , rhog , mul , kl , Hvap , Cpl , q , A_channel_flow ) :
r'''Calculates the two - phase boiling heat transfer coefficient of a
liquid and gas flowing inside a plate and frame heat exchanger , as
developed in [ 1 ] _ . Reviewed in [ 2 ] _ , [ 3 ] _ , [ 4 ] _ , and [ 5 ] _... | G = m / A_channel_flow
G_eq = G * ( ( 1. - x ) + x * ( rhol / rhog ) ** 0.5 )
Re_eq = G_eq * Dh / mul
Re = G * Dh / mul
# Not actually specified clearly but it is in another paper by them
Bo_eq = q / ( G_eq * Hvap )
Pr_l = Prandtl ( Cp = Cpl , k = kl , mu = mul )
return 1.926 * ( kl / Dh ) * Re_eq * Pr_l ** ( 1 / 3. ) ... |
def parse_rule ( rule ) :
"""Parse a rule and return it as generator . Each iteration yields tuples
in the form ` ` ( converter , arguments , variable ) ` ` . If the converter is
` None ` it ' s a static url part , otherwise it ' s a dynamic one .
: internal :""" | pos = 0
end = len ( rule )
do_match = _rule_re . match
used_names = set ( )
while pos < end :
m = do_match ( rule , pos )
if m is None :
break
data = m . groupdict ( )
if data [ "static" ] :
yield None , None , data [ "static" ]
variable = data [ "variable" ]
converter = data [ "... |
def put_stream ( self , bucket , label , stream_object , params = None , replace = True , add_md = True ) :
'''Put a bitstream ( stream _ object ) for the specified bucket : label identifier .
: param bucket : as standard
: param label : as standard
: param stream _ object : file - like object to read from or... | if self . mode == "r" :
raise OFSException ( "Cannot write into archive in 'r' mode" )
else :
params = params or { }
fn = self . _zf ( bucket , label )
params [ '_creation_date' ] = datetime . now ( ) . isoformat ( ) . split ( "." ) [ 0 ]
# # ' 2010-07-08T19:56:47'
params [ '_label' ] = label
... |
def forwards ( self , orm ) :
"Write your forwards methods here ." | for tag in orm [ 'tagging.Tag' ] . objects . all ( ) :
if tag . tagtitle_set . all ( ) . count ( ) == 0 :
orm [ 'tagging_translated.TagTitle' ] . objects . create ( trans_name = tag . name , tag = tag , language = 'en' ) |
def finish ( self , data = '' ) :
'''Optionally add pending data , turn off streaming mode , and yield
result chunks , which implies all pending data will be consumed .
: yields : result chunks
: ytype : str''' | self . pending += data
self . streaming = False
for i in self :
yield i |
def identifier_director ( ** kwargs ) :
"""Direct how to handle the identifier element .""" | ark = kwargs . get ( 'ark' , None )
domain_name = kwargs . get ( 'domain_name' , None )
# Set default scheme if it is None or is not supplied .
scheme = kwargs . get ( 'scheme' ) or 'http'
qualifier = kwargs . get ( 'qualifier' , None )
content = kwargs . get ( 'content' , '' )
# See if the ark and domain name were giv... |
def default_indexes ( coords : Mapping [ Any , Variable ] , dims : Iterable , ) -> 'OrderedDict[Any, pd.Index]' :
"""Default indexes for a Dataset / DataArray .
Parameters
coords : Mapping [ Any , xarray . Variable ]
Coordinate variables from which to draw default indexes .
dims : iterable
Iterable of dim... | return OrderedDict ( ( key , coords [ key ] . to_index ( ) ) for key in dims if key in coords ) |
def update_app ( self , app_id , app , force = False , minimal = True ) :
"""Update an app .
Applies writable settings in ` app ` to ` app _ id `
Note : this method can not be used to rename apps .
: param str app _ id : target application ID
: param app : application settings
: type app : : class : ` mar... | # Changes won ' t take if version is set - blank it for convenience
app . version = None
params = { 'force' : force }
data = app . to_json ( minimal = minimal )
response = self . _do_request ( 'PUT' , '/v2/apps/{app_id}' . format ( app_id = app_id ) , params = params , data = data )
return response . json ( ) |
def variables ( self ) :
"""Display a list of templatable variables present in the file .
Templating is accomplished by creating a bracketed object in the same
way that Python performs ` string formatting ` _ . The editor is able to
replace the placeholder value of the template . Integer templates are
posit... | string = str ( self )
constants = [ match [ 1 : - 1 ] for match in re . findall ( '{{[A-z0-9]}}' , string ) ]
variables = re . findall ( '{[A-z0-9]*}' , string )
return sorted ( set ( variables ) . difference ( constants ) ) |
def populate ( cls , as_of = None ) :
"""Ensure the next X years of billing cycles exist""" | return cls . _populate ( as_of = as_of or date . today ( ) , delete = True ) |
def as_number ( self ) :
"""> > > round ( SummableVersion ( ' 1.9.3 ' ) . as _ number ( ) , 12)
1.93""" | def combine ( subver , ver ) :
return subver / 10 + ver
return reduce ( combine , reversed ( self . version ) ) |
def fetch ( self , R , pk , depth = 1 ) :
"Request object from API" | d , e = self . _fetcher . fetch ( R , pk , depth )
if e :
raise e
return d |
def parse ( self , ** kwargs ) :
"""Parse the contents of the output files retrieved in the ` FolderData ` .""" | try :
output_folder = self . retrieved
except exceptions . NotExistent :
return self . exit_codes . ERROR_NO_RETRIEVED_FOLDER
filename_stdout = self . node . get_attribute ( 'output_filename' )
filename_stderr = self . node . get_attribute ( 'error_filename' )
try :
with output_folder . open ( filename_stde... |
def get_resource_url ( self ) :
"""Get resource complete url""" | name = self . __class__ . resource_name
url = self . __class__ . rest_base_url ( )
return "%s/%s" % ( url , name ) |
def safe_purge_collection ( coll ) :
"""Cannot remove documents from capped collections
in later versions of MongoDB , so drop the
collection instead .""" | op = ( drop_collection if coll . options ( ) . get ( 'capped' , False ) else purge_collection )
return op ( coll ) |
def export_as_package ( self , package_path , cv_source ) :
"""Exports the ensemble as a Python package and saves it to ` package _ path ` .
Args :
package _ path ( str , unicode ) : Absolute / local path of place to save package in
cv _ source ( str , unicode ) : String containing actual code for base learne... | if os . path . exists ( package_path ) :
raise exceptions . UserError ( '{} already exists' . format ( package_path ) )
package_name = os . path . basename ( os . path . normpath ( package_path ) )
os . makedirs ( package_path )
# Write _ _ init _ _ . py
with open ( os . path . join ( package_path , '__init__.py' )... |
async def _move ( self , target_position : 'OrderedDict[Axis, float]' , speed : float = None , home_flagged_axes : bool = True ) :
"""Worker function to apply robot motion .
Robot motion means the kind of motions that are relevant to the robot ,
i . e . only one pipette plunger and mount move at the same time ,... | # Transform only the x , y , and ( z or a ) axes specified since this could
# get the b or c axes as well
to_transform = tuple ( ( tp for ax , tp in target_position . items ( ) if ax in Axis . gantry_axes ( ) ) )
# Pre - fill the dict we ’ ll send to the backend with the axes we don ’ t
# need to transform
smoothie_pos... |
def update_campaign_destroy ( self , campaign_id , ** kwargs ) : # noqa : E501
"""Delete a campaign # noqa : E501
Delete an update campaign . # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass asynchronous = True
> > > thread = api . up... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'asynchronous' ) :
return self . update_campaign_destroy_with_http_info ( campaign_id , ** kwargs )
# noqa : E501
else :
( data ) = self . update_campaign_destroy_with_http_info ( campaign_id , ** kwargs )
# noqa : E501
return data |
def broadcast_setting_change ( message = 'Environment' ) :
'''Send a WM _ SETTINGCHANGE Broadcast to all Windows
Args :
message ( str ) :
A string value representing the portion of the system that has been
updated and needs to be refreshed . Default is ` ` Environment ` ` . These
are some common values : ... | # Listen for messages sent by this would involve working with the
# SetWindowLong function . This can be accessed via win32gui or through
# ctypes . You can find examples on how to do this by searching for
# ` Accessing WGL _ WNDPROC ` on the internet . Here are some examples of how
# this might work :
# # using win32g... |
def Query ( cls , index_urn , target_prefix = "" , limit = 100 , token = None ) :
"""Search the index for matches starting with target _ prefix .
Args :
index _ urn : The index to use . Should be a urn that points to the sha256
namespace .
target _ prefix : The prefix to match against the index .
limit : ... | return data_store . DB . FileHashIndexQuery ( index_urn , target_prefix , limit = limit ) |
def parse ( self , rrstr ) : # type : ( bytes ) - > None
'''Parse a Rock Ridge Time Stamp record out of a string .
Parameters :
rrstr - The string to parse the record out of .
Returns :
Nothing .''' | if self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'TF record already initialized!' )
# We assume that the caller has already checked the su _ entry _ version ,
# so we don ' t bother .
( su_len , su_entry_version_unused , self . time_flags , ) = struct . unpack_from ( '=BBB' , rrstr [ : 5 ] ,... |
def deprecated_conditional ( predicate , removal_version , entity_description , hint_message = None , stacklevel = 4 ) :
"""Marks a certain configuration as deprecated .
The predicate is used to determine if that configuration is deprecated . It is a function that
will be called , if true , then the deprecation... | validate_deprecation_semver ( removal_version , 'removal version' )
if predicate ( ) :
warn_or_error ( removal_version , entity_description , hint_message , stacklevel = stacklevel ) |
def _format_response ( rows , fields , unique_col_names ) :
"""This function will look at the data column of rows and extract the specified fields . It
will also dedup changes where the specified fields have not changed . The list of rows should
be ordered by the compound primary key which versioning pivots aro... | output = [ ]
old_id = None
for row in rows :
id_ = { k : row [ k ] for k in unique_col_names }
formatted = { k : row [ k ] for k in row if k != 'data' }
if id_ != old_id : # new unique versioned row
data = row [ 'data' ]
formatted [ 'data' ] = { k : data . get ( k ) for k in fields }
... |
def _send_data ( self , data ) :
"""Send data to the ADB server""" | total_sent = 0
while total_sent < len ( data ) : # Send only the bytes that haven ' t been
# sent yet
sent = self . socket . send ( data [ total_sent : ] . encode ( "ascii" ) )
if sent == 0 :
self . close ( )
raise RuntimeError ( "Socket connection dropped, " "send failed" )
total_sent += se... |
def nb_to_q_nums ( nb ) -> list :
"""Gets question numbers from each cell in the notebook""" | def q_num ( cell ) :
assert cell . metadata . tags
return first ( filter ( lambda t : 'q' in t , cell . metadata . tags ) )
return [ q_num ( cell ) for cell in nb [ 'cells' ] ] |
def _data_received ( self , next_bytes ) :
"""Maintains buffer of bytes received from peer and extracts bgp
message from this buffer if enough data is received .
Validates bgp message marker , length , type and data and constructs
appropriate bgp message instance and calls handler .
: Parameters :
- ` nex... | # Append buffer with received bytes .
self . _recv_buff += next_bytes
while True : # If current buffer size is less then minimum bgp message size , we
# return as we do not have a complete bgp message to work with .
if len ( self . _recv_buff ) < BGP_MIN_MSG_LEN :
return
# Parse message header into elem... |
def _api_path ( self , item ) :
"""Get the API path for the current cursor position .""" | if self . base_url is None :
raise NotImplementedError ( "base_url not set" )
path = "/" . join ( [ x . blob [ "id" ] for x in item . path ] )
return "/" . join ( [ self . base_url , path ] ) |
def validate_kernel_string ( self , kernel ) :
"""determine if a kernel string is valid , meaning it is in the format
of { username } / { kernel - slug } .
Parameters
kernel : the kernel name to validate""" | if kernel :
if '/' not in kernel :
raise ValueError ( 'Kernel must be specified in the form of ' '\'{username}/{kernel-slug}\'' )
split = kernel . split ( '/' )
if not split [ 0 ] or not split [ 1 ] :
raise ValueError ( 'Kernel must be specified in the form of ' '\'{username}/{kernel-slug}\'... |
def OnKey ( self , event ) :
"""Handles non - standard shortcut events""" | def switch_to_next_table ( ) :
newtable = self . grid . current_table + 1
post_command_event ( self . grid , self . GridActionTableSwitchMsg , newtable = newtable )
def switch_to_previous_table ( ) :
newtable = self . grid . current_table - 1
post_command_event ( self . grid , self . GridActionTableSwit... |
def _prepare_record ( self , group ) :
"""compute record dtype and parents dict fro this group
Parameters
group : dict
MDF group dict
Returns
parents , dtypes : dict , numpy . dtype
mapping of channels to records fields , records fields dtype""" | parents , dtypes = group . parents , group . types
no_parent = None , None
if parents is None :
channel_group = group . channel_group
channels = group . channels
bus_event = channel_group . flags & v4c . FLAG_CG_BUS_EVENT
record_size = channel_group . samples_byte_nr
invalidation_bytes_nr = channel_... |
def prune_chunks ( self , tsn ) :
"""Prune chunks up to the given TSN .""" | pos = - 1
size = 0
for i , chunk in enumerate ( self . reassembly ) :
if uint32_gte ( tsn , chunk . tsn ) :
pos = i
size += len ( chunk . user_data )
else :
break
self . reassembly = self . reassembly [ pos + 1 : ]
return size |
def get_block_containing_tx ( self , txid ) :
"""Retrieve the list of blocks ( block ids ) containing a
transaction with transaction id ` txid `
Args :
txid ( str ) : transaction id of the transaction to query
Returns :
Block id list ( list ( int ) )""" | blocks = list ( backend . query . get_block_with_transaction ( self . connection , txid ) )
if len ( blocks ) > 1 :
logger . critical ( 'Transaction id %s exists in multiple blocks' , txid )
return [ block [ 'height' ] for block in blocks ] |
def is_fully_verified ( self ) :
"""Determine if this Job is fully verified based on the state of its Errors .
An Error ( TextLogError or FailureLine ) is considered Verified once its
related TextLogErrorMetadata has best _ is _ verified set to True . A Job
is then considered Verified once all its Errors Text... | unverified_errors = TextLogError . objects . filter ( _metadata__best_is_verified = False , step__job = self ) . count ( )
if unverified_errors :
logger . error ( "Job %r has unverified TextLogErrors" , self )
return False
logger . info ( "Job %r is fully verified" , self )
return True |
def get_observer_look ( sat_lon , sat_lat , sat_alt , utc_time , lon , lat , alt ) :
"""Calculate observers look angle to a satellite .
http : / / celestrak . com / columns / v02n02/
utc _ time : Observation time ( datetime object )
lon : Longitude of observer position on ground in degrees east
lat : Latitu... | ( pos_x , pos_y , pos_z ) , ( vel_x , vel_y , vel_z ) = astronomy . observer_position ( utc_time , sat_lon , sat_lat , sat_alt )
( opos_x , opos_y , opos_z ) , ( ovel_x , ovel_y , ovel_z ) = astronomy . observer_position ( utc_time , lon , lat , alt )
lon = np . deg2rad ( lon )
lat = np . deg2rad ( lat )
theta = ( astr... |
def unmonitor ( self , target ) :
"""Stop monitoring the online status of a user . Returns whether or not the server supports monitoring .""" | if 'monitor-notify' in self . _capabilities and self . is_monitoring ( target ) :
yield from self . rawmsg ( 'MONITOR' , '-' , target )
self . _monitoring . remove ( target )
return True
else :
return False |
def fitlin ( imgarr , refarr ) :
"""Compute the least - squares fit between two arrays .
A Python translation of ' FITLIN ' from ' drutil . f ' ( Drizzle V2.9 ) .""" | # Initialize variables
_mat = np . zeros ( ( 3 , 3 ) , dtype = np . float64 )
_xorg = imgarr [ 0 ] [ 0 ]
_yorg = imgarr [ 0 ] [ 1 ]
_xoorg = refarr [ 0 ] [ 0 ]
_yoorg = refarr [ 0 ] [ 1 ]
_sigxox = 0.
_sigxoy = 0.
_sigxo = 0.
_sigyox = 0.
_sigyoy = 0.
_sigyo = 0.
_npos = len ( imgarr )
# Populate matrices
for i in rang... |
def calc_normal_std_he_backward ( inmaps , outmaps , kernel = ( 1 , 1 ) ) :
r"""Calculates the standard deviation of He et al . ( backward case ) .
. . math : :
\ sigma = \ sqrt { \ frac { 2 } { MK } }
Args :
inmaps ( int ) : Map size of an input Variable , : math : ` N ` .
outmaps ( int ) : Map size of a... | return np . sqrt ( 2. / ( np . prod ( kernel ) * outmaps ) ) |
def load_styles ( path_or_doc ) :
"""Return a dictionary of all styles contained in an ODF document .""" | if isinstance ( path_or_doc , string_types ) :
doc = load ( path_or_doc )
else : # Recover the OpenDocumentText instance .
if isinstance ( path_or_doc , ODFDocument ) :
doc = path_or_doc . _doc
else :
doc = path_or_doc
assert isinstance ( doc , OpenDocument ) , doc
styles = { _style_name... |
def auto_invalidate ( self ) :
"""Invalidate the cache if the current time is past the time to live .""" | current = datetime . now ( )
if current > self . _invalidated + timedelta ( seconds = self . _timetolive ) :
self . invalidate ( ) |
def document ( self ) :
""": return : the : class : ` Document ` node that contains this node ,
or ` ` self ` ` if this node is the document .""" | if self . is_document :
return self
return self . adapter . wrap_document ( self . adapter . impl_document ) |
def get_assessment_taken_id ( self ) :
"""Gets the ` ` Id ` ` of the ` ` AssessmentTaken ` ` .
return : ( osid . id . Id ) - the assessment taken ` ` Id ` `
* compliance : mandatory - - This method must be implemented . *""" | # Implemented from template for osid . learning . Activity . get _ objective _ id
if not bool ( self . _my_map [ 'assessmentTakenId' ] ) :
raise errors . IllegalState ( 'assessment_taken empty' )
return Id ( self . _my_map [ 'assessmentTakenId' ] ) |
def make_sudo_cmd ( sudo_user , executable , cmd ) :
"""helper function for connection plugins to create sudo commands""" | # Rather than detect if sudo wants a password this time , - k makes
# sudo always ask for a password if one is required .
# Passing a quoted compound command to sudo ( or sudo - s )
# directly doesn ' t work , so we shellquote it with pipes . quote ( )
# and pass the quoted string to the user ' s shell . We loop readin... |
def check_usage ( docstring , argv = None , usageifnoargs = False ) :
"""Check if the program has been run with a - - help argument ; if so ,
print usage information and exit .
: arg str docstring : the program help text
: arg argv : the program arguments ; taken as : data : ` sys . argv ` if
given as : con... | if argv is None :
from sys import argv
if len ( argv ) == 1 and usageifnoargs :
show_usage ( docstring , ( usageifnoargs != 'long' ) , None , 0 )
if len ( argv ) == 2 and argv [ 1 ] in ( '-h' , '--help' ) :
show_usage ( docstring , False , None , 0 ) |
def yellow ( cls , string , auto = False ) :
"""Color - code entire string .
: param str string : String to colorize .
: param bool auto : Enable auto - color ( dark / light terminal ) .
: return : Class instance for colorized string .
: rtype : Color""" | return cls . colorize ( 'yellow' , string , auto = auto ) |
def check_for_rerun_user_task ( self ) :
"""Checks that the user task needs to re - run .
If necessary , current task and pre task ' s states are changed and re - run .
If wf _ meta not in data ( there is no user interaction from pre - task ) and last completed task
type is user task and current step is not E... | data = self . current . input
if 'wf_meta' in data :
return
current_task = self . workflow . get_tasks ( Task . READY ) [ 0 ]
current_task_type = current_task . task_spec . __class__ . __name__
pre_task = current_task . parent
pre_task_type = pre_task . task_spec . __class__ . __name__
if pre_task_type != 'UserTask... |
def OpenFileObject ( cls , path_spec_object , resolver_context = None ) :
"""Opens a file - like object defined by path specification .
Args :
path _ spec _ object ( PathSpec ) : path specification .
resolver _ context ( Optional [ Context ] ) : resolver context , where None
represents the built in context ... | if not isinstance ( path_spec_object , path_spec . PathSpec ) :
raise TypeError ( 'Unsupported path specification type.' )
if resolver_context is None :
resolver_context = cls . _resolver_context
if path_spec_object . type_indicator == definitions . TYPE_INDICATOR_MOUNT :
if path_spec_object . HasParent ( )... |
def end_headers ( self ) :
"""Ends the headers part""" | # Send them all at once
for name , value in self . _headers . items ( ) :
self . _handler . send_header ( name , value )
self . _handler . end_headers ( ) |
def Convert ( self , metadata , checkresult , token = None ) :
"""Converts a single CheckResult .
Args :
metadata : ExportedMetadata to be used for conversion .
checkresult : CheckResult to be converted .
token : Security token .
Yields :
Resulting ExportedCheckResult . Empty list is a valid result and ... | if checkresult . HasField ( "anomaly" ) :
for anomaly in checkresult . anomaly :
exported_anomaly = ExportedAnomaly ( type = anomaly . type , severity = anomaly . severity , confidence = anomaly . confidence )
if anomaly . symptom :
exported_anomaly . symptom = anomaly . symptom
... |
def parse_xml ( self , node ) :
"""Parse a Tileset from ElementTree xml element
A bit of mangling is done here so that tilesets that have external
TSX files appear the same as those that don ' t
: param node : ElementTree element
: return : self""" | import os
# if true , then node references an external tileset
source = node . get ( 'source' , None )
if source :
if source [ - 4 : ] . lower ( ) == ".tsx" : # external tilesets don ' t save this , store it for later
self . firstgid = int ( node . get ( 'firstgid' ) )
# we need to mangle the path -... |
def factory ( description = "" , codes = [ 200 ] , response_example = None , response_ctor = None , ) :
"""desc : Describes a response to an API call
args :
- name : description
type : str
desc : A description of the condition that causes this response
required : false
default : " "
- name : codes
t... | return RouteMethodResponse ( description , codes , response_example , DocString . from_ctor ( response_ctor ) if response_ctor else None , ) |
def mjd_to_ut_datetime ( self , mjd , sqlDate = False , datetimeObject = False ) :
"""* mjd to ut datetime *
Precision should be respected .
* * Key Arguments : * *
- ` ` mjd ` ` - - time in MJD .
- ` ` sqlDate ` ` - - add a ' T ' between date and time instead of space
- ` ` datetimeObject ` ` - - return ... | self . log . info ( 'starting the ``mjd_to_ut_datetime`` method' )
from datetime import datetime
# CONVERT TO UNIXTIME
unixtime = ( float ( mjd ) + 2400000.5 - 2440587.5 ) * 86400.0
theDate = datetime . utcfromtimestamp ( unixtime )
if datetimeObject == False : # DETERMINE PRECISION
strmjd = repr ( mjd )
if "."... |
def cancel_all ( self , product_id = None ) :
"""With best effort , cancel all open orders .
Args :
product _ id ( Optional [ str ] ) : Only cancel orders for this
product _ id
Returns :
list : A list of ids of the canceled orders . Example : :
"144c6f8e - 713f - 4682-8435-5280fbe8b2b4 " ,
" debe4907-... | if product_id is not None :
params = { 'product_id' : product_id }
else :
params = None
return self . _send_message ( 'delete' , '/orders' , params = params ) |
def collate ( data : Iterable , reverse : bool = False ) -> List [ str ] :
""": param list data : a list of strings to be sorted
: param bool reverse : reverse flag , set to get the result in descending order
: return : a list of strings , sorted alphabetically , according to Thai rules
* * Example * * : :
... | return sorted ( data , key = _thkey , reverse = reverse ) |
def get_realms_by_explosion ( self , realms ) :
"""Get all members of this realm including members of sub - realms on multi - levels
: param realms : realms list , used to look for a specific one
: type realms : alignak . objects . realm . Realms
: return : list of members and add realm to realm _ members att... | # If rec _ tag is already set , then we detected a loop in the realms hierarchy !
if getattr ( self , 'rec_tag' , False ) :
self . add_error ( "Error: there is a loop in the realm definition %s" % self . get_name ( ) )
return None
# Ok , not in a loop , we tag the realm and parse its members
self . rec_tag = Tr... |
def raw_content ( self , output = None , str_output = None ) :
"""Searches for ` output ` regex match within content of page , regardless of mimetype .""" | return self . _search_page ( output , str_output , self . response . data , lambda regex , content : regex . search ( content . decode ( ) ) ) |
def do_sing ( self , arg ) :
"""Sing a colorful song .""" | color_escape = COLORS . get ( self . songcolor , Fore . RESET )
self . poutput ( arg , color = color_escape ) |
def reconfigure_resolver ( ) :
"""Reset the resolver configured for this thread to a fresh instance . This
essentially re - reads the system - wide resolver configuration .
If a custom resolver has been set using : func : ` set _ resolver ` , the flag
indicating that no automatic re - configuration shall take... | global _state
_state . resolver = dns . resolver . Resolver ( )
_state . overridden_resolver = False |
def _handle_backend_error ( self , exception , idp ) :
"""See super class satosa . frontends . base . FrontendModule
: type exception : satosa . exception . SATOSAAuthenticationError
: type idp : saml . server . Server
: rtype : satosa . response . Response
: param exception : The SATOSAAuthenticationError ... | loaded_state = self . load_state ( exception . state )
relay_state = loaded_state [ "relay_state" ]
resp_args = loaded_state [ "resp_args" ]
error_resp = idp . create_error_response ( resp_args [ "in_response_to" ] , resp_args [ "destination" ] , Exception ( exception . message ) )
http_args = idp . apply_binding ( res... |
def handle_read ( repo , ** kwargs ) :
"""handles reading repo information""" | log . info ( 'read: %s %s' % ( repo , kwargs ) )
if type ( repo ) in [ unicode , str ] :
return { 'name' : 'Repo' , 'desc' : 'Welcome to Grit' , 'comment' : '' }
else :
return repo . serialize ( ) |
def get_games_by_season ( self , season ) :
"""Game schedule for a specified season .""" | try :
season = int ( season )
except ValueError :
raise FantasyDataError ( 'Error: Invalid method parameters' )
result = self . _method_call ( "Games/{season}" , "stats" , season = season )
return result |
def add_observer ( self , callable_ , entity_type = None , action = None , entity_id = None , predicate = None ) :
"""Register an " on - model - change " callback
Once the model is connected , ` ` callable _ ` `
will be called each time the model changes . ` ` callable _ ` ` should
be Awaitable and accept the... | observer = _Observer ( callable_ , entity_type , action , entity_id , predicate )
self . _observers [ observer ] = callable_ |
def sync_original_prompt ( self , sync_multiplier = 1.0 ) :
'''This attempts to find the prompt . Basically , press enter and record
the response ; press enter again and record the response ; if the two
responses are similar then assume we are at the original prompt .
This can be a slow function . Worst case ... | # All of these timing pace values are magic .
# I came up with these based on what seemed reliable for
# connecting to a heavily loaded machine I have .
self . sendline ( )
time . sleep ( 0.1 )
try : # Clear the buffer before getting the prompt .
self . try_read_prompt ( sync_multiplier )
except TIMEOUT :
pass
... |
def cumulative_value ( self , slip , mmax , mag_value , bbar , dbar , beta ) :
'''Returns the rate of events with M > mag _ value
: param float slip :
Slip rate in mm / yr
: param float mmax :
Maximum magnitude
: param float mag _ value :
Magnitude value
: param float bbar :
\b ar { b } parameter ( ... | delta_m = mmax - mag_value
a_2 = self . _get_a2_value ( bbar , dbar , slip / 10. , beta , mmax )
return a_2 * ( np . exp ( bbar * delta_m ) - 1.0 ) * ( delta_m > 0.0 ) |
def set_branching_model ( self , project , repository , data ) :
"""Set branching model
: param project :
: param repository :
: param data :
: return :""" | url = 'rest/branch-utils/1.0/projects/{project}/repos/{repository}/branchmodel/configuration' . format ( project = project , repository = repository )
return self . put ( url , data = data ) |
def httpauth_login_required ( func ) :
"""Put this decorator before your view to check if the user is logged in
via httpauth and return a JSON 401 error if he / she is not .""" | def wrapper ( request , * args , ** kwargs ) :
user = None
# get the Basic username and password from the request .
auth_string = request . META . get ( 'HTTP_AUTHORIZATION' , None )
if auth_string :
( authmeth , auth ) = auth_string . split ( " " , 1 )
auth = auth . strip ( ) . decode (... |
def serve_file ( load , fnd ) :
'''Return a chunk from a file based on the data received''' | if 'env' in load : # " env " is not supported ; Use " saltenv " .
load . pop ( 'env' )
ret = { 'data' : '' , 'dest' : '' }
if 'path' not in load or 'loc' not in load or 'saltenv' not in load :
return ret
if not fnd [ 'path' ] :
return ret
ret [ 'dest' ] = fnd [ 'rel' ]
gzip = load . get ( 'gzip' , None )
fp... |
def entry_id_from_cobra_encoding ( cobra_id ) :
"""Convert COBRA - encoded ID string to decoded ID string .""" | for escape , symbol in iteritems ( _COBRA_DECODE_ESCAPES ) :
cobra_id = cobra_id . replace ( escape , symbol )
return cobra_id |
def releaseNetToMs ( ) :
"""RELEASE Section 9.3.18.1""" | a = TpPd ( pd = 0x3 )
b = MessageType ( mesType = 0x2d )
# 00101101
c = CauseHdr ( ieiC = 0x08 , eightBitC = 0x0 )
d = CauseHdr ( ieiC = 0x08 , eightBitC = 0x0 )
e = FacilityHdr ( ieiF = 0x1C , eightBitF = 0x0 )
f = UserUserHdr ( ieiUU = 0x7E , eightBitUU = 0x0 )
packet = a / b / c / d / e / f
return packet |
def Write ( self , * state_args , ** state_dict ) :
"""See ` phi . dsl . Expression . Read `""" | if len ( state_dict ) + len ( state_args ) < 1 :
raise Exception ( "Please include at-least 1 state variable, got {0} and {1}" . format ( state_args , state_dict ) )
if len ( state_dict ) > 1 :
raise Exception ( "Please include at-most 1 keyword argument expression, got {0}" . format ( state_dict ) )
if len ( s... |
def get_attrtext ( value ) :
"""attrtext = 1 * ( any non - ATTRIBUTE _ ENDS character )
We allow any non - ATTRIBUTE _ ENDS in attrtext , but add defects to the
token ' s defects list if we find non - attrtext characters . We also register
defects for * any * non - printables even though the RFC doesn ' t exc... | m = _non_attribute_end_matcher ( value )
if not m :
raise errors . HeaderParseError ( "expected attrtext but found {!r}" . format ( value ) )
attrtext = m . group ( )
value = value [ len ( attrtext ) : ]
attrtext = ValueTerminal ( attrtext , 'attrtext' )
_validate_xtext ( attrtext )
return attrtext , value |
def generate_signing_key ( args ) :
"""Generate an ECDSA signing key for signing secure boot images ( post - bootloader )""" | if os . path . exists ( args . keyfile ) :
raise esptool . FatalError ( "ERROR: Key file %s already exists" % args . keyfile )
sk = ecdsa . SigningKey . generate ( curve = ecdsa . NIST256p )
with open ( args . keyfile , "wb" ) as f :
f . write ( sk . to_pem ( ) )
print ( "ECDSA NIST256p private key in PEM forma... |
def summary ( self , CorpNum , JobID , TradeType , TradeUsage , UserID = None ) :
"""수집 결과 요약정보 조회
args
CorpNum : 팝빌회원 사업자번호
JobID : 작업아이디
TradeType : 문서형태 배열 , N - 일반 현금영수증 , C - 취소 현금영수증
TradeUsage : 거래구분 배열 , P - 소등공제용 ... | if JobID == None or len ( JobID ) != 18 :
raise PopbillException ( - 99999999 , "작업아이디(jobID)가 올바르지 않습니다." )
uri = '/HomeTax/Cashbill/' + JobID + '/Summary'
uri += '?TradeType=' + ',' . join ( TradeType )
uri += '&TradeUsage=' + ',' . join ( TradeUsage )
return self . _httpget ( uri , CorpNum , UserID ) |
def get_pytorch_link ( ft ) -> str :
"Returns link to pytorch docs of ` ft ` ." | name = ft . __name__
ext = '.html'
if name == 'device' :
return f'{PYTORCH_DOCS}tensor_attributes{ext}#torch-device'
if name == 'Tensor' :
return f'{PYTORCH_DOCS}tensors{ext}#torch-tensor'
if name . startswith ( 'torchvision' ) :
doc_path = get_module_name ( ft ) . replace ( '.' , '/' )
if inspect . ism... |
def get_configuration_dict ( self , secret_attrs = False ) :
"""Type - specific configuration for backward compatibility""" | cd = { 'repo_nexml2json' : self . repo_nexml2json , 'number_of_shards' : len ( self . _shards ) , 'initialization' : self . _filepath_args , 'shards' : [ ] , }
for i in self . _shards :
cd [ 'shards' ] . append ( i . get_configuration_dict ( secret_attrs = secret_attrs ) )
return cd |
def calculateHurst ( self , series , exponent = None ) :
''': type series : List
: type exponent : int
: rtype : float''' | rescaledRange = list ( )
sizeRange = list ( )
rescaledRangeMean = list ( )
if ( exponent is None ) :
exponent = self . bestExponent ( len ( series ) )
for i in range ( 0 , exponent ) :
partsNumber = int ( math . pow ( 2 , i ) )
size = int ( len ( series ) / partsNumber )
sizeRange . append ( size )
... |
def check_python_classifiers ( package_info , * args ) :
"""Does the package have Python classifiers ?
: param package _ info : package _ info dictionary
: return : Tuple ( is the condition True or False ? , reason if it is False else None , score to be applied )""" | classifiers = package_info . get ( 'classifiers' )
reason = "Python classifiers missing"
result = False
if len ( [ c for c in classifiers if c . startswith ( 'Programming Language :: Python ::' ) ] ) > 0 :
result = True
return result , reason , HAS_PYTHON_CLASSIFIERS |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.