signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def save_volt ( elecs , volt , filename ) :
"""Save the values in volt - format .""" | # bring data in shape
content = np . column_stack ( ( elecs , volt , np . zeros ( len ( volt ) ) ) )
# save datapoints
with open ( filename , 'w' ) as fid :
fid . write ( '{0}\n' . format ( content . shape [ 0 ] ) )
with open ( filename , 'ab' ) as fid :
np . savetxt ( fid , np . array ( content ) , fmt = '%i %... |
def set_umr_namelist ( self ) :
"""Set UMR excluded modules name list""" | arguments , valid = QInputDialog . getText ( self , _ ( 'UMR' ) , _ ( "Set the list of excluded modules as " "this: <i>numpy, scipy</i>" ) , QLineEdit . Normal , ", " . join ( self . get_option ( 'umr/namelist' ) ) )
if valid :
arguments = to_text_string ( arguments )
if arguments :
namelist = arguments... |
def handle_json_GET_routepatterns ( self , params ) :
"""Given a route _ id generate a list of patterns of the route . For each
pattern include some basic information and a few sample trips .""" | schedule = self . server . schedule
route = schedule . GetRoute ( params . get ( 'route' , None ) )
if not route :
self . send_error ( 404 )
return
time = int ( params . get ( 'time' , 0 ) )
date = params . get ( 'date' , "" )
sample_size = 3
# For each pattern return the start time for this many trips
pattern_... |
def add_metrics ( self , metrics : Iterable [ float ] ) -> None :
"""Helper to add multiple metrics at once .""" | for metric in metrics :
self . add_metric ( metric ) |
def get_params ( self , deep = False ) :
"""Get parameter . s""" | params = super ( XGBModel , self ) . get_params ( deep = deep )
if params [ 'missing' ] is np . nan :
params [ 'missing' ] = None
# sklearn doesn ' t handle nan . see # 4725
if not params . get ( 'eval_metric' , True ) :
del params [ 'eval_metric' ]
# don ' t give as None param to Booster
return params |
def download_reference_files ( job , inputs , samples ) :
"""Downloads shared files that are used by all samples for alignment , or generates them if they were not provided .
: param JobFunctionWrappingJob job : passed automatically by Toil
: param Namespace inputs : Input arguments ( see main )
: param list ... | # Create dictionary to store FileStoreIDs of shared input files
shared_ids = { }
urls = [ ( 'amb' , inputs . amb ) , ( 'ann' , inputs . ann ) , ( 'bwt' , inputs . bwt ) , ( 'pac' , inputs . pac ) , ( 'sa' , inputs . sa ) ]
# Alt file is optional and can only be provided , not generated
if inputs . alt :
urls . appe... |
def prepend_bcbiopath ( ) :
"""Prepend paths in the BCBIOPATH environment variable ( if any ) to PATH .
Uses either a pre - sent global environmental variable ( BCBIOPATH ) or the
local anaconda directory .""" | if os . environ . get ( 'BCBIOPATH' ) :
os . environ [ 'PATH' ] = _prepend ( os . environ . get ( 'PATH' , '' ) , os . environ . get ( 'BCBIOPATH' , None ) )
else :
os . environ [ 'PATH' ] = _prepend ( os . environ . get ( 'PATH' , '' ) , utils . get_bcbio_bin ( ) ) |
def markdownify ( markdown_content ) :
"""Render the markdown content to HTML .
Basic :
> > > from martor . utils import markdownify
> > > content = " ! [ awesome ] ( http : / / i . imgur . com / hvguiSn . jpg ) "
> > > markdownify ( content )
' < p > < img alt = " awesome " src = " http : / / i . imgur .... | try :
return markdown . markdown ( markdown_content , safe_mode = MARTOR_MARKDOWN_SAFE_MODE , extensions = MARTOR_MARKDOWN_EXTENSIONS , extension_configs = MARTOR_MARKDOWN_EXTENSION_CONFIGS )
except Exception :
raise VersionNotCompatible ( "The markdown isn't compatible, please reinstall " "your python markdown... |
async def createAnswer ( self ) :
"""Create an SDP answer to an offer received from a remote peer during
the offer / answer negotiation of a WebRTC connection .
: rtype : : class : ` RTCSessionDescription `""" | # check state is valid
self . __assertNotClosed ( )
if self . signalingState not in [ 'have-remote-offer' , 'have-local-pranswer' ] :
raise InvalidStateError ( 'Cannot create answer in signaling state "%s"' % self . signalingState )
# create description
ntp_seconds = clock . current_ntp_time ( ) >> 32
description =... |
def intersects ( self , other ) :
'''Returns True iff this record ' s reference positions overlap
the other record reference positions ( and are on same chromosome )''' | return self . CHROM == other . CHROM and self . POS <= other . ref_end_pos ( ) and other . POS <= self . ref_end_pos ( ) |
def restart ( ctx , ** kwargs ) :
"""restart a vaping process""" | update_context ( ctx , kwargs )
daemon = mk_daemon ( ctx )
daemon . stop ( )
daemon . start ( ) |
def _match_display_text ( self , element_key , string , string_match_type , match ) :
"""Matches a display text value""" | if string is None or string_match_type is None :
raise NullArgument ( )
match_value = self . _get_string_match_value ( string , string_match_type )
self . _add_match ( element_key + '.text' , match_value , match ) |
def export ( self , private_keys = True ) :
"""Exports a RFC 7517 keyset using the standard JSON format
: param private _ key ( bool ) : Whether to export private keys .
Defaults to True .""" | exp_dict = dict ( )
for k , v in iteritems ( self ) :
if k == 'keys' :
keys = list ( )
for jwk in v :
keys . append ( json_decode ( jwk . export ( private_keys ) ) )
v = keys
exp_dict [ k ] = v
return json_encode ( exp_dict ) |
def list ( showgroups ) :
"""Show list of Anchore data feeds .""" | ecode = 0
try :
result = { }
subscribed = { }
available = { }
unavailable = { }
current_user_data = contexts [ 'anchore_auth' ] [ 'user_info' ]
feedmeta = anchore_feeds . load_anchore_feedmeta ( )
for feed in feedmeta . keys ( ) :
if feedmeta [ feed ] [ 'subscribed' ] :
s... |
def from_interval_shorthand ( self , startnote , shorthand , up = True ) :
"""Empty the container and add the note described in the startnote and
shorthand .
See core . intervals for the recognized format .
Examples :
> > > nc = NoteContainer ( )
> > > nc . from _ interval _ shorthand ( ' C ' , ' 5 ' )
... | self . empty ( )
if type ( startnote ) == str :
startnote = Note ( startnote )
n = Note ( startnote . name , startnote . octave , startnote . dynamics )
n . transpose ( shorthand , up )
self . add_notes ( [ startnote , n ] )
return self |
def get_note_names ( self ) :
"""Return a list with all the note names in the current container .
Every name will only be mentioned once .""" | res = [ ]
for n in self . notes :
if n . name not in res :
res . append ( n . name )
return res |
def get_and_set ( self , value ) :
'''Atomically sets the value to ` value ` and returns the old value .
: param value : The value to set .''' | with self . _reference . get_lock ( ) :
oldval = self . _reference . value
self . _reference . value = value
return oldval |
def stop ( self ) :
"""Stop the sensor .""" | # check that everything is running
if not self . _running :
logging . warning ( 'Realsense not running. Aborting stop.' )
return False
self . _pipe . stop ( )
self . _running = False
return True |
def commit ( self , session , mutations , transaction_id = None , single_use_transaction = None , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) :
"""Commits a transaction . The request includes the mutations to be applied
... | # Wrap the transport method to add retry and timeout logic .
if "commit" not in self . _inner_api_calls :
self . _inner_api_calls [ "commit" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . commit , default_retry = self . _method_configs [ "Commit" ] . retry , default_timeout = self . _m... |
def create_context ( self , message_queue , task_id ) :
"""Create data needed by upload _ project _ run ( DukeDS connection info ) .
: param message _ queue : Queue : queue background process can send messages to us on
: param task _ id : int : id of this command ' s task so message will be routed correctly""" | params = ( self . settings . dest_directory , self . file_url . json_data , self . seek_amt , self . bytes_to_read )
return DownloadContext ( self . settings , params , message_queue , task_id ) |
def train ( self , images ) :
r"""Train a standard intensity space and an associated transformation model .
Note that the passed images should be masked to contain only the foreground .
Parameters
images : sequence of array _ likes
A number of images .
Returns
IntensityRangeStandardization : IntensityRa... | self . __stdrange = self . __compute_stdrange ( images )
lim = [ ]
for idx , i in enumerate ( images ) :
ci = numpy . array ( numpy . percentile ( i , self . __cutoffp ) )
li = numpy . array ( numpy . percentile ( i , self . __landmarkp ) )
ipf = interp1d ( ci , self . __stdrange )
lim . append ( ipf ( ... |
def inherit_handlers ( self , excluded_handlers ) : # type : ( Iterable [ str ] ) - > None
"""Merges the inherited configuration with the current ones
: param excluded _ handlers : Excluded handlers""" | if not excluded_handlers :
excluded_handlers = tuple ( )
for handler , configuration in self . __inherited_configuration . items ( ) :
if handler in excluded_handlers : # Excluded handler
continue
elif handler not in self . __handlers : # Fully inherited configuration
self . __handlers [ han... |
def show_settings ( self ) :
"""Open the Setting windows , after updating the values in GUI .""" | self . notes . config . put_values ( )
self . overview . config . put_values ( )
self . settings . config . put_values ( )
self . spectrum . config . put_values ( )
self . traces . config . put_values ( )
self . video . config . put_values ( )
self . settings . show ( ) |
def files_size ( fs0 , fs1 , files ) :
"""Gets the file size of the given files .""" | for file_meta in files [ 'deleted_files' ] :
file_meta [ 'size' ] = fs0 . stat ( file_meta [ 'path' ] ) [ 'size' ]
for file_meta in files [ 'created_files' ] + files [ 'modified_files' ] :
file_meta [ 'size' ] = fs1 . stat ( file_meta [ 'path' ] ) [ 'size' ]
return files |
def first_timestamp ( self , event_key = None ) :
"""Obtain the first timestamp .
Args :
event _ key : the type key of the sought events ( e . g . , constants . NAN _ KEY ) .
If None , includes all event type keys .
Returns :
First ( earliest ) timestamp of all the events of the given type ( or all
even... | if event_key is None :
timestamps = [ self . _trackers [ key ] . first_timestamp for key in self . _trackers ]
return min ( timestamp for timestamp in timestamps if timestamp >= 0 )
else :
return self . _trackers [ event_key ] . first_timestamp |
def update ( self , ** kwargs ) :
"""Update a service ' s configuration . Similar to the ` ` docker service
update ` ` command .
Takes the same parameters as : py : meth : ` ~ ServiceCollection . create ` .
Raises :
: py : class : ` docker . errors . APIError `
If the server returns an error .""" | # Image is required , so if it hasn ' t been set , use current image
if 'image' not in kwargs :
spec = self . attrs [ 'Spec' ] [ 'TaskTemplate' ] [ 'ContainerSpec' ]
kwargs [ 'image' ] = spec [ 'Image' ]
if kwargs . get ( 'force_update' ) is True :
task_template = self . attrs [ 'Spec' ] [ 'TaskTemplate' ]
... |
def wosParser ( isifile ) :
"""This is a function that is used to create [ RecordCollections ] ( . . / classes / RecordCollection . html # metaknowledge . RecordCollection ) from files .
* * wosParser * * ( ) reads the file given by the path isifile , checks that the header is correct then reads until it reaches ... | plst = set ( )
error = None
try :
with open ( isifile , 'r' , encoding = 'utf-8-sig' ) as openfile :
f = enumerate ( openfile , start = 0 )
while "VR 1.0" not in f . __next__ ( ) [ 1 ] :
pass
notEnd = True
while notEnd :
line = f . __next__ ( )
if ... |
def romanize ( number ) :
"""Convert ` number ` to a Roman numeral .""" | roman = [ ]
for numeral , value in NUMERALS :
times , number = divmod ( number , value )
roman . append ( times * numeral )
return '' . join ( roman ) |
def normalize_excludes ( rootpath , excludes ) :
"""Normalize the excluded directory list .""" | return [ path . normpath ( path . abspath ( exclude ) ) for exclude in excludes ] |
def _get_LMv1_response ( password , server_challenge ) :
"""[ MS - NLMP ] v28.0 2016-07-14
2.2.2.3 LM _ RESPONSE
The LM _ RESPONSE structure defines the NTLM v1 authentication LmChallengeResponse
in the AUTHENTICATE _ MESSAGE . This response is used only when NTLM v1
authentication is configured .
: param... | lm_hash = comphash . _lmowfv1 ( password )
response = ComputeResponse . _calc_resp ( lm_hash , server_challenge )
return response |
def delete_state_changes ( self , state_changes_to_delete : List [ int ] ) -> None :
"""Delete state changes .
Args :
state _ changes _ to _ delete : List of ids to delete .""" | with self . write_lock , self . conn :
self . conn . executemany ( 'DELETE FROM state_events WHERE identifier = ?' , state_changes_to_delete , ) |
def read_chunk_body ( self ) :
'''Read a fragment of a single chunk .
Call : meth : ` read _ chunk _ header ` first .
Returns :
tuple : 2 - item tuple with the content data and raw data .
First item is empty bytes string when chunk is fully read .
Coroutine .''' | # chunk _ size = self . _ chunk _ size
bytes_left = self . _bytes_left
# _ logger . debug ( _ _ ( ' Getting chunk size = { 0 } , remain = { 1 } . ' ,
# chunk _ size , bytes _ left ) )
if bytes_left > 0 :
size = min ( bytes_left , self . _read_size )
data = yield from self . _connection . read ( size )
self ... |
def readline ( self ) :
"""Read one line from the pseudoterminal , and return it as unicode .
Can block if there is nothing to read . Raises : exc : ` EOFError ` if the
terminal was closed .""" | try :
s = self . fileobj . readline ( )
except ( OSError , IOError ) as err :
if err . args [ 0 ] == errno . EIO : # Linux - style EOF
self . flag_eof = True
raise EOFError ( 'End Of File (EOF). Exception style platform.' )
raise
if s == b'' : # BSD - style EOF ( also appears to work on rece... |
def copy_public_attrs ( source_obj , dest_obj ) :
"""Shallow copies all public attributes from source _ obj to dest _ obj .
Overwrites them if they already exist .""" | for name , value in inspect . getmembers ( source_obj ) :
if not any ( name . startswith ( x ) for x in [ "_" , "func" , "im" ] ) :
setattr ( dest_obj , name , value ) |
def list_role_secrets ( self , role_name , mount_point = 'approle' ) :
"""LIST / auth / < mount _ point > / role / < role name > / secret - id
: param role _ name : Name of the AppRole .
: type role _ name : str | unicode
: param mount _ point : The " path " the AppRole auth backend was mounted on . Vault cur... | url = '/v1/auth/{mount_point}/role/{name}/secret-id' . format ( mount_point = mount_point , name = role_name )
return self . _adapter . list ( url ) . json ( ) |
def _update_time ( self ) :
"""Increments the timestep counter by one .
Furthermore ` ` self . time [ ' days _ elapsed ' ] ` ` and
` ` self . time [ ' num _ steps _ per _ year ' ] ` ` are updated .
The function is called by the time stepping methods .""" | self . time [ 'steps' ] += 1
# time in days since beginning
self . time [ 'days_elapsed' ] += self . time [ 'timestep' ] / const . seconds_per_day
if self . time [ 'day_of_year_index' ] >= self . time [ 'num_steps_per_year' ] - 1 :
self . _do_new_calendar_year ( )
else :
self . time [ 'day_of_year_index' ] += 1 |
def sort_values ( self , return_indexer = False , ascending = True ) :
"""Return sorted copy of Index .""" | if return_indexer :
_as = self . argsort ( )
if not ascending :
_as = _as [ : : - 1 ]
sorted_index = self . take ( _as )
return sorted_index , _as
else :
sorted_values = np . sort ( self . _ndarray_values )
attribs = self . _get_attributes_dict ( )
freq = attribs [ 'freq' ]
if fr... |
def mongoimport ( json , database , ip = 'localhost' , port = 27017 , user = None , password = None , delim = '_' , delim1 = None , delim2 = None , delim_occurance = 1 , delim1_occurance = 1 , delim2_occurance = 1 ) :
'''Performs mongoimport on one or more json files .
Args :
json : Can be one of several things... | logger = log . get_logger ( 'mongodb' )
_print_mongoimport_info ( logger )
if type ( json ) in ( list , tuple ) :
pass
elif os . path . isdir ( json ) :
from abtools . utils . pipeline import list_files
json = list_files ( json )
else :
json = [ json , ]
jsons = sorted ( [ os . path . expanduser ( j ) f... |
def _filter_meta_data ( self , source , soup , data , url = None ) :
"""This method filters the web page content for meta tags that match patterns given in the ` ` FILTER _ MAPS ` `
: param source : The key of the meta dictionary in ` ` FILTER _ MAPS [ ' meta ' ] ` `
: type source : string
: param soup : Beau... | meta = FILTER_MAPS [ 'meta' ] [ source ]
meta_map = meta [ 'map' ]
html = soup . find_all ( 'meta' , { meta [ 'key' ] : meta [ 'pattern' ] } )
image = { }
video = { }
for line in html :
prop = line . get ( meta [ 'key' ] )
value = line . get ( 'content' )
_prop = meta_map . get ( prop )
if prop in meta_... |
def remove_datasource ( jboss_config , name , profile = None ) :
'''Remove an existing datasource from the running jboss instance .
jboss _ config
Configuration dictionary with properties specified above .
name
Datasource name
profile
The profile ( JBoss domain mode only )
CLI Example :
. . code - b... | log . debug ( "======================== MODULE FUNCTION: jboss7.remove_datasource, name=%s, profile=%s" , name , profile )
operation = '/subsystem=datasources/data-source={name}:remove' . format ( name = name )
if profile is not None :
operation = '/profile="{profile}"' . format ( profile = profile ) + operation
re... |
def stop_instance ( self , instance_id ) :
"""Stops the instance gracefully .
: param str instance _ id : instance identifier""" | self . _init_az_api ( )
cluster_name , node_name = instance_id
self . _init_inventory ( cluster_name )
for name , api_version in [ # we must delete resources in a specific order : e . g . ,
# a public IP address cannot be deleted if it ' s still
# in use by a NIC . . .
( node_name , '2018-06-01' ) , ( node_name + '-nic... |
def convert2wavenumber ( self ) :
"""Convert from wavelengths to wavenumber .
Units :
Wavelength : micro meters ( 1e - 6 m )
Wavenumber : cm - 1""" | self . wavenumber = 1. / ( 1e-4 * self . wavelength [ : : - 1 ] )
self . irradiance = ( self . irradiance [ : : - 1 ] * self . wavelength [ : : - 1 ] * self . wavelength [ : : - 1 ] * 0.1 )
self . wavelength = None |
def update_question ( self , question , publisher_name , extension_name , question_id ) :
"""UpdateQuestion .
[ Preview API ] Updates an existing question for an extension .
: param : class : ` < Question > < azure . devops . v5_1 . gallery . models . Question > ` question : Updated question to be set for the e... | route_values = { }
if publisher_name is not None :
route_values [ 'publisherName' ] = self . _serialize . url ( 'publisher_name' , publisher_name , 'str' )
if extension_name is not None :
route_values [ 'extensionName' ] = self . _serialize . url ( 'extension_name' , extension_name , 'str' )
if question_id is n... |
def _set_ssh_server_port ( self , v , load = False ) :
"""Setter method for ssh _ server _ port , mapped from YANG variable / ssh _ sa / ssh / server / ssh _ server _ port ( uint32)
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ ssh _ server _ port is considered as a p... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = RestrictedClassType ( base_type = long , restriction_dict = { 'range' : [ '0..4294967295' ] } , int_size = 32 ) , restriction_dict = { 'range' : [ u'22' , u'1024..49151' ] } ) , is_leaf = Tru... |
def qt_message_handler ( msg_type , msg_log_context , msg_string ) :
"""Qt warning messages are intercepted by this handler .
On some operating systems , warning messages might be displayed
even if the actual message does not apply . This filter adds a
blacklist for messages that are being printed for no appa... | BLACKLIST = [ 'QMainWidget::resizeDocks: all sizes need to be larger than 0' , ]
if DEV or msg_string not in BLACKLIST :
print ( msg_string ) |
def line ( self , x = None , y = None , ** kwds ) :
"""Plot DataFrame columns as lines .
This function is useful to plot lines using DataFrame ' s values
as coordinates .
Parameters
x : int or str , optional
Columns to use for the horizontal axis .
Either the location or the label of the columns to be u... | return self ( kind = 'line' , x = x , y = y , ** kwds ) |
def parse_metrics ( self , f ) :
"""Parse the metrics . tsv file from RNA - SeQC""" | headers = None
for l in f [ 'f' ] . splitlines ( ) :
s = l . strip ( ) . split ( "\t" )
if headers is None :
headers = s
else :
s_name = s [ headers . index ( 'Sample' ) ]
data = dict ( )
for idx , h in enumerate ( headers ) :
try :
data [ h ] = fl... |
def set ( self , id , value ) :
"""根据 id 写入数据 。
: param id : 要写入的 id
: param value : 要写入的数据 , 可以是一个 ` ` dict ` ` 对象""" | session = json_dumps ( value )
self . collection . replace_one ( { "wechat_id" : id } , { "wechat_id" : id , "session" : session } , upsert = True ) |
def find_min ( a , b ) :
"""This function determines the smaller of two numbers .
Examples :
> > > find _ min ( 10 , 20)
10
> > > find _ min ( 19 , 15)
15
> > > find _ min ( - 10 , - 20)
-20
: param a : First number
: param b : Second number
: return : Returns the minimum of a and b .""" | return a if a < b else b |
def display ( method = EraseMethod . ALL_MOVE ) :
"""Clear the screen or part of the screen , and possibly moves the cursor
to the " home " position ( 1 , 1 ) . See ` method ` argument below .
Esc [ < method > J
Arguments :
method : One of these possible values :
EraseMethod . END or 0:
Clear from curso... | accepted_methods = ( '0' , '1' , '2' , '3' , '4' )
methodstr = str ( method )
if methodstr not in accepted_methods :
raise ValueError ( 'Invalid method, expected {}. Got: {!r}' . format ( ', ' . join ( accepted_methods ) , method , ) )
if methodstr == '4' :
methods = ( 2 , 3 )
else :
methods = ( method , )
... |
def nobs ( self ) :
"""get the number of observations
Returns
nobs : int
the number of observations""" | self . control_data . nobs = self . observation_data . shape [ 0 ]
return self . control_data . nobs |
def entitlement ( self , token ) :
"""Client applications can use a specific endpoint to obtain a special
security token called a requesting party token ( RPT ) . This token
consists of all the entitlements ( or permissions ) for a user as a
result of the evaluation of the permissions and authorization polici... | headers = { "Authorization" : "Bearer %s" % token }
url = self . _realm . client . get_full_url ( PATH_ENTITLEMENT . format ( self . _realm . realm_name , self . _client_id ) )
return self . _realm . client . get ( url , headers = headers ) |
def touch ( self , expiration ) :
"""Updates the current document ' s expiration value .
: param expiration : Expiration in seconds for the document to be removed by
couchbase server , defaults to 0 - will never expire .
: type expiration : int
: returns : Response from CouchbaseClient .
: rtype : unicode... | if not self . cas_value or not self . doc_id :
raise self . DoesNotExist ( self )
return self . bucket . touch ( self . doc_id , expiration ) |
def getSymmetricallyEncryptedVal ( val , secretKey : Union [ str , bytes ] = None ) -> Tuple [ str , str ] :
"""Encrypt the provided value with symmetric encryption
: param val : the value to encrypt
: param secretKey : Optional key , if provided should be either in hex or bytes
: return : Tuple of the encryp... | if isinstance ( val , str ) :
val = val . encode ( "utf-8" )
if secretKey :
if isHex ( secretKey ) :
secretKey = bytes ( bytearray . fromhex ( secretKey ) )
elif not isinstance ( secretKey , bytes ) :
error ( "Secret key must be either in hex or bytes" )
box = libnacl . secret . SecretBo... |
def revnet_range ( rhp ) :
"""Hyperparameters for tuning revnet .""" | rhp . set_float ( 'learning_rate' , 0.05 , 0.2 , scale = rhp . LOG_SCALE )
rhp . set_float ( 'weight_decay' , 1e-5 , 1e-3 , scale = rhp . LOG_SCALE )
rhp . set_discrete ( 'num_channels_init_block' , [ 64 , 128 ] )
return rhp |
def subtract ( self , years = 0 , months = 0 , weeks = 0 , days = 0 , hours = 0 , minutes = 0 , seconds = 0 , microseconds = 0 , ) :
"""Remove duration from the instance .
: param years : The number of years
: type years : int
: param months : The number of months
: type months : int
: param weeks : The n... | return self . add ( years = - years , months = - months , weeks = - weeks , days = - days , hours = - hours , minutes = - minutes , seconds = - seconds , microseconds = - microseconds , ) |
def _set_pvlan_tag ( self , v , load = False ) :
"""Setter method for pvlan _ tag , mapped from YANG variable / interface / port _ channel / switchport / private _ vlan / trunk / pvlan _ tag ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ pvlan _ tag is co... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = pvlan_tag . pvlan_tag , is_container = 'container' , presence = False , yang_name = "pvlan-tag" , rest_name = "tag" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True... |
def authorize_security_group_egress ( DryRun = None , GroupId = None , SourceSecurityGroupName = None , SourceSecurityGroupOwnerId = None , IpProtocol = None , FromPort = None , ToPort = None , CidrIp = None , IpPermissions = None ) :
"""[ EC2 - VPC only ] Adds one or more egress rules to a security group for use w... | pass |
def from_filename ( self , filename ) :
'''Build an IntentSchema from a file path
creates a new intent schema if the file does not exist , throws an error if the file
exists but cannot be loaded as a JSON''' | if os . path . exists ( filename ) :
with open ( filename ) as fp :
return IntentSchema ( json . load ( fp , object_pairs_hook = OrderedDict ) )
else :
print ( 'File does not exist' )
return IntentSchema ( ) |
async def make_request ( self , service : str , method : str , path : str , body : bytes = None , query : str = None , headers : dict = None , correlation_id : str = None , content_type : str = None , timeout : int = 30 , ** kwargs ) -> webtypes . Response :
"""Method for actually making a request
: param service... | |
def format_time ( timestamp , precision = datetime . timedelta ( seconds = 1 ) ) :
'''Formats timedelta / datetime / seconds
> > > format _ time ( ' 1 ' )
'0:00:01'
> > > format _ time ( 1.234)
'0:00:01'
> > > format _ time ( 1)
'0:00:01'
> > > format _ time ( datetime . datetime ( 2000 , 1 , 2 , 3 , ... | precision_seconds = precision . total_seconds ( )
if isinstance ( timestamp , six . string_types + six . integer_types + ( float , ) ) :
try :
castfunc = six . integer_types [ - 1 ]
timestamp = datetime . timedelta ( seconds = castfunc ( timestamp ) )
except OverflowError : # pragma : no cover
... |
def allowed_image ( self , module_id ) :
"""Given a module id , determine whether the image is allowed to be built .""" | shutit_global . shutit_global_object . yield_to_draw ( )
self . log ( "In allowed_image: " + module_id , level = logging . DEBUG )
cfg = self . cfg
if self . build [ 'ignoreimage' ] :
self . log ( "ignoreimage == true, returning true" + module_id , level = logging . DEBUG )
return True
self . log ( str ( cfg [ ... |
def send_to_websocket ( self , data ) :
"""Send ( data ) directly to the websocket .""" | data = json . dumps ( data )
self . websocket . send ( data ) |
def get_all_users ( self , nid = None ) :
"""Get a listing of data for each user in a network ` nid `
: type nid : str
: param nid : This is the ID of the network to get users
from . This is optional and only to override the existing
` network _ id ` entered when created the class
: returns : Python objec... | r = self . request ( method = "network.get_all_users" , nid = nid )
return self . _handle_error ( r , "Could not get users." ) |
def configureLogger ( logFolder , logFile ) :
'''Start the logger instance and configure it''' | # Set debug level
logLevel = 'DEBUG'
logger = logging . getLogger ( )
logger . setLevel ( logLevel )
# Format
formatter = logging . Formatter ( '%(asctime)s - %(levelname)s | %(name)s -> %(message)s' , '%Y-%m-%d %H:%M:%S' )
# Remove default handler to keep only clean one
for hdlr in logger . handlers :
logger . rem... |
def fixup_msg ( lvl , msg ) :
"""Fixup for this ERROR to a WARNING because it has a reasonable fallback .
WARNING : ROOT . TGClient . TGClient ] can ' t open display " localhost : 10.0 " , switching to batch mode . . .
In case you run from a remote ssh session , reconnect with ssh - Y""" | if "switching to batch mode..." in msg and lvl == logging . ERROR :
return logging . WARNING , msg
return lvl , msg |
def diagnostic_send ( self , diagFl1 , diagFl2 , diagFl3 , diagSh1 , diagSh2 , diagSh3 , force_mavlink1 = False ) :
'''Configurable diagnostic messages .
diagFl1 : Diagnostic float 1 ( float )
diagFl2 : Diagnostic float 2 ( float )
diagFl3 : Diagnostic float 3 ( float )
diagSh1 : Diagnostic short 1 ( int16 ... | return self . send ( self . diagnostic_encode ( diagFl1 , diagFl2 , diagFl3 , diagSh1 , diagSh2 , diagSh3 ) , force_mavlink1 = force_mavlink1 ) |
def regular_subset ( spikes , n_spikes_max = None , offset = 0 ) :
"""Prune the current selection to get at most n _ spikes _ max spikes .""" | assert spikes is not None
# Nothing to do if the selection already satisfies n _ spikes _ max .
if n_spikes_max is None or len ( spikes ) <= n_spikes_max : # pragma : no cover
return spikes
step = math . ceil ( np . clip ( 1. / n_spikes_max * len ( spikes ) , 1 , len ( spikes ) ) )
step = int ( step )
# Note : rand... |
def calls ( ctx , obj , limit ) :
"""List call / short positions of an account or an asset""" | if obj . upper ( ) == obj : # Asset
from bitshares . asset import Asset
asset = Asset ( obj , full = True )
calls = asset . get_call_orders ( limit )
t = [ [ "acount" , "debt" , "collateral" , "call price" , "ratio" ] ]
for call in calls :
t . append ( [ str ( call [ "account" ] [ "name" ] )... |
def dirsize_get ( l_filesWithoutPath , ** kwargs ) :
"""Sample callback that determines a directory size .""" | str_path = ""
for k , v in kwargs . items ( ) :
if k == 'path' :
str_path = v
d_ret = { }
l_size = [ ]
size = 0
for f in l_filesWithoutPath :
str_f = '%s/%s' % ( str_path , f )
if not os . path . islink ( str_f ) :
try :
size += os . path . getsize ( str_f )
except :
... |
def _call_numpy ( self , x ) :
"""Return ` ` self ( x ) ` ` using numpy .
Parameters
x : ` numpy . ndarray `
Input array to be transformed
Returns
out : ` numpy . ndarray `
Result of the transform""" | if self . halfcomplex :
return np . fft . irfftn ( x , axes = self . axes )
else :
if self . sign == '+' :
return np . fft . ifftn ( x , axes = self . axes )
else :
return ( np . fft . fftn ( x , axes = self . axes ) / np . prod ( np . take ( self . domain . shape , self . axes ) ) ) |
def redis_from_url ( url ) :
"""Converts a redis URL used by celery into a ` redis . Redis ` object .""" | # Makes sure that we only try to import redis when we need
# to use it
import redis
url = url or ""
parsed_url = urlparse ( url )
if parsed_url . scheme != "redis" :
return None
kwargs = { }
match = PASS_HOST_PORT . match ( parsed_url . netloc )
if match . group ( 'password' ) is not None :
kwargs [ 'password' ... |
def _compile_tag_re ( self ) :
"""Compile regex strings from device _ tag _ re option and return list of compiled regex / tag pairs""" | device_tag_list = [ ]
for regex_str , tags in iteritems ( self . _device_tag_re ) :
try :
device_tag_list . append ( [ re . compile ( regex_str , IGNORE_CASE ) , [ t . strip ( ) for t in tags . split ( ',' ) ] ] )
except TypeError :
self . log . warning ( '{} is not a valid regular expression an... |
def valid ( self , name ) :
"""Ensure a variable name is valid .
Note : Assumes variable names are ASCII , which isn ' t necessarily true in
Python 3.
Args :
name : A proposed variable name .
Returns :
A valid version of the name .""" | name = re . sub ( '[^0-9a-zA-Z_]' , '' , name )
if re . match ( '[0-9]' , name ) :
name = '_' + name
return name |
def autoconf ( self ) :
"""Implements Munin Plugin Auto - Configuration Option .
@ return : True if plugin can be auto - configured , False otherwise .""" | fpminfo = PHPfpmInfo ( self . _host , self . _port , self . _user , self . _password , self . _monpath , self . _ssl )
return fpminfo is not None |
def gen_client_id ( ) :
"""Generates random client ID
: return :""" | import random
gen_id = 'hbmqtt/'
for i in range ( 7 , 23 ) :
gen_id += chr ( random . randint ( 0 , 74 ) + 48 )
return gen_id |
def remove_module_load ( state_dict ) :
"""create new OrderedDict that does not contain ` module . `""" | new_state_dict = OrderedDict ( )
for k , v in state_dict . items ( ) :
new_state_dict [ k [ 7 : ] ] = v
return new_state_dict |
def CreateInstance ( r , mode , name , disk_template , disks , nics , ** kwargs ) :
"""Creates a new instance .
More details for parameters can be found in the RAPI documentation .
@ type mode : string
@ param mode : Instance creation mode
@ type name : string
@ param name : Hostname of the instance to cr... | if INST_CREATE_REQV1 not in r . features :
raise GanetiApiError ( "Cannot create Ganeti 2.1-style instances" )
query = { }
if kwargs . get ( "dry_run" ) :
query [ "dry-run" ] = 1
if kwargs . get ( "no_install" ) :
query [ "no-install" ] = 1
# Make a version 1 request .
body = { _REQ_DATA_VERSION_FIELD : 1 ,... |
def configure ( self , subscription_id , tenant_id , client_id = "" , client_secret = "" , environment = 'AzurePublicCloud' , mount_point = DEFAULT_MOUNT_POINT ) :
"""Configure the credentials required for the plugin to perform API calls to Azure .
These credentials will be used to query roles and create / delete... | if environment not in VALID_ENVIRONMENTS :
error_msg = 'invalid environment argument provided "{arg}", supported environments: "{environments}"'
raise exceptions . ParamValidationError ( error_msg . format ( arg = environment , environments = ',' . join ( VALID_ENVIRONMENTS ) , ) )
params = { 'subscription_id' ... |
def get_stp_mst_detail_output_msti_port_oper_bpdu_guard ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_stp_mst_detail = ET . Element ( "get_stp_mst_detail" )
config = get_stp_mst_detail
output = ET . SubElement ( get_stp_mst_detail , "output" )
msti = ET . SubElement ( output , "msti" )
instance_id_key = ET . SubElement ( msti , "instance-id" )
instance_id_key . text = kwargs . pop... |
def _get_batch_representative ( items , key ) :
"""Retrieve a representative data item from a batch .
Handles standard bcbio cases ( a single data item ) and CWL cases with
batches that have a consistent variant file .""" | if isinstance ( items , dict ) :
return items , items
else :
vals = set ( [ ] )
out = [ ]
for data in items :
if key in data :
vals . add ( data [ key ] )
out . append ( data )
if len ( vals ) != 1 :
raise ValueError ( "Incorrect values for %s: %s" % ( key , l... |
def write_can_msg ( self , channel , can_msg ) :
"""Transmits one ore more CAN messages through the specified CAN channel of the device .
: param int channel :
CAN channel , which is to be used ( : data : ` Channel . CHANNEL _ CH0 ` or : data : ` Channel . CHANNEL _ CH1 ` ) .
: param list ( CanMsg ) can _ msg... | c_can_msg = ( CanMsg * len ( can_msg ) ) ( * can_msg )
c_count = DWORD ( len ( can_msg ) )
UcanWriteCanMsgEx ( self . _handle , channel , c_can_msg , c_count )
return c_count |
def list_templates ( self , offset = 0 , count = 20 ) :
"""获取本账号内所有模板
详情请参考
https : / / open . weixin . qq . com / cgi - bin / showdocument ? action = dir _ list & id = open1500465446 _ j4CgR
: param offset : 用于分页 , 表示起始量 , 最小值为0
: type offset : int
: param count : 用于分页 , 表示拉取数量 , 最大值为20
: type count : ... | return self . _post ( 'cgi-bin/wxopen/template/list' , data = { 'offset' : offset , 'count' : count , } , result_processor = lambda x : x [ 'list' ] , ) |
def delete ( cls , ** kwargs ) :
'''If a record matching the instance id exists in the database , delete it .''' | q = cls . _get_instance ( ** kwargs )
if q :
_action_and_commit ( q , session . delete ) |
def _comm ( self , thermostat = False , kp = 0.06 , ki = 0.0075 , kd = 0.01 , heater_segments = 8 , ext_sw_heater_drive = False , update_data_event = None ) :
"""Do not call this directly - call auto _ connect ( ) , which will spawn
comm ( ) for you .
This is the main communications loop to the roaster .
when... | # since this process is started with daemon = True , it should exit
# when the owning process terminates . Therefore , safe to loop forever .
while not self . _teardown . value : # waiting for command to attempt connect
# print ( " waiting for command to attempt connect " )
while self . _attempting_connect . value ... |
def read_uint16 ( self , little_endian = True ) :
"""Read 2 byte as an unsigned integer value from the stream .
Args :
little _ endian ( bool ) : specify the endianness . ( Default ) Little endian .
Returns :
int :""" | if little_endian :
endian = "<"
else :
endian = ">"
return self . unpack ( '%sH' % endian , 2 ) |
def to_ds9 ( self , free = 'box' , fixed = 'cross' , frame = 'fk5' , color = 'green' , header = True ) :
"""Returns a list of ds9 region definitions
Parameters
free : bool
one of the supported ds9 point symbols , used for free sources , see here : http : / / ds9 . si . edu / doc / ref / region . html
fixed ... | # todo : add support for extended sources ? !
allowed_symbols = [ 'circle' , 'box' , 'diamond' , 'cross' , 'x' , 'arrow' , 'boxcircle' ]
# adding some checks .
assert free in allowed_symbols , "symbol %s not supported" % free
assert fixed in allowed_symbols , "symbol %s not supported" % fixed
lines = [ ]
if header :
... |
def get_download_url ( self , instance , default = None ) :
"""Calculate the download url""" | download = default
# calculate the download url
download = "{url}/@@download/{fieldname}/{filename}" . format ( url = api . get_url ( instance ) , fieldname = self . get_field_name ( ) , filename = self . get_filename ( instance ) , )
return download |
def do_dictsort ( value , case_sensitive = False , by = 'key' , reverse = False ) :
"""Sort a dict and yield ( key , value ) pairs . Because python dicts are
unsorted you may want to use this function to order them by either
key or value :
. . sourcecode : : jinja
{ % for item in mydict | dictsort % }
sor... | if by == 'key' :
pos = 0
elif by == 'value' :
pos = 1
else :
raise FilterArgumentError ( 'You can only sort by either "key" or "value"' )
def sort_func ( item ) :
value = item [ pos ]
if not case_sensitive :
value = ignore_case ( value )
return value
return sorted ( value . items ( ) , k... |
def getMusicAlbumList ( self , tagtype = 0 , startnum = 0 , pagingrow = 100 , dummy = 51467 ) :
"""Get music album list .
: param tagtype : ?
: return : ` ` metadata ` ` or ` ` False ` `
: metadata :
- u ' album ' : u ' Greatest Hits Coldplay ' ,
- u ' artist ' : u ' Coldplay ' ,
- u ' href ' : u ' / Co... | data = { 'tagtype' : tagtype , 'startnum' : startnum , 'pagingrow' : pagingrow , 'userid' : self . user_id , 'useridx' : self . useridx , 'dummy' : dummy , }
s , metadata = self . POST ( 'getMusicAlbumList' , data )
if s is True :
return metadata
else :
return False |
def delete ( self ) :
"""Del or Backspace pressed . Delete selection""" | with self . _qpart :
for cursor in self . cursors ( ) :
if cursor . hasSelection ( ) :
cursor . deleteChar ( ) |
def lemmatize ( self , input_text , return_raw = False , return_string = False ) :
"""Take incoming string or list of tokens . Lookup done against a
key - value list of lemmata - headword . If a string , tokenize with
` ` PunktLanguageVars ( ) ` ` . If a final period appears on a token , remove
it , then re -... | assert type ( input_text ) in [ list , str ] , logger . error ( 'Input must be a list or string.' )
if type ( input_text ) is str :
punkt = PunktLanguageVars ( )
tokens = punkt . word_tokenize ( input_text )
else :
tokens = input_text
lemmatized_tokens = [ ]
for token in tokens : # check for final period
... |
def full_split ( text , regex ) :
"""Split the text by the regex , keeping all parts .
The parts should re - join back into the original text .
> > > list ( full _ split ( ' word ' , re . compile ( ' & . * ? ' ) ) )
[ ' word ' ]""" | while text :
m = regex . search ( text )
if not m :
yield text
break
left = text [ : m . start ( ) ]
middle = text [ m . start ( ) : m . end ( ) ]
right = text [ m . end ( ) : ]
if left :
yield left
if middle :
yield middle
text = right |
def printed_out ( self , name ) :
"""Create a string representation of the action""" | opt = self . variables ( ) . optional_namestring ( )
req = self . variables ( ) . required_namestring ( )
out = ''
out += '| |\n'
out += '| |---{}({}{})\n' . format ( name , req , opt )
if self . description :
out += '| | {}\n' . format ( self . description )
return out |
def find_config_files ( self ) :
"""Find as many configuration files as should be processed for this
platform , and return a list of filenames in the order in which they
should be parsed . The filenames returned are guaranteed to exist
( modulo nasty race conditions ) .
There are three possible config files... | files = [ ]
check_environ ( )
# Where to look for the system - wide Distutils config file
sys_dir = os . path . dirname ( sys . modules [ 'distutils' ] . __file__ )
# Look for the system config file
sys_file = os . path . join ( sys_dir , "distutils.cfg" )
if os . path . isfile ( sys_file ) :
files . append ( sys_f... |
def prog ( text ) :
"""Decorator used to specify the program name for the console script
help message .
: param text : The text to use for the program name .""" | def decorator ( func ) :
adaptor = ScriptAdaptor . _get_adaptor ( func )
adaptor . prog = text
return func
return decorator |
def add_values_to_run_xml ( self , run ) :
"""This function adds the result values to the XML representation of a run .""" | runElem = run . xml
for elem in list ( runElem ) :
runElem . remove ( elem )
self . add_column_to_xml ( runElem , 'status' , run . status )
self . add_column_to_xml ( runElem , 'cputime' , run . cputime )
self . add_column_to_xml ( runElem , 'walltime' , run . walltime )
self . add_column_to_xml ( runElem , '@categ... |
def __is_video_app_launch_directive_present ( self ) : # type : ( ) - > bool
"""Checks if the video app launch directive is present or not .
: return : boolean to show if video app launch directive is
present or not .
: rtype : bool""" | if self . response . directives is None :
return False
for directive in self . response . directives :
if ( directive is not None and directive . object_type == "VideoApp.Launch" ) :
return True
return False |
def get_declared_fields ( bases , attrs ) :
"""Find all fields and return them as a dictionary .
note : : this function is copied and modified
from django . forms . get _ declared _ fields""" | def is_field ( prop ) :
return isinstance ( prop , forms . Field ) or isinstance ( prop , BaseRepresentation )
fields = [ ( field_name , attrs . pop ( field_name ) ) for field_name , obj in attrs . items ( ) if is_field ( obj ) ]
# add fields from base classes :
for base in bases [ : : - 1 ] :
if hasattr ( base... |
def _check_rename_constraints ( self , old_key , new_key ) :
"""Check the rename constraints , and return whether or not the rename
can proceed .
If the new key is already present , that is an error .
If the old key is absent , we debug log and return False , assuming it ' s
a temp table being renamed .
:... | if new_key in self . relations :
dbt . exceptions . raise_cache_inconsistent ( 'in rename, new key {} already in cache: {}' . format ( new_key , list ( self . relations . keys ( ) ) ) )
if old_key not in self . relations :
logger . debug ( 'old key {} not found in self.relations, assuming temporary' . format ( ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.