signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def unget_bytes ( self , string ) :
"""Adds bytes to be internal buffer to be read
This method is for reporting bytes from an in _ stream read
not initiated by this Input object""" | self . unprocessed_bytes . extend ( string [ i : i + 1 ] for i in range ( len ( string ) ) ) |
def create_db ( self , models ) :
"""Creates the in - memory SQLite database from the model
configuration .""" | # first create the table definitions
self . tables = dict ( [ ( model_name , self . create_model_table ( model ) ) for model_name , model in iteritems ( models ) ] )
# now create the tables in memory
logger . debug ( "Creating %d database table(s)..." , len ( self . tables ) )
try :
self . Base . metadata . create_... |
def stdout_encode ( u , default = 'utf-8' ) :
"""Encodes a given string with the proper standard out encoding
If sys . stdout . encoding isn ' t specified , it this defaults to @ default
@ default : default encoding
- > # str with standard out encoding""" | # from http : / / stackoverflow . com / questions / 3627793 / best - output - type - and -
# encoding - practices - for - repr - functions
encoding = sys . stdout . encoding or default
return u . encode ( encoding , "replace" ) . decode ( encoding , "replace" ) |
def solveConsKinkyPref ( solution_next , IncomeDstn , PrefShkDstn , LivPrb , DiscFac , CRRA , Rboro , Rsave , PermGroFac , BoroCnstArt , aXtraGrid , vFuncBool , CubicBool ) :
'''Solves a single period of a consumption - saving model with preference shocks
to marginal utility and a different interest rate on savin... | solver = ConsKinkyPrefSolver ( solution_next , IncomeDstn , PrefShkDstn , LivPrb , DiscFac , CRRA , Rboro , Rsave , PermGroFac , BoroCnstArt , aXtraGrid , vFuncBool , CubicBool )
solver . prepareToSolve ( )
solution = solver . solve ( )
return solution |
def _init_map ( self ) :
"""stub""" | self . my_osid_object_form . _my_map [ 'learningObjectiveId' ] = str ( self . _learning_objective_id_metadata [ 'default_id_values' ] [ 0 ] )
self . my_osid_object_form . _my_map [ 'minimumProficiency' ] = str ( self . _minimum_proficiency_metadata [ 'default_id_values' ] [ 0 ] ) |
def set_brightness ( self , brightness , duration = 0 , rapid = False ) :
"""brightness to set
duration in ms""" | color = self . get_color ( )
color2 = ( color [ 0 ] , color [ 1 ] , brightness , color [ 3 ] )
try :
if rapid :
self . fire_and_forget ( LightSetColor , { "color" : color2 , "duration" : duration } , num_repeats = 1 )
else :
self . req_with_ack ( LightSetColor , { "color" : color2 , "duration" :... |
def file_open ( self , fn ) :
"""Yields the opening text of a file section in multipart HTTP .
Parameters
fn : str
Filename for the file being opened and added to the HTTP body""" | yield b'--'
yield self . boundary . encode ( )
yield CRLF
headers = content_disposition ( fn )
headers . update ( content_type ( fn ) )
for c in self . _write_headers ( headers ) :
yield c |
def transliterate ( string ) :
"""Replace non - ASCII characters with an ASCII approximation . If no
approximation exists , the non - ASCII character is ignored . The string must
be ` ` unicode ` ` .
Examples : :
> > > transliterate ( u ' älämölö ' )
u ' alamolo '
> > > transliterate ( u ' Ærøskøbin... | try :
normalized = unicodedata . normalize ( 'NFKD' , unicode ( string ) )
except NameError :
normalized = unicodedata . normalize ( 'NFKD' , string )
return normalized . encode ( 'ascii' , 'ignore' ) . decode ( 'ascii' ) |
def parse_time_indices ( s ) :
"""Parse a string as time indices .
Args :
s : A valid slicing string for time indices . E . g . , ' - 1 ' , ' [ : ] ' , ' : ' , ' 2:10'
Returns :
A slice object .
Raises :
ValueError : If ` s ` does not represent valid time indices .""" | if not s . startswith ( '[' ) :
s = '[' + s + ']'
parsed = command_parser . _parse_slices ( s )
if len ( parsed ) != 1 :
raise ValueError ( 'Invalid number of slicing objects in time indices (%d)' % len ( parsed ) )
else :
return parsed [ 0 ] |
def set_yticklabels_position ( self , row , column , position ) :
"""Specify the position of the axis tick labels .
This is generally only useful for multiplots containing only one
column . This can be used to e . g . alternatively draw the tick
labels on the left or the right of the subplot .
: param row ,... | subplot = self . get_subplot_at ( row , column )
subplot . set_yticklabels_position ( position ) |
def associate ( self , floating_ip_id , port_id ) :
"""Associates the floating IP to the port .
` ` port _ id ` ` represents a VNIC of an instance .
` ` port _ id ` ` argument is different from a normal neutron port ID .
A value passed as ` ` port _ id ` ` must be one of target _ id returned by
` ` list _ t... | # NOTE : In Neutron Horizon floating IP support , port _ id is
# " < port _ id > _ < ip _ address > " format to identify multiple ports .
pid , ip_address = port_id . split ( '_' , 1 )
update_dict = { 'port_id' : pid , 'fixed_ip_address' : ip_address }
self . client . update_floatingip ( floating_ip_id , { 'floatingip'... |
def refresh ( self ) :
"""Reload the current page with the same request as originally done .
Any change ( ` select _ form ` , or any value filled - in in the form ) made to
the current page before refresh is discarded .
: raise ValueError : Raised if no refreshable page is loaded , e . g . , when
using the ... | old_request = self . __state . request
if old_request is None :
raise ValueError ( 'The current page is not refreshable. Either no ' 'page is opened or low-level browser methods ' 'were used to do so' )
resp = self . session . send ( old_request )
Browser . add_soup ( resp , self . soup_config )
self . __state = _B... |
def _snip_whitespace ( self , text ) :
"""* snip the whitespace at the start and end of the text *
* * Key Arguments : * *
- ` ` text ` ` - - the text to snip
* * Return : * *
- ` ` prefix ` ` , ` ` text ` ` , ` ` suffix ` ` - - the starting whitespace , text and endding whitespace""" | self . log . debug ( 'starting the ``_snip_whitespace`` method' )
m = self . reWS . match ( text )
prefix = m . group ( 1 )
text = m . group ( 2 )
suffix = m . group ( 3 )
self . log . debug ( 'completed the ``_snip_whitespace`` method' )
return prefix , text , suffix |
def _ecc_static_length_signature ( key , algorithm , digest ) :
"""Calculates an elliptic curve signature with a static length using pre - calculated hash .
: param key : Elliptic curve private key
: type key : cryptography . hazmat . primitives . asymmetric . ec . EllipticCurvePrivateKey
: param algorithm : ... | pre_hashed_algorithm = ec . ECDSA ( Prehashed ( algorithm . signing_hash_type ( ) ) )
signature = b""
while len ( signature ) != algorithm . signature_len :
_LOGGER . debug ( "Signature length %d is not desired length %d. Recalculating." , len ( signature ) , algorithm . signature_len )
signature = key . sign ... |
def distance ( f1 , f2 ) :
"""Distance between 2 features . The integer result is always positive or zero .
If the features overlap or touch , it is zero .
> > > from intersecter import Feature , distance
> > > distance ( Feature ( 1 , 2 ) , Feature ( 12 , 13 ) )
10
> > > distance ( Feature ( 1 , 2 ) , Fe... | if f1 . end < f2 . start :
return f2 . start - f1 . end
if f2 . end < f1 . start :
return f1 . start - f2 . end
return 0 |
def request ( self , method , url , * args ) :
"""Pass - thru method to make this class behave a little like HTTPConnection""" | return self . http . request ( method , url , * args ) |
def enable_asynchronous ( self ) :
"""Check if socket have been monkey patched by gevent""" | def is_monkey_patched ( ) :
try :
from gevent import monkey , socket
except ImportError :
return False
if hasattr ( monkey , "saved" ) :
return "socket" in monkey . saved
return gevent . socket . socket == socket . socket
if not is_monkey_patched ( ) :
raise Exception ( "To a... |
def _create_single_taskpaper_task_list ( self , content , setName ) :
"""* create single , sorted taskpaper task list from content pulled in from all of the workspace taskpaper docs *
* * Key Arguments : * *
- ` ` content ` ` - - the content to add to the taskpaper task index
- ` ` setName ` ` - - the name of... | self . log . info ( 'starting the ``_create_single_taskpaper_task_list`` method' )
taskpaperDocPath = None
if len ( content ) : # content = content . decode ( " utf - 8 " )
if self . editorialRootPath :
taskpaperDocPath = self . syncFolder + "/e-" + self . workspaceName + "-" + setName + "-tasks.taskpaper"
... |
def coord ( self , func : CoordFunc , * args , ** kwargs ) -> 'Image' :
"Equivalent to ` image . flow = func ( image . flow , image . size ) ` ." | self . flow = func ( self . flow , * args , ** kwargs )
return self |
def resolve_aliases ( self , target , scope = None ) :
"""Resolve aliases in the direct dependencies of the target .
: param target : The direct dependencies of this target are included .
: param scope : When specified , only deps with this scope are included . This is more
than a filter , because it prunes t... | for declared in target . dependencies :
if scope is not None and declared . scope != scope : # Only ` DEFAULT ` scoped deps are eligible for the unused dep check .
continue
elif type ( declared ) in ( AliasTarget , Target ) : # Is an alias . Recurse to expand .
for r , _ in self . resolve_aliase... |
def linkify_one_command_with_commands ( self , commands , prop ) :
"""Link a command to a property ( check _ command for example )
: param commands : commands object
: type commands : alignak . objects . command . Commands
: param prop : property name
: type prop : str
: param default : default command to... | for i in self :
command = getattr ( i , prop , '' ) . strip ( )
if command :
setattr ( i , prop , self . create_commandcall ( i , commands , command ) )
else : # No defined command
setattr ( i , prop , None ) |
def convert_logistic_regression_output ( node , ** kwargs ) :
"""Map MXNet ' s SoftmaxOutput operator attributes to onnx ' s Softmax operator
and return the created node .""" | name = node [ "name" ]
input1_idx = kwargs [ "index_lookup" ] [ node [ "inputs" ] [ 0 ] [ 0 ] ]
input1 = kwargs [ "proc_nodes" ] [ input1_idx ]
sigmoid_node = onnx . helper . make_node ( "Sigmoid" , [ input1 . name ] , [ name ] , name = name )
return [ sigmoid_node ] |
def from_payload ( self , payload ) :
"""Init frame from binary data .""" | self . session_id = payload [ 0 ] * 256 + payload [ 1 ]
self . index_id = payload [ 2 ]
self . node_parameter = payload [ 3 ]
self . seconds = payload [ 4 ] * 256 + payload [ 5 ] |
def system ( self ) -> 'EFBChat' :
"""Set the chat as a system chat .
Only set for channel - level and group - level system chats .
Returns :
EFBChat : This object .""" | self . chat_name = "System"
self . chat_alias = None
self . chat_uid = EFBChat . SYSTEM_ID
self . chat_type = ChatType . System
return self |
def unique_dimkeys ( obj , default_dim = 'Frame' ) :
"""Finds all common dimension keys in the object including subsets of
dimensions . If there are is no common subset of dimensions , None
is returned .
Returns the list of dimensions followed by the list of unique
keys .""" | from . ndmapping import NdMapping , item_check
from . spaces import HoloMap
key_dims = obj . traverse ( lambda x : ( tuple ( x . kdims ) , list ( x . data . keys ( ) ) ) , ( HoloMap , ) )
if not key_dims :
return [ Dimension ( default_dim ) ] , [ ( 0 , ) ]
dim_groups , keys = zip ( * sorted ( key_dims , key = lambd... |
def to_tf_matrix ( expression_matrix , gene_names , tf_names ) :
""": param expression _ matrix : numpy matrix . Rows are observations and columns are genes .
: param gene _ names : a list of gene names . Each entry corresponds to the expression _ matrix column with same index .
: param tf _ names : a list of t... | tuples = [ ( index , gene ) for index , gene in enumerate ( gene_names ) if gene in tf_names ]
tf_indices = [ t [ 0 ] for t in tuples ]
tf_matrix_names = [ t [ 1 ] for t in tuples ]
return expression_matrix [ : , tf_indices ] , tf_matrix_names |
def check_events ( self ) :
'''check for events , calling registered callbacks as needed''' | while self . event_count ( ) > 0 :
event = self . get_event ( )
for callback in self . _callbacks :
callback ( event ) |
def run ( self ) :
"""Parse the script file .
: rtype : : py : class : ` ~ turberfield . dialogue . model . Model `""" | model = Model ( self . fP , self . doc )
self . doc . walkabout ( model )
return model |
def on_data ( self , raw_data ) :
"""Called when raw data is received from connection .
Override this method if you wish to manually handle
the stream data . Return False to stop stream and close connection .""" | data = json . loads ( raw_data )
message_type = data [ 'meta' ] . get ( 'type' )
prepare_method = 'prepare_%s' % ( message_type )
args = getattr ( self , prepare_method , self . prepare_fallback ) ( data . get ( 'data' ) )
method_name = 'on_%s' % ( message_type , )
func = getattr ( self , method_name , self . on_fallba... |
def num_lines ( self ) :
"""Lazy evaluation of the number of lines .
Returns None for stdin input currently .""" | if self . from_stdin :
return None
if not self . _num_lines :
self . _iterate_lines ( )
return self . _num_lines |
def _setup_xauth ( self ) :
'''Set up the Xauthority file and the XAUTHORITY environment variable .''' | handle , filename = tempfile . mkstemp ( prefix = 'PyVirtualDisplay.' , suffix = '.Xauthority' )
self . _xauth_filename = filename
os . close ( handle )
# Save old environment
self . _old_xauth = { }
self . _old_xauth [ 'AUTHFILE' ] = os . getenv ( 'AUTHFILE' )
self . _old_xauth [ 'XAUTHORITY' ] = os . getenv ( 'XAUTHO... |
def find_max_neg ( input_list : list ) -> int :
"""This function identifies the largest negative number in the given list .
Args :
input _ list : A list of integers
Returns :
An integer that represents the largest negative number in the list
Examples :
> > > find _ max _ neg ( [ 1,2,3 , - 4 , - 6 ] )
... | largest_negative = input_list [ 0 ]
for num in input_list :
if num < largest_negative :
largest_negative = num
return largest_negative |
def create_app ( name , config = None , flask_params = None ) :
"""Create app
Generalized way of creating a flask app . Use it in your concrete apps and
do further configuration there : add app - specific options , extensions ,
listeners and other features .
Note : application name should be its fully quali... | from boiler . config import DefaultConfig
if config is None :
config = DefaultConfig ( )
# get flask parameters
options = dict ( import_name = name )
if flask_params is not None :
options . update ( flask_params )
if config . get ( 'FLASK_STATIC_URL' ) is not None :
options [ 'static_url_path' ] = config . ... |
def start ( self ) :
"""Create a background thread for httpd and serve ' forever '""" | self . _process = threading . Thread ( target = self . _background_runner )
self . _process . start ( ) |
def Clone ( self ) :
"""Clone self .
Returns :
AccountState :""" | return AccountState ( self . ScriptHash , self . IsFrozen , self . Votes , self . Balances ) |
def serve_http ( self ) :
"""serve _ http serves the Prometheus endpoint .""" | start_http_server ( port = self . options . port , addr = str ( self . options . address ) ) |
def fen ( self , * , shredder : bool = False , en_passant : str = "legal" , promoted : Optional [ bool ] = None ) -> str :
"""Gets a FEN representation of the position .
A FEN string ( e . g . ,
` ` rnbqkbnr / ppppp / 8/8/8/8 / PPPPP / RNBQKBNR w KQkq - 0 1 ` ` ) consists
of the position part : func : ` ~ che... | return " " . join ( [ self . epd ( shredder = shredder , en_passant = en_passant , promoted = promoted ) , str ( self . halfmove_clock ) , str ( self . fullmove_number ) ] ) |
def rotation_matrix ( self , angles ) :
"""Return the rotation matrix to the system state at ` ` angles ` ` .
Parameters
angles : ` array - like ` or sequence
Euler angles in radians describing the rotation of the detector .
The length of the provided argument ( along the first axis in
case of an array ) ... | squeeze_out = ( np . broadcast ( * angles ) . shape == ( ) )
angles_in = angles
angles = tuple ( np . array ( angle , dtype = float , copy = False , ndmin = 1 ) for angle in angles )
if ( self . check_bounds and not is_inside_bounds ( angles , self . motion_params ) ) :
raise ValueError ( '`angles` {} not in the va... |
def addresses_from_address_families ( address_mapper , specs ) :
"""Given an AddressMapper and list of Specs , return matching BuildFileAddresses .
: raises : : class : ` ResolveError ` if :
- there were no matching AddressFamilies , or
- the Spec matches no addresses for SingleAddresses .
: raises : : clas... | # Capture a Snapshot covering all paths for these Specs , then group by directory .
snapshot = yield Get ( Snapshot , PathGlobs , _spec_to_globs ( address_mapper , specs ) )
dirnames = { dirname ( f ) for f in snapshot . files }
address_families = yield [ Get ( AddressFamily , Dir ( d ) ) for d in dirnames ]
address_fa... |
def submit_recording ( raw_data_json ) :
"""Submit a recording to the database on write - math . com .
Parameters
raw _ data _ json : str
Raw data in JSON format
Raises
requests . exceptions . ConnectionError
If the internet connection is lost .""" | url = "http://www.martin-thoma.de/write-math/classify/index.php"
headers = { 'User-Agent' : 'Mozilla/5.0' , 'Content-Type' : 'application/x-www-form-urlencoded' }
payload = { 'drawnJSON' : raw_data_json }
s = requests . Session ( )
req = requests . Request ( 'POST' , url , headers = headers , data = payload )
prepared ... |
def clean_previous_run ( self ) :
"""Clean variables from previous configuration ,
such as schedulers , broks and external commands
: return : None""" | # Clean all lists
self . arbiters . clear ( )
self . schedulers . clear ( )
with self . external_commands_lock :
self . external_commands = self . external_commands [ : ] |
def parse_args_to_action_args ( self , argv = None ) :
'''Parses args and returns an action and the args that were parsed''' | args = self . parse_args ( argv )
action = self . subcommands [ args . subcommand ] [ 1 ]
return action , args |
def get_labels ( obj ) :
"""Retrieve the labels of a clustering . rst object
: param obj : the clustering . rst object
: return : the resulting labels""" | if Clustering . is_pyclustering_instance ( obj . model ) :
return obj . _labels_from_pyclusters
else :
return obj . model . labels_ |
def get_config ( ) :
"""Get the configuration from file""" | if CONFIG_FILE is not None :
configfile = CONFIG_FILE
else :
configfile = BUILTIN_CONFIG_FILE
config = { }
with open ( configfile , 'r' ) as fp_ :
config = recursive_dict_update ( config , yaml . load ( fp_ , Loader = UnsafeLoader ) )
app_dirs = AppDirs ( 'pyspectral' , 'pytroll' )
user_datadir = app_dirs .... |
def fc_to_features ( dataset ) :
"""converts a dataset to a list of feature objects
Input :
dataset - path to table or feature class
Output :
list of feature objects""" | if arcpyFound :
desc = arcpy . Describe ( dataset )
fields = [ field . name for field in arcpy . ListFields ( dataset ) if field . type not in [ 'Geometry' ] ]
date_fields = [ field . name for field in arcpy . ListFields ( dataset ) if field . type == 'Date' ]
non_geom_fields = copy . deepcopy ( fields ... |
def lambda_handler ( event , context ) :
'''Demonstrates a simple HTTP endpoint using API Gateway . You have full
access to the request and response payload , including headers and
status code .
To scan a DynamoDB table , make a GET request with the TableName as a
query string parameter . To put , update , ... | # print ( " Received event : " + json . dumps ( event , indent = 2 ) )
operations = { 'DELETE' : lambda dynamo , x : dynamo . delete_item ( ** x ) , 'GET' : lambda dynamo , x : dynamo . scan ( ** x ) , 'POST' : lambda dynamo , x : dynamo . put_item ( ** x ) , 'PUT' : lambda dynamo , x : dynamo . update_item ( ** x ) , ... |
def FDMT_initialization ( datain , f_min , f_max , maxDT , dataType ) :
"""Input : datain - visibilities of ( nint , nbl , nchan , npol )
f _ min , f _ max - are the base - band begin and end frequencies .
The frequencies can be entered in both MHz and GHz , units are factored out in all uses .
maxDT - the ma... | # Data initialization is done prior to the first FDMT iteration
# See Equations 17 and 19 in Zackay & Ofek ( 2014)
[ nint , nbl , nchan , npol ] = datain . shape
deltaF = ( f_max - f_min ) / float ( nchan )
deltaT = int ( np . ceil ( ( maxDT - 1 ) * ( 1. / f_min ** 2 - 1. / ( f_min + deltaF ) ** 2 ) / ( 1. / f_min ** 2... |
def create ( self ) :
"""Create the local repository ( if it doesn ' t already exist ) .
: returns : : data : ` True ` if the local repository was just created ,
: data : ` False ` if it already existed .
What : func : ` create ( ) ` does depends on the situation :
- When : attr : ` exists ` is : data : ` T... | if self . exists :
logger . debug ( "Local %s repository (%s) already exists, ignoring request to create it." , self . friendly_name , format_path ( self . local ) )
return False
else :
timer = Timer ( )
if self . remote :
logger . info ( "Creating local %s repository (%s) by cloning %s .." , se... |
def get_traceback_stxt ( ) :
"""Result is ( bytes ) str type on Python 2 and ( unicode ) str type on Python 3.""" | exc_cls , exc_obj , tb_obj = sys . exc_info ( )
txt_s = traceback . format_exception ( exc_cls , exc_obj , tb_obj )
res = '' . join ( txt_s )
return res |
def _compile ( cls , lines ) :
'''Return the filename from the current line .''' | m = cls . RE_EXTEND . match ( lines . current )
if m is None :
raise DefineBlockError ( '''Incorrect block definition at line {}, {}
Should be something like: #extend path/foo.html:''' . format ( lines . pos , lines . current ) )
return m . group ( 1 ) |
def record ( file_path , topic_names = [ ] , host = jps . env . get_master_host ( ) , sub_port = jps . DEFAULT_SUB_PORT ) :
'''record the topic data to the file''' | class TopicRecorder ( object ) :
def __init__ ( self , file_path , topic_names ) :
self . _topic_names = topic_names
self . _file_path = file_path
self . _output = open ( self . _file_path , 'w' )
signal . signal ( signal . SIGINT , self . _handle_signal )
signal . signal ( s... |
def _is_entity ( bpe ) :
"""Return True if the element is a physical entity .""" | if isinstance ( bpe , _bp ( 'Protein' ) ) or isinstance ( bpe , _bpimpl ( 'Protein' ) ) or isinstance ( bpe , _bp ( 'SmallMolecule' ) ) or isinstance ( bpe , _bpimpl ( 'SmallMolecule' ) ) or isinstance ( bpe , _bp ( 'Complex' ) ) or isinstance ( bpe , _bpimpl ( 'Complex' ) ) or isinstance ( bpe , _bp ( 'Rna' ) ) or isi... |
def saveInputsToFile ( self , filename ) :
"""Deprecated .""" | fp = open ( filename , 'w' )
for input in self . inputs :
vec = self . replacePatterns ( input )
for item in vec :
fp . write ( "%f " % item )
fp . write ( "\n" ) |
def append_dictionary_to_file ( localization_key_to_comment , file_path , section_name ) :
"""Appends dictionary of localization keys and comments to a file
Args :
localization _ key _ to _ comment ( dict ) : A mapping between localization keys and comments .
file _ path ( str ) : The path of the file to appe... | output_file = open_strings_file ( file_path , "a" )
write_section_header_to_file ( output_file , section_name )
for entry_key , entry_comment in sorted ( localization_key_to_comment . iteritems ( ) , key = operator . itemgetter ( 1 ) ) :
output_file . write ( u'\n' )
write_entry_to_file ( output_file , entry_co... |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'score' ) and self . score is not None :
_dict [ 'score' ] = self . score
if hasattr ( self , 'confidence' ) and self . confidence is not None :
_dict [ 'confidence' ] = self . confidence
return _dict |
def _actionsiter ( self , message_iterator ) :
"""Iterate bulk actions .
: param message _ iterator : Iterator yielding messages from a queue .""" | for message in message_iterator :
payload = message . decode ( )
try :
if payload [ 'op' ] == 'delete' :
yield self . _delete_action ( payload )
else :
yield self . _index_action ( payload )
message . ack ( )
except NoResultFound :
message . reject ( )... |
def get_parameters ( self , regex_exp , parameters ) :
"""Given a regex expression and the string with the paramers ,
either return a regex match object or raise an exception if the regex
did not find a match
: param regex _ exp :
: param parameters :
: return :""" | # TODO find a better way to do the equate replacement
for rep in self . equates :
parameters = parameters . replace ( rep , str ( self . equates [ rep ] ) )
match = re . match ( regex_exp , parameters )
if not match :
raise iarm . exceptions . ParsingError ( "Parameters are None, did you miss a comma?" )
return... |
def __send_retry_requests ( self , last_send_failure_time ) :
"""Called via Timer from _ _ send _ ready to resend requests which might not have been sent due to transport
failure . This can happen since the current transport implementation does not received acknowledgements
for sent messages .""" | # make sure multiple failures having set multiple times do not run concurrently
with self . __send_retry_requests_lock :
with self . __requests : # produce list instead of generator as requests mapping can change during subsequent loop
retry_reqs = [ req for req in self . __requests . values ( ) if req . _s... |
def wait_on_job ( self , job_id ) :
"""Poll task status until STOPPED""" | while True :
status = self . get_job_status ( job_id )
if status == 'SUCCEEDED' :
logger . info ( 'Batch job {} SUCCEEDED' . format ( job_id ) )
return True
elif status == 'FAILED' : # Raise and notify if job failed
jobs = self . _client . describe_jobs ( jobs = [ job_id ] ) [ 'jobs'... |
def expected_cost_for_region ( short_numobj , region_dialing_from ) :
"""Gets the expected cost category of a short number when dialled from a
region ( however , nothing is implied about its validity ) . If it is
important that the number is valid , then its validity must first be
checked using is _ valid _ s... | if not _region_dialing_from_matches_number ( short_numobj , region_dialing_from ) :
return ShortNumberCost . UNKNOWN_COST
# Note that region _ dialing _ from may be None , in which case metadata will also be None .
metadata = PhoneMetadata . short_metadata_for_region ( region_dialing_from )
if metadata is None : # ... |
def series_lstrip ( series , startswith = 'http://' , ignorecase = True ) :
"""Strip a suffix str ( ` endswith ` str ) from a ` df ` columns or pd . Series of type str""" | return series_strip ( series , startswith = startswith , endswith = None , startsorendswith = None , ignorecase = ignorecase ) |
def execute_get ( self , resource , ** kwargs ) :
"""Execute an HTTP GET request against the API endpoints .
This method is meant for internal use .
: param resource : The last part of the URI
: param kwargs : Additional query parameters ( and optionally headers )
: return : The HTTP response as JSON or ` G... | url = '%s/%s' % ( self . base_url , resource )
headers = kwargs . pop ( 'headers' , dict ( ) )
headers [ 'Accept' ] = 'application/json'
headers [ 'Content-Type' ] = 'application/json'
if kwargs :
separator = '&' if '?' in url else '?'
for key , value in kwargs . items ( ) :
if hasattr ( value , '__iter... |
def _GetNormalizedTimestamp ( self ) :
"""Retrieves the normalized timestamp .
Returns :
decimal . Decimal : normalized timestamp , which contains the number of
seconds since January 1 , 1970 00:00:00 and a fraction of second used
for increased precision , or None if the normalized timestamp cannot be
det... | if self . _normalized_timestamp is None :
if self . _timestamp is not None :
self . _normalized_timestamp = decimal . Decimal ( self . _timestamp )
if self . fraction_of_second is not None :
fraction_of_second = decimal . Decimal ( self . fraction_of_second )
if self . _preci... |
def Dictionary ( self ) :
"""Emulates the items ( ) method of dictionaries .""" | d = self . __dict__ [ '__subject' ] . Dictionary ( ) . copy ( )
d . update ( self . __dict__ [ 'overrides' ] )
return d |
def generate_hash ( data : dict , token : str ) -> str :
"""Generate secret hash
: param data :
: param token :
: return :""" | secret = hashlib . sha256 ( )
secret . update ( token . encode ( 'utf-8' ) )
sorted_params = collections . OrderedDict ( sorted ( data . items ( ) ) )
msg = '\n' . join ( "{}={}" . format ( k , v ) for k , v in sorted_params . items ( ) if k != 'hash' )
return hmac . new ( secret . digest ( ) , msg . encode ( 'utf-8' )... |
def make_environment_relocatable ( home_dir ) :
"""Makes the already - existing environment use relative paths , and takes out
the # ! - based environment selection in scripts .""" | activate_this = os . path . join ( home_dir , 'bin' , 'activate_this.py' )
if not os . path . exists ( activate_this ) :
logger . fatal ( 'The environment doesn\'t have a file %s -- please re-run virtualenv ' 'on this environment to update it' % activate_this )
fixup_scripts ( home_dir )
fixup_pth_and_egg_link ( ho... |
def one_of ( * args ) :
"""Validates that a field value matches one of the values
given to this validator .""" | if len ( args ) == 1 and isinstance ( args [ 0 ] , list ) :
items = args [ 0 ]
else :
items = list ( args )
def validate ( value ) :
if not value in items :
return e ( "{} is not in the list {}" , value , items )
return validate |
def remove_custom_css ( destdir , resource = PKGNAME ) :
"""Remove the kernel CSS from custom . css""" | # Remove the inclusion in the main CSS
if not os . path . isdir ( destdir ) :
return False
custom = os . path . join ( destdir , 'custom.css' )
copy = True
found = False
prefix = css_frame_prefix ( resource )
with io . open ( custom + '-new' , 'wt' ) as fout :
with io . open ( custom ) as fin :
for line... |
def todatetime ( self ) :
"""Converts the current instance to the python builtins : py : class : ` datetime . datetime ` instance .
: return : the new : py : class : ` datetime . datetime ` instance representing the current date and time in gregorian calendar .
: rtype : : py : class : ` datetime . datetime `""... | arr = get_gregorian_date_from_julian_day ( self . tojulianday ( ) )
return datetime ( int ( arr [ 0 ] ) , int ( arr [ 1 ] ) , int ( arr [ 2 ] ) , self . hour , self . minute , self . second , self . microsecond , self . tzinfo ) |
def run0 ( self ) :
"""Run one item ( a callback or an RPC wait _ any ) .
Returns :
A time to sleep if something happened ( may be 0 ) ;
None if all queues are empty .""" | if self . current :
self . inactive = 0
callback , args , kwds = self . current . popleft ( )
_logging_debug ( 'nowevent: %s' , callback . __name__ )
callback ( * args , ** kwds )
return 0
if self . run_idle ( ) :
return 0
delay = None
if self . queue :
delay = self . queue [ 0 ] [ 0 ] - sel... |
def cwt ( ts , freqs = np . logspace ( 0 , 2 ) , wavelet = cwtmorlet , plot = True ) :
"""Continuous wavelet transform
Note the full results can use a huge amount of memory at 64 - bit precision
Args :
ts : Timeseries of m variables , shape ( n , m ) . Assumed constant timestep .
freqs : list of frequencies... | orig_ndim = ts . ndim
if ts . ndim is 1 :
ts = ts [ : , np . newaxis ]
channels = ts . shape [ 1 ]
fs = ( len ( ts ) - 1.0 ) / ( 1.0 * ts . tspan [ - 1 ] - ts . tspan [ 0 ] )
x = signal . detrend ( ts , axis = 0 )
dtype = wavelet ( fs / freqs [ 0 ] , fs / freqs [ 0 ] ) . dtype
coefs = np . zeros ( ( len ( ts ) , le... |
def get_parser ( self , prog_name ) :
"""Override to add command options .""" | parser = argparse . ArgumentParser ( description = self . get_description ( ) , prog = prog_name , add_help = False )
return parser |
def config_filter_lines ( parent_regex , child_regex , source = 'running' ) :
r'''. . versionadded : : 2019.2.0
Return a list of detailed matches , for the configuration blocks ( parent - child
relationship ) whose parent respects the regular expressions configured via
the ` ` parent _ regex ` ` argument , an... | config_txt = __salt__ [ 'net.config' ] ( source = source ) [ 'out' ] [ source ]
return __salt__ [ 'ciscoconfparse.filter_lines' ] ( config = config_txt , parent_regex = parent_regex , child_regex = child_regex ) |
def pypackable ( name , pytype , format ) :
"""Create a " mix - in " class with a python type and a
Packable with the given struct format""" | size , items = _formatinfo ( format )
return type ( Packable ) ( name , ( pytype , Packable ) , { '_format_' : format , '_size_' : size , '_items_' : items , } ) |
def close ( self ) :
"""Close and delete instance .""" | # remove callbacks
DatastoreLegacy . datastores [ self . domain ] . remove ( self )
# delete data after the last instance is gone
if self . release_storage and not DatastoreLegacy . datastores [ self . domain ] :
del DatastoreLegacy . store [ self . domain ]
del self |
def _unset_child ( self , name , child ) :
"""Untie child from parent .
: param name : Child name .
: param child : Parentable object .""" | if name not in self . _children or self . _children [ name ] is not child :
msg = 'Child {child} with name "{name}" is not found'
raise ValueError ( msg . format ( child = child , name = name ) )
child . _set_parent ( None )
self . _remove_child ( name , child ) |
def BNF ( ) :
"""expop : : ' ^ '
multop : : ' * ' | ' / '
addop : : ' + ' | ' - '
integer : : [ ' + ' | ' - ' ] ' 0 ' . . ' 9 ' +
atom : : PI | E | real | fn ' ( ' expr ' ) ' | ' ( ' expr ' ) '
factor : : atom [ expop factor ] *
term : : factor [ multop factor ] *
expr : : term [ addop term ] *""" | global bnf
if not bnf :
point = Literal ( "." )
# use CaselessKeyword for e and pi , to avoid accidentally matching
# functions that start with ' e ' or ' pi ' ( such as ' exp ' ) ; Keyword
# and CaselessKeyword only match whole words
e = CaselessKeyword ( "E" )
pi = CaselessKeyword ( "PI" )
... |
def cisco_conf_parse_parents ( parent , child , config ) :
"""Use CiscoConfParse to find parent lines that contain a specific child line .
: param parent : The parent line to search for
: param child : The child line required under the given parent
: param config : The device running / startup config""" | if type ( config ) == str :
config = config . splitlines ( )
parse = CiscoConfParse ( config )
cfg_obj = parse . find_parents_w_child ( parent , child )
return cfg_obj |
def boot ( zone , single = False , altinit = None , smf_options = None ) :
'''Boot ( or activate ) the specified zone .
zone : string
name or uuid of the zone
single : boolean
boots only to milestone svc : / milestone / single - user : default .
altinit : string
valid path to an alternative executable t... | ret = { 'status' : True }
# # build boot _ options
boot_options = ''
if single :
boot_options = '-s {0}' . format ( boot_options )
if altinit : # note : we cannot validate the path , as this is local to the zonepath .
boot_options = '-i {0} {1}' . format ( altinit , boot_options )
if smf_options :
boot_opti... |
def setup ( app ) :
"""Set up the plugin""" | app . add_config_value ( 'sphinx_tabs_nowarn' , False , '' )
app . add_config_value ( 'sphinx_tabs_valid_builders' , [ ] , '' )
app . add_directive ( 'tabs' , TabsDirective )
app . add_directive ( 'tab' , TabDirective )
app . add_directive ( 'group-tab' , GroupTabDirective )
app . add_directive ( 'code-tab' , CodeTabDi... |
def _instantiate_layers ( self ) :
"""Instantiates all the linear modules used in the network .
Layers are instantiated in the constructor , as opposed to the build
function , because MLP implements the Transposable interface , and the
transpose function can be called before the module is actually connected
... | # Here we are entering the module ' s variable scope to name our submodules
# correctly ( not to create variables ) . As such it ' s safe to not check
# whether we ' re in the same graph . This is important if we ' re constructing
# the module in one graph and connecting it in another ( e . g . with ` defun `
# the mod... |
def prepare_static_data ( self , data ) :
"""If user defined static fields , then process them with visiable value""" | d = data . copy ( )
for f in self . get_fields ( ) :
if f [ 'static' ] and f [ 'name' ] in d :
d [ f [ 'name' ] ] = make_view_field ( f , None , self . types_convert_map , self . fields_convert_map , d [ f [ 'name' ] ] ) [ 'display' ]
return d |
def make_oracle ( input_qubits , output_qubit , secret_factor_bits , secret_bias_bit ) :
"""Gates implementing the function f ( a ) = a · factors + bias ( mod 2 ) .""" | if secret_bias_bit :
yield cirq . X ( output_qubit )
for qubit , bit in zip ( input_qubits , secret_factor_bits ) :
if bit :
yield cirq . CNOT ( qubit , output_qubit ) |
def setup ( app ) :
"""Allow this module to be used as sphinx extension .
This attaches the Sphinx hooks .
: type app : sphinx . application . Sphinx""" | import sphinxcontrib_django . docstrings
import sphinxcontrib_django . roles
# Setup both modules at once . They can also be separately imported to
# use only fragments of this package .
sphinxcontrib_django . docstrings . setup ( app )
sphinxcontrib_django . roles . setup ( app ) |
def start ( self ) :
"""Starts this QEMU VM .""" | with ( yield from self . _execute_lock ) :
if self . is_running ( ) : # resume the VM if it is paused
yield from self . resume ( )
return
if self . _manager . config . get_section_config ( "Qemu" ) . getboolean ( "monitor" , True ) :
try :
info = socket . getaddrinfo ( self .... |
def dao_fork_at ( dao_fork_block_number : BlockNumber , chain_class : Type [ BaseChain ] ) -> Type [ BaseChain ] :
"""Set the block number on which the DAO fork will happen . Requires that a
version of the : class : ` ~ eth . vm . forks . homestead . HomesteadVM ` is present in
the chain ' s ` ` vm _ configurat... | homstead_vms_found = any ( _is_homestead ( vm_class ) for _ , vm_class in chain_class . vm_configuration )
if not homstead_vms_found :
raise ValidationError ( "No HomesteadVM found in vm_configuration." )
vm_configuration = _set_vm_dao_fork_block_number ( dao_fork_block_number , chain_class . vm_configuration , )
r... |
def always ( func : Callable [ [ ] , Generator ] ) -> AlwaysFixture :
"""Decorator that registers an ' always ' fixture , which is always run before all provider
state fixtures and faasport call .""" | global user_always
if user_always is not None :
raise RuntimeError ( 'Multiple definitions of @always fixture.' )
as_context_manager = contextmanager ( func )
user_always = as_context_manager
return as_context_manager |
def scp_file_remote_to_local ( self , remote_path , local_path ) :
"""Scp a remote file to local
Args :
remote _ path ( str )
local _ path ( str )""" | sshadd_command = [ 'ssh-add' , '/Users/pyrat/.ssh/ubuntuNode' ]
self . info_log ( "executing command: %s" % ' ' . join ( sshadd_command ) )
p = subprocess . Popen ( sshadd_command )
p . wait ( )
scp_command = [ 'scp' , '-o' , 'StrictHostKeyChecking=no' , '%s@%s:"%s"' % ( self . browser_config . get ( 'username' ) , sel... |
def kindpath ( self , kind ) :
"""Returns a path to the resources for a given input kind .
: param ` kind ` : The kind of input :
- " ad " : Active Directory
- " monitor " : Files and directories
- " registry " : Windows Registry
- " script " : Scripts
- " splunktcp " : TCP , processed
- " tcp " : TCP... | if kind == 'tcp' :
return UrlEncoded ( 'tcp/raw' , skip_encode = True )
elif kind == 'splunktcp' :
return UrlEncoded ( 'tcp/cooked' , skip_encode = True )
else :
return UrlEncoded ( kind , skip_encode = True ) |
def fetch_data ( self , stock_no , nowdatetime ) :
"""Fetch data from twse . com . tw
return list .
從 twse . com . tw 下載資料 , 回傳格式為 csv . reader
0 . 日期
1 . 成交股數
2 . 成交金額
3 . 開盤價
4 . 最高價 ( 續 )
5 . 最低價
6 . 收盤價
7 . 漲跌價差
8 . 成交筆數
: param str stock _ no : 股票代碼
: param datetime nowdatetime : 此刻時間... | result = TWSE_CONNECTIONS . request ( 'POST' , '/ch/trading/exchange/STOCK_DAY/STOCK_DAYMAIN.php' , fields = { 'download' : 'csv' , 'query_year' : nowdatetime . year , 'query_month' : nowdatetime . month , 'CO_ID' : stock_no } )
_de = result . data . decode ( 'cp950' , 'ignore' )
csv_files = csv . reader ( StringIO ( _... |
def get_all_loopbacks ( engine ) :
"""Get all loopback interfaces for a given engine""" | data = [ ]
if 'fw_cluster' in engine . type :
for cvi in engine . data . get ( 'loopback_cluster_virtual_interface' , [ ] ) :
data . append ( LoopbackClusterInterface ( cvi , engine ) )
for node in engine . nodes :
for lb in node . data . get ( 'loopback_node_dedicated_interface' , [ ] ) :
data ... |
def cmd_wp_remove ( self , args ) :
'''handle wp remove''' | if len ( args ) != 1 :
print ( "usage: wp remove WPNUM" )
return
idx = int ( args [ 0 ] )
if idx < 0 or idx >= self . wploader . count ( ) :
print ( "Invalid wp number %u" % idx )
return
wp = self . wploader . wp ( idx )
# setup for undo
self . undo_wp = copy . copy ( wp )
self . undo_wp_idx = idx
self ... |
def _include_exclude ( file_path , include = None , exclude = None ) :
"""Check if file matches one of include filters and not in exclude filter .
: param file _ path : Path to the file .
: param include : Tuple containing patterns to which include from result .
: param exclude : Tuple containing patterns to ... | if exclude is not None and exclude :
for pattern in exclude :
if file_path . match ( pattern ) :
return False
if include is not None and include :
for pattern in include :
if file_path . match ( pattern ) :
return True
return False
return True |
def export ( self , output : str = None , exclude : List [ str ] = None , ** kwargs ) :
"""Export the collection item in the Mimetype required .
. . note : : If current implementation does not have special mimetypes , reuses default _ export method
: param output : Mimetype to export to ( Uses MyCapytain . comm... | return Exportable . export ( self , output , exclude = exclude , ** kwargs ) |
async def read_headers ( stream : asyncio . StreamReader ) -> "Headers" :
"""Read HTTP headers from ` ` stream ` ` .
` ` stream ` ` is an : class : ` ~ asyncio . StreamReader ` .
Return a : class : ` Headers ` instance
Non - ASCII characters are represented with surrogate escapes .""" | # https : / / tools . ietf . org / html / rfc7230 # section - 3.2
# We don ' t attempt to support obsolete line folding .
headers = Headers ( )
for _ in range ( MAX_HEADERS + 1 ) :
line = await read_line ( stream )
if line == b"" :
break
# This may raise " ValueError : not enough values to unpack "
... |
def disapproveworker ( ctx , workers , account ) :
"""Disapprove worker ( es )""" | print_tx ( ctx . bitshares . disapproveworker ( workers , account = account ) ) |
def main ( ) :
"""Fetch simple gene - term assocaitions from Golr using bioentity document type , one line per gene .""" | import argparse
prs = argparse . ArgumentParser ( __doc__ , formatter_class = argparse . ArgumentDefaultsHelpFormatter )
prs . add_argument ( '--taxon_id' , type = str , help = 'NCBI taxon ID, must match exact species/strain used by GO Central, e.g. 4896 for S Pombe' )
prs . add_argument ( '--golr_url' , default = 'htt... |
def p_recent ( self , kind , cur_p = '' , with_catalog = True , with_date = True ) :
'''List posts that recent edited , partially .''' | if cur_p == '' :
current_page_number = 1
else :
current_page_number = int ( cur_p )
current_page_number = 1 if current_page_number < 1 else current_page_number
pager_num = int ( MPost . total_number ( kind ) / CMS_CFG [ 'list_num' ] )
kwd = { 'pager' : '' , 'title' : 'Recent posts.' , 'with_catalog' : with_cata... |
def _find_methods ( cls , * names , ** kwds ) :
"""Compute a list of composable methods .
Because this is a common operation and the class hierarchy is
static , the outcome is cached ( assuming that for a particular list
of names the reversed flag is either always on , or always off ) .
Args :
* names : O... | reverse = kwds . pop ( 'reverse' , False )
assert not kwds , repr ( kwds )
cache = cls . __dict__ . get ( '_find_methods_cache' )
if cache :
hit = cache . get ( names )
if hit is not None :
return hit
else :
cls . _find_methods_cache = cache = { }
methods = [ ]
for c in cls . __mro__ :
for name ... |
def cmd_line ( line , ctrl ) :
clients = ctrl . modules
""": type : list [ WrapperClient ]""" | if line == "update start" :
for client in clients :
client . updating_start ( )
elif line == "update stop" :
for client in clients :
client . updating_stop ( )
return line |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.