signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def buy_margin ( self ) :
"""[ float ] 买方向保证金""" | return sum ( position . buy_margin for position in six . itervalues ( self . _positions ) ) |
def get_raw_data ( self , mac , response_format = 'json' ) :
"""Get data from API as string .
Keyword arguments :
mac - - MAC address or OUI for searching
response _ format - - supported types you can see on the https : / / macaddress . io""" | data = { self . _FORMAT_F : response_format , self . _SEARCH_F : mac }
response = self . __decode_str ( self . __call_api ( self . __url , data ) , 'utf-8' )
if len ( response ) > 0 :
return response
raise EmptyResponseException ( ) |
def all_options ( self ) :
"""Returns the set of all options used in all export entries""" | items = chain . from_iterable ( hosts . values ( ) for hosts in self . data . values ( ) )
return set ( chain . from_iterable ( items ) ) |
def _add_numeric_methods_unary ( cls ) :
"""Add in numeric unary methods .""" | def _make_evaluate_unary ( op , opstr ) :
def _evaluate_numeric_unary ( self ) :
self . _validate_for_numeric_unaryop ( op , opstr )
attrs = self . _get_attributes_dict ( )
attrs = self . _maybe_update_attributes ( attrs )
return Index ( op ( self . values ) , ** attrs )
_evaluat... |
def _get_data ( self , url , accept = None ) :
"""GETs the resource at url and returns the raw response
If the accept parameter is not None , the request passes is as the Accept header""" | if self . parsed_endpoint . scheme == 'https' :
conn = httplib . HTTPSConnection ( self . parsed_endpoint . netloc )
else :
conn = httplib . HTTPConnection ( self . parsed_endpoint . netloc )
head = { "User-Agent" : USER_AGENT , API_TOKEN_HEADER_NAME : self . api_token , }
if self . api_version in [ '0.1' , '0.... |
def sendoff_current_user ( self ) :
"""Tell current user that s / he finished it ' s job for now .
We ' ll notify if workflow arrives again to his / her WF Lane .""" | msgs = self . task_data . get ( 'LANE_CHANGE_MSG' , DEFAULT_LANE_CHANGE_MSG )
self . msg_box ( title = msgs [ 'title' ] , msg = msgs [ 'body' ] ) |
def close_poll ( self , chat_id : Union [ int , str ] , message_id : id ) -> bool :
"""Use this method to close ( stop ) a poll .
Closed polls can ' t be reopened and nobody will be able to vote in it anymore .
Args :
chat _ id ( ` ` int ` ` | ` ` str ` ` ) :
Unique identifier ( int ) or username ( str ) of... | poll = self . get_messages ( chat_id , message_id ) . poll
self . send ( functions . messages . EditMessage ( peer = self . resolve_peer ( chat_id ) , id = message_id , media = types . InputMediaPoll ( poll = types . Poll ( id = poll . id , closed = True , question = "" , answers = [ ] ) ) ) )
return True |
def weight2codon ( self , weight , length = None ) :
"""Given a weight between - 5 and 5 , turn it into
a codon , eg " 000 " to " 999" """ | if length is None :
length = self . clen
retval = 0
weight = min ( max ( weight + 5.0 , 0 ) , 10.0 ) * ( 10 ** ( length - 1 ) )
for i in range ( length ) :
if i == length - 1 : # last one
d = int ( round ( weight / ( 10 ** ( length - i - 1 ) ) ) )
else :
d = int ( weight / ( 10 ** ( length -... |
def download ( sid , credentials = None , subjects_path = None , overwrite = False , release = 'HCP_1200' , database = 'hcp-openaccess' , file_list = None ) :
'''download ( sid ) downloads the data for subject with the given subject id . By default , the subject
will be placed in the first HCP subject directory i... | if s3fs is None :
raise RuntimeError ( 's3fs was not successfully loaded, so downloads may not occur; check ' 'your Python configuration to make sure that s3fs is installed. See ' 'http://s3fs.readthedocs.io/en/latest/install.html for details.' )
if credentials is None :
credentials = config [ 'hcp_credentials'... |
def run_task ( self , task_name , task_args = [ ] , task_kwargs = { } ) :
"""Run asynchronous task on a : class : ` carotte . Worker ` .
: param string task _ name : Name of task to execute
: param list task _ args : ( optional ) List of arguments to give to task
: param dict task _ kwargs : ( optional ) Dict... | data = { 'action' : 'run_task' , 'name' : task_name , 'args' : task_args , 'kwargs' : task_kwargs }
self . __send_pyobj ( data )
task = self . __recv_pyobj ( )
task . client = self
return task |
def load_default_healthchecks ( self ) :
"""Loads healthchecks specified in settings . HEALTHCHECKS as dotted import
paths to the classes . Defaults are listed in ` DEFAULT _ HEALTHCHECKS ` .""" | default_healthchecks = getattr ( settings , 'HEALTHCHECKS' , DEFAULT_HEALTHCHECKS )
for healthcheck in default_healthchecks :
healthcheck = import_string ( healthcheck )
self . register_healthcheck ( healthcheck ) |
def version_cmp ( pkg1 , pkg2 , ** kwargs ) :
'''Do a cmp - style comparison on two packages . Return - 1 if pkg1 < pkg2 , 0 if
pkg1 = = pkg2 , and 1 if pkg1 > pkg2 . Return None if there was a problem
making the comparison .
CLI Example :
. . code - block : : bash
salt ' * ' pkg . version _ cmp ' 0.2.4-0... | # ignore _ epoch is not supported here , but has to be included for API
# compatibility . Rather than putting this argument into the function
# definition ( and thus have it show up in the docs ) , we just pop it out of
# the kwargs dict and then raise an exception if any kwargs other than
# ignore _ epoch were passed ... |
def transform_timeseries4pypsa ( timeseries , timerange , column = None ) :
"""Transform pq - set timeseries to PyPSA compatible format
Parameters
timeseries : Pandas DataFrame
Containing timeseries
Returns
pypsa _ timeseries : Pandas DataFrame
Reformated pq - set timeseries""" | timeseries . index = [ str ( i ) for i in timeseries . index ]
if column is None :
pypsa_timeseries = timeseries . apply ( Series ) . transpose ( ) . set_index ( timerange )
else :
pypsa_timeseries = timeseries [ column ] . apply ( Series ) . transpose ( ) . set_index ( timerange )
return pypsa_timeseries |
def virtualchain_set_opfields ( op , ** fields ) :
"""Pass along virtualchain - reserved fields to a virtualchain operation .
This layer of indirection is meant to help with future compatibility ,
so virtualchain implementations do not try to set operation fields
directly .""" | # warn about unsupported fields
for f in fields . keys ( ) :
if f not in indexer . RESERVED_KEYS :
log . warning ( "Unsupported virtualchain field '%s'" % f )
# propagate reserved fields
for f in fields . keys ( ) :
if f in indexer . RESERVED_KEYS :
op [ f ] = fields [ f ]
return op |
def getKeywordsForText ( self , retina_name , body , ) :
"""Get a list of keywords from the text
Args :
retina _ name , str : The retina name ( required )
body , str : The text to be evaluated ( required )
Returns : Array [ str ]""" | resourcePath = '/text/keywords'
method = 'POST'
queryParams = { }
headerParams = { 'Accept' : 'Application/json' , 'Content-Type' : 'application/json' }
postData = None
queryParams [ 'retina_name' ] = retina_name
postData = body
response = self . apiClient . _callAPI ( resourcePath , method , queryParams , postData , h... |
def now_heating ( self ) :
"""Return current heating state .""" | try :
if self . side == 'left' :
heat = self . device . device_data [ 'leftNowHeating' ]
elif self . side == 'right' :
heat = self . device . device_data [ 'rightNowHeating' ]
return heat
except TypeError :
return None |
def _biotype_lookup_fn ( gtf ) :
"""return a function that will look up the biotype of a feature
this checks for either gene _ biotype or biotype being set or for the source
column to have biotype information""" | db = get_gtf_db ( gtf )
sources = set ( [ feature . source for feature in db . all_features ( ) ] )
gene_biotypes = set ( [ feature . attributes . get ( "gene_biotype" , [ None ] ) [ 0 ] for feature in db . all_features ( ) ] )
biotypes = set ( [ feature . attributes . get ( "biotype" , [ None ] ) [ 0 ] for feature in ... |
def download_magic ( infile , dir_path = '.' , input_dir_path = '' , overwrite = False , print_progress = True , data_model = 3. , separate_locs = False ) :
"""takes the name of a text file downloaded from the MagIC database and
unpacks it into magic - formatted files . by default , download _ magic assumes
tha... | if data_model == 2.5 :
method_col = "magic_method_codes"
else :
method_col = "method_codes"
input_dir_path , dir_path = pmag . fix_directories ( input_dir_path , dir_path )
infile = pmag . resolve_file_name ( infile , input_dir_path )
# try to deal reasonably with unicode errors
try :
f = codecs . open ( in... |
def parse ( html_string , wrapper = Parser , * args , ** kwargs ) :
"""Parse html with wrapper""" | return Parser ( lxml . html . fromstring ( html_string ) , * args , ** kwargs ) |
def run_project ( project_directory : str , output_directory : str = None , log_path : str = None , shared_data : dict = None , reader_path : str = None , reload_project_libraries : bool = False ) -> ExecutionResult :
"""Opens , executes and closes a Cauldron project in a single command in
production mode ( non -... | log_path = initialize_logging_path ( log_path )
logger . add_output_path ( log_path )
def on_complete ( command_response : environ . Response , project_data : SharedCache = None , message : str = None ) -> ExecutionResult :
environ . modes . remove ( environ . modes . SINGLE_RUN )
if message :
logger . ... |
def find ( self ) :
"""Call the find function""" | options = self . find_options . get_options ( )
if options is None :
return
self . stop_and_reset_thread ( ignore_results = True )
self . search_thread = SearchThread ( self )
self . search_thread . sig_finished . connect ( self . search_complete )
self . search_thread . sig_current_file . connect ( lambda x : self... |
def setup_destination ( self ) :
"""Setup output directory based on self . dst and self . identifier .
Returns the output directory name on success , raises and exception on
failure .""" | # Do we have a separate identifier ?
if ( not self . identifier ) : # No separate identifier specified , split off the last path segment
# of the source name , strip the extension to get the identifier
self . identifier = os . path . splitext ( os . path . split ( self . src ) [ 1 ] ) [ 0 ]
# Done if dryrun , else ... |
def _set_overlay_acl_in ( self , v , load = False ) :
"""Setter method for overlay _ acl _ in , mapped from YANG variable / overlay _ gateway / access _ lists / overlay _ acl _ in ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ overlay _ acl _ in is consid... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = overlay_acl_in . overlay_acl_in , is_container = 'container' , presence = False , yang_name = "overlay-acl-in" , rest_name = "overlay" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , re... |
def new_type ( cls , ** kwargs ) -> typing . Type :
"""Create a user defined type .
The new type will contain all attributes of the ` cls ` type passed in .
Any attribute ' s value can be overwritten using kwargs .
: param kwargs : Can include any attribute defined in
the provided user defined type .""" | props = dict ( cls . __dict__ )
props . update ( kwargs )
return type ( cls . __name__ , ( cls , ) , props ) |
def validate ( self , value , attribute_filter = None , minified = False ) :
""": param value :
: type value : list | None
: param attribute _ filter :
: type attribute _ filter : prestans . parser . AttributeFilter
: param minified :
: type minified : bool
: return :""" | if not self . _required and value is None :
return None
elif self . _required and value is None :
raise exception . RequiredAttributeError ( )
_validated_value = self . __class__ ( element_template = self . _element_template , min_length = self . _min_length , max_length = self . _max_length )
if not isinstance... |
def _get_ln_sf ( self , C , C_SITE , idx , n_sites , rup ) :
"""Returns the log SF term required for equation 12""" | ln_sf = np . zeros ( n_sites )
for i in range ( 1 , 5 ) :
ln_sf_i = ( C [ "lnSC1AM" ] - C_SITE [ "LnAmax1D{:g}" . format ( i ) ] )
if i > 1 :
ln_sf_i += C [ "S{:g}" . format ( i ) ]
ln_sf [ idx [ i ] ] += ln_sf_i
return ln_sf |
def remove_target ( self , target_id ) :
"""remove a target , given the id""" | updated_targets = [ ]
for target in self . my_osid_object_form . _my_map [ 'targets' ] :
if target [ 'id' ] != target_id :
updated_targets . append ( target )
self . my_osid_object_form . _my_map [ 'targets' ] = updated_targets |
def dbsize ( host = None , port = None , db = None , password = None ) :
'''Return the number of keys in the selected database
CLI Example :
. . code - block : : bash
salt ' * ' redis . dbsize''' | server = _connect ( host , port , db , password )
return server . dbsize ( ) |
def put ( self , url , params = None , headers = None , content = None , form_content = None ) : # type : ( str , Optional [ Dict [ str , str ] ] , Optional [ Dict [ str , str ] ] , Any , Optional [ Dict [ str , Any ] ] ) - > ClientRequest
"""Create a PUT request object .
: param str url : The request URL .
: p... | request = self . _request ( 'PUT' , url , params , headers , content , form_content )
return request |
def removeContour ( self , contour ) :
"""Remove ` ` contour ` ` from the glyph .
> > > glyph . removeContour ( contour )
` ` contour ` ` may be a : ref : ` BaseContour ` or an : ref : ` type - int `
representing a contour index .""" | if isinstance ( contour , int ) :
index = contour
else :
index = self . _getContourIndex ( contour )
index = normalizers . normalizeIndex ( index )
if index >= len ( self ) :
raise ValueError ( "No contour located at index %d." % index )
self . _removeContour ( index ) |
def _open_file ( self , filename ) :
"""Open a file to be tailed""" | if not self . _os_is_windows :
self . _fh = open ( filename , "rb" )
self . filename = filename
self . _fh . seek ( 0 , os . SEEK_SET )
self . oldsize = 0
return
# if we ' re in Windows , we need to use the WIN32 API to open the
# file without locking it
import win32file
import msvcrt
handle = win32... |
def info ( self ) :
"""return information about replica set""" | hosts = ',' . join ( x [ 'host' ] for x in self . members ( ) )
mongodb_uri = 'mongodb://' + hosts + '/?replicaSet=' + self . repl_id
result = { "id" : self . repl_id , "auth_key" : self . auth_key , "members" : self . members ( ) , "mongodb_uri" : mongodb_uri , "orchestration" : 'replica_sets' }
if self . login : # Ad... |
def take ( arr , indices , axis = 0 , allow_fill = False , fill_value = None ) :
"""Take elements from an array .
. . versionadded : : 0.23.0
Parameters
arr : sequence
Non array - likes ( sequences without a dtype ) are coerced
to an ndarray .
indices : sequence of integers
Indices to be taken .
axi... | from pandas . core . indexing import validate_indices
if not is_array_like ( arr ) :
arr = np . asarray ( arr )
indices = np . asarray ( indices , dtype = np . intp )
if allow_fill : # Pandas style , - 1 means NA
validate_indices ( indices , len ( arr ) )
result = take_1d ( arr , indices , axis = axis , all... |
def removeItems ( self , items ) :
"""Removes all the inputed items from the scene at once . The list of items will be stored in an internal cache . When updating a node or connection ' s prepareToRemove method , any additional items that need to be removed as a result of that object being removed , should use the ... | count = 0
self . _removalQueue = items
blocked = self . signalsBlocked ( )
self . blockSignals ( True )
update = set ( )
for item in items :
if isinstance ( item , XNodeConnection ) :
update . add ( item . inputNode ( ) )
update . add ( item . outputNode ( ) )
if self . removeItem ( item ) :
... |
def update_external_store ( self , project_name , config ) :
"""update the logstore meta info
Unsuccessful opertaion will cause an LogException .
: type config : ExternalStoreConfig
: param config : external store config
: return : UpdateExternalStoreResponse
: raise : LogException""" | headers = { "x-log-bodyrawsize" : '0' , "Content-Type" : "application/json" }
params = { }
resource = "/externalstores/" + config . externalStoreName
body_str = six . b ( json . dumps ( config . to_json ( ) ) )
( resp , header ) = self . _send ( "PUT" , project_name , body_str , resource , params , headers )
return Upd... |
def convert ( self , caffemodel_path , outmodel_path ) :
"""Convert a Caffe . caffemodel file to MXNet . params file""" | net_param = caffe_pb2 . NetParameter ( )
with open ( caffemodel_path , 'rb' ) as caffe_model_file :
net_param . ParseFromString ( caffe_model_file . read ( ) )
layers = net_param . layer
self . layers = layers
for idx , layer in enumerate ( layers ) :
layer_name = str ( layer . name )
if layer . blobs : # I... |
def sku_delete ( self , product_id , properties , session ) :
'''taobao . fenxiao . product . sku . delete 产品SKU删除接口
根据sku properties删除sku数据''' | request = TOPRequest ( 'taobao.fenxiao.product.sku.delete' )
request [ 'product_id' ] = product_id
request [ 'properties' ] = properties
self . create ( self . execute ( request , session ) , fields = [ 'result' , 'created' ] , models = { 'created' : TOPDate } )
return self |
def _pre_md5_skip_on_check ( self , src , rfile ) : # type : ( Uploader , blobxfer . models . upload . LocalPath ,
# blobxfer . models . azure . StorageEntity ) - > None
"""Perform pre MD5 skip on check
: param Uploader self : this
: param blobxfer . models . upload . LocalPath src : local path
: param blobxf... | md5 = blobxfer . models . metadata . get_md5_from_metadata ( rfile )
key = blobxfer . operations . upload . Uploader . create_unique_id ( src , rfile )
with self . _md5_meta_lock :
self . _md5_map [ key ] = ( src , rfile )
self . _md5_offload . add_localfile_for_md5_check ( key , None , str ( src . absolute_path ) ... |
def update ( self , mini_batch , num_sequences ) :
"""Performs update on model .
: param mini _ batch : Batch of experiences .
: param num _ sequences : Number of sequences to process .
: return : Results of update .""" | feed_dict = { self . model . dropout_rate : self . update_rate , self . model . batch_size : num_sequences , self . model . sequence_length : self . sequence_length }
if self . use_continuous_act :
feed_dict [ self . model . true_action ] = mini_batch [ 'actions' ] . reshape ( [ - 1 , self . brain . vector_action_s... |
def slice ( self , start = None , stop = None , step = None ) :
"""Slice substrings from each element .
Note that negative step is currently not supported .
Parameters
start : int
stop : int
step : int
Returns
Series""" | check_type ( start , int )
check_type ( stop , int )
check_type ( step , int )
if step is not None and step < 0 :
raise ValueError ( 'Only positive steps are currently supported' )
return _series_str_result ( self , weld_str_slice , start = start , stop = stop , step = step ) |
def _set_allowed_ouis ( self , v , load = False ) :
"""Setter method for allowed _ ouis , mapped from YANG variable / interface / port _ channel / switchport / port _ security / allowed _ ouis ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ allowed _ ouis is co... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "oui" , allowed_ouis . allowed_ouis , yang_name = "allowed-ouis" , rest_name = "allowed-ouis" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys = 'ou... |
def get_phi_ss_at_quantile ( phi_model , quantile ) :
"""Returns the phi _ ss values at the specified quantile as an instance of
` class ` : : openquake . hazardlib . gsim . base . CoeffsTable - applies to the
magnitude - dependent cases""" | # Setup SA coeffs - the backward compatible Python 2.7 way
coeffs = deepcopy ( phi_model . sa_coeffs )
coeffs . update ( phi_model . non_sa_coeffs )
for imt in coeffs :
if quantile is None :
coeffs [ imt ] = { "a" : phi_model [ imt ] [ "mean_a" ] , "b" : phi_model [ imt ] [ "mean_b" ] }
else :
c... |
def distribution_files ( self ) -> Iterator [ str ] :
"""Find distribution packages .""" | # This is verbatim from flake8
if self . distribution . packages :
package_dirs = self . distribution . package_dir or { }
for package in self . distribution . packages :
pkg_dir = package
if package in package_dirs :
pkg_dir = package_dirs [ package ]
elif '' in package_dirs... |
def migrateFileFields ( portal ) :
"""This function walks over all attachment types and migrates their FileField
fields .""" | portal_types = [ "Attachment" , "ARImport" , "Instrument" , "InstrumentCertification" , "Method" , "Multifile" , "Report" , "ARReport" , "SamplePoint" ]
for portal_type in portal_types : # Do the migration
migrate_to_blob ( portal , portal_type = portal_type , remove_old_value = True ) |
def get_viewable_members_serializer ( self , request ) :
"""Get a QuerySet of User objects of students in the activity . Needed for the
EighthScheduledActivitySerializer .
Returns : QuerySet""" | ids = [ ]
user = request . user
for member in self . members . all ( ) :
show = False
if member . can_view_eighth :
show = member . can_view_eighth
if not show and user and user . is_eighth_admin :
show = True
if not show and user and user . is_teacher :
show = True
if not sh... |
def get_interfaces_ip ( self ) :
"""Get interface IP details . Returns a dictionary of dictionaries .
Sample output :
" Ethernet2/3 " : {
" ipv4 " : {
"4.4.4.4 " : {
" prefix _ length " : 16
" ipv6 " : {
"2001 : db8 : : 1 " : {
" prefix _ length " : 10
" fe80 : : 2ec2:60ff : fe4f : feb2 " : {
" ... | interfaces_ip = { }
ipv4_command = "show ip interface vrf all"
ipv6_command = "show ipv6 interface vrf all"
output_v4 = self . _send_command ( ipv4_command )
output_v6 = self . _send_command ( ipv6_command )
v4_interfaces = { }
for line in output_v4 . splitlines ( ) : # Ethernet2/2 , Interface status : protocol - up / ... |
def newton ( func , x0 , fprime , args = ( ) , tol = 1.48e-8 , maxiter = 50 , disp = True ) :
"""Find a zero from the Newton - Raphson method using the jitted version of
Scipy ' s newton for scalars . Note that this does not provide an alternative
method such as secant . Thus , it is important that ` fprime ` c... | if tol <= 0 :
raise ValueError ( "tol is too small <= 0" )
if maxiter < 1 :
raise ValueError ( "maxiter must be greater than 0" )
# Convert to float ( don ' t use float ( x0 ) ; this works also for complex x0)
p0 = 1.0 * x0
funcalls = 0
status = _ECONVERR
# Newton - Raphson method
for itr in range ( maxiter ) :... |
def check_output_input ( * popenargs , ** kwargs ) :
"""Run command with arguments and return its output as a byte string .
If the exit code was non - zero it raises a CalledProcessError . The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute . ... | if 'stdout' in kwargs :
raise ValueError ( 'stdout argument not allowed, it will be overridden.' )
if 'input' in kwargs :
if 'stdin' in kwargs :
raise ValueError ( 'stdin and input arguments may not both be used.' )
inputdata = kwargs [ 'input' ]
del kwargs [ 'input' ]
kwargs [ 'stdin' ] = P... |
def stop_apppool ( name ) :
'''Stop an IIS application pool .
. . versionadded : : 2017.7.0
Args :
name ( str ) : The name of the App Pool to stop .
Returns :
bool : True if successful , otherwise False
CLI Example :
. . code - block : : bash
salt ' * ' win _ iis . stop _ apppool name = ' MyTestPool... | ps_cmd = [ 'Stop-WebAppPool' , r"'{0}'" . format ( name ) ]
cmd_ret = _srvmgr ( ps_cmd )
return cmd_ret [ 'retcode' ] == 0 |
def rmR ( kls , path ) :
"""` rm - R path ` . Deletes , but does not recurse into , symlinks .
If the path does not exist , silently return .""" | if os . path . islink ( path ) or os . path . isfile ( path ) :
os . unlink ( path )
elif os . path . isdir ( path ) :
walker = os . walk ( path , topdown = False , followlinks = False )
for dirpath , dirnames , filenames in walker :
for f in filenames :
os . unlink ( os . path . join ( ... |
def convert_to_radiance ( self , data ) :
"""Calibrate to radiance .""" | bnum = self . _header [ "block5" ] [ 'band_number' ] [ 0 ]
# Check calibration mode and select corresponding coefficients
if self . calib_mode == "UPDATE" and bnum < 7 :
gain = self . _header [ 'calibration' ] [ "cali_gain_count2rad_conversion" ] [ 0 ]
offset = self . _header [ 'calibration' ] [ "cali_offset_co... |
def flexion ( self , x , y , kwargs , diff = 0.000001 ) :
"""third derivatives ( flexion )
: param x : x - position ( preferentially arcsec )
: type x : numpy array
: param y : y - position ( preferentially arcsec )
: type y : numpy array
: param kwargs : list of keyword arguments of lens model parameters... | f_xx , f_xy , f_yx , f_yy = self . hessian ( x , y , kwargs )
f_xx_dx , f_xy_dx , f_yx_dx , f_yy_dx = self . hessian ( x + diff , y , kwargs )
f_xx_dy , f_xy_dy , f_yx_dy , f_yy_dy = self . hessian ( x , y + diff , kwargs )
f_xxx = ( f_xx_dx - f_xx ) / diff
f_xxy = ( f_xx_dy - f_xx ) / diff
f_xyy = ( f_xy_dy - f_xy ) /... |
def draw ( self , milliseconds , surface ) :
"""Render the bounds of this collision ojbect onto the specified surface .""" | super ( CollidableObj , self ) . draw ( milliseconds , surface ) |
def _handleFailedExecutor ( self , agentID , executorID = None ) :
"""Should be called when we find out an executor has failed .
Gets the log from some container ( since we are never handed a container
ID ) that ran on the given executor on the given agent , if the agent is
still up , and dumps it to our log ... | log . warning ( "Handling failure of executor '%s' on agent '%s'." , executorID , agentID )
try : # Look up the IP . We should always know it unless we get answers
# back without having accepted offers .
agentAddress = self . agentsByID [ agentID ]
# For now we assume the agent is always on the same port . We c... |
def get_free_energy ( self , temperature , pressure = 'Default' , electronic_energy = 'Default' , overbinding = True ) :
"""Returns the internal energy of an adsorbed molecule .
Parameters
temperature : numeric
temperature in K
electronic _ energy : numeric
energy in eV
pressure : numeric
pressure in ... | if not temperature or not pressure : # either None or 0
return ( 0 )
else :
if electronic_energy == 'Default' :
electronic_energy = molecule_dict [ self . name ] [ 'electronic_energy' ]
if overbinding == True :
electronic_energy += molecule_dict [ self . name ] [ 'overbinding' ]
... |
def assign_objective_requisites ( self , objective_id = None , requisite_objective_ids = None ) :
"""Creates a requirement dependency between Objective + a list of objectives .
NON - standard method impl by cjshaw
arg : objective _ id ( osid . id . Id ) : the Id of the dependent
Objective
arg : requisite _ ... | if objective_id is None or requisite_objective_ids is None :
raise NullArgument ( )
ors = ObjectiveRequisiteSession ( self . _objective_bank_id , runtime = self . _runtime )
ids_arg = { 'ids' : [ str ( i ) for i in requisite_objective_ids ] }
url_path = construct_url ( 'requisiteids' , bank_id = self . _catalog_ids... |
def load_image ( name ) :
"""Load an image""" | image = pyglet . image . load ( name ) . texture
verify_dimensions ( image )
return image |
def start ( self ) :
"""Start stream .""" | if not self . stream or self . stream . session . state == STATE_STOPPED :
self . stream = RTSPClient ( self . config . loop , self . stream_url , self . config . host , self . config . username , self . config . password , self . session_callback )
self . stream . start ( ) |
def read ( file_path ) :
"""Read a gmt file at the path specified by file _ path .
Args :
file _ path ( string ) : path to gmt file
Returns :
gmt ( GMT object ) : list of dicts , where each dict corresponds to one
line of the GMT file""" | # Read in file
actual_file_path = os . path . expanduser ( file_path )
with open ( actual_file_path , 'r' ) as f :
lines = f . readlines ( )
# Create GMT object
gmt = [ ]
# Iterate over each line
for line_num , line in enumerate ( lines ) : # Separate along tabs
fields = line . split ( '\t' )
assert len ( f... |
def getp ( self , name ) :
"""Get the named parameter .
Parameters
name : string
The parameter name .
Returns
param :
The parameter object .""" | name = self . _mapping . get ( name , name )
return self . params [ name ] |
def train ( self , jsondocs , model_dir ) :
"""Train a NER model using given documents .
Each word in the documents must have a " label " attribute , which
denote the named entities in the documents .
Parameters
jsondocs : list of JSON - style documents .
The documents used for training the CRF model .
... | modelUtil = ModelStorageUtil ( model_dir )
modelUtil . makedir ( )
modelUtil . copy_settings ( self . settings )
# Convert json documents to ner documents
nerdocs = [ json_document_to_estner_document ( jsondoc ) for jsondoc in jsondocs ]
self . fex . prepare ( nerdocs )
self . fex . process ( nerdocs )
self . trainer .... |
def send ( self , event , message ) :
"""Send a message to the backend .
: param reason : Reason of the message .
: param message : Message content .""" | self . connection . send ( { 'reason' : [ 'request' , 'send' ] , 'content' : { 'reason' : event , 'request_id' : self . request_counter , 'content' : message , } , } )
self . request_counter = self . request_counter + 1 |
def get_video_count ( self , search_q = None ) :
'''Return the number of videos in the account''' | if search_q is not None :
params = { 'q' : search_q }
else :
params = None
url = "/counts/videos"
result = self . _make_request ( self . CMS_Server , 'GET' , url , params = params )
return result [ 'count' ] |
def before_render ( self ) :
"""Before template render hook""" | # If the current user is a client contact , display those analysis
# requests that belong to same client only
super ( AnalysisRequestsView , self ) . before_render ( )
client = api . get_current_client ( )
if client :
self . contentFilter [ 'path' ] = { "query" : "/" . join ( client . getPhysicalPath ( ) ) , "level... |
def format_args ( self ) :
"""Get the arguments formatted as string .
: returns : The formatted arguments .
: rtype : str""" | result = [ ]
if self . args :
result . append ( _format_args ( self . args , self . defaults , getattr ( self , "annotations" , None ) ) )
if self . vararg :
result . append ( "*%s" % self . vararg )
if self . kwonlyargs :
if not self . vararg :
result . append ( "*" )
result . append ( _format_... |
def encr_tags ( self ) -> dict :
"""Accessor for record tags ( metadata ) stored encrypted .
: return : record tags stored encrypted""" | return { t : self . _tags [ t ] for t in self . tags or { } if not t . startswith ( '~' ) } or None |
def raw_escape ( pattern , unix = False ) :
"""Apply raw character transform before applying escape .""" | pattern = util . norm_pattern ( pattern , False , True )
return escape ( pattern , unix ) |
def available_datasets ( self ) :
"""Automatically determine datasets provided by this file""" | sensor = self . get_sensor ( self [ '/attr/sensor' ] )
nadir_resolution = self . get_nadir_resolution ( sensor )
for var_name , val in self . file_content . items ( ) :
if isinstance ( val , SDS ) :
ds_info = { 'file_type' : self . filetype_info [ 'file_type' ] , 'resolution' : nadir_resolution , }
... |
def add_child_objective ( self , objective_id , child_id ) :
"""Adds a child to an objective .
arg : objective _ id ( osid . id . Id ) : the ` ` Id ` ` of an objective
arg : child _ id ( osid . id . Id ) : the ` ` Id ` ` of the new child
raise : AlreadyExists - ` ` objective _ id ` ` is already a parent of
... | # Implemented from template for
# osid . ontology . SubjectHierarchyDesignSession . add _ child _ subject _ template
return self . _hierarchy_session . add_child ( id_ = objective_id , child_id = child_id ) |
def ip ( self ) :
'''a method to retrieve the ip of system running docker
: return : string with ip address of system''' | if self . localhost . os . sysname == 'Windows' and float ( self . localhost . os . release ) < 10 :
sys_cmd = 'docker-machine ip %s' % self . vbox
system_ip = self . command ( sys_cmd ) . replace ( '\n' , '' )
else :
system_ip = self . localhost . ip
return system_ip |
def get_dataset ( self , key , info ) :
"""Load a dataset""" | logger . debug ( 'Reading %s.' , key . name )
# Check if file _ key is specified in the yaml
file_key = info . get ( 'file_key' , key . name )
variable = self . nc [ file_key ]
l_step = self . nc . attrs . get ( 'al_subsampling_factor' , 1 )
c_step = self . nc . attrs . get ( 'ac_subsampling_factor' , 16 )
if c_step !=... |
def flatten ( attrs , inputs , proto_obj ) :
"""Flattens the input array into a 2 - D array by collapsing the higher dimensions .""" | # Mxnet does not have axis support . By default uses axis = 1
if 'axis' in attrs and attrs [ 'axis' ] != 1 :
raise RuntimeError ( "Flatten operator only supports axis=1" )
new_attrs = translation_utils . _remove_attributes ( attrs , [ 'axis' ] )
return 'Flatten' , new_attrs , inputs |
def date_to_solr ( d ) :
"""converts DD - MM - YYYY to YYYY - MM - DDT00:00:00Z""" | return "{y}-{m}-{day}T00:00:00Z" . format ( day = d [ : 2 ] , m = d [ 3 : 5 ] , y = d [ 6 : ] ) if d else d |
def serialize ( v , known_modules = [ ] ) :
'''Get a text representation of an object .''' | tname = name ( v , known_modules = known_modules )
func = serializer ( tname )
return func ( v ) , tname |
def hl_canvas2table ( self , canvas , button , data_x , data_y ) :
"""Highlight mask on table when user click on canvas .""" | self . treeview . clear_selection ( )
# Remove existing highlight
if self . maskhltag :
try :
canvas . delete_object_by_tag ( self . maskhltag , redraw = True )
except Exception :
pass
# Nothing to do if no masks are displayed
try :
obj = canvas . get_object_by_tag ( self . masktag )
except ... |
def parse_req_file ( req_file , verbatim = False ) :
"""Take a file and return a dict of ( requirement , versions , ignore ) based
on the files requirements specs .""" | req_list = [ ]
requirements = req_file . readlines ( )
for requirement in requirements :
requirement_no_comments = requirement . split ( '#' ) [ 0 ] . strip ( )
# if matching requirement line ( Thing = = 1.2.3 ) , update dict , continue
req_match = re . match ( r'\s*(?P<package>[^\s\[\]]+)(?P<extras>\[\S+\]... |
def search ( self , attr , value , tolerance = 0 ) :
"""Find paths with a key value match
Parameters
attr : str
name of the attribute
value : str or numerical value
value of the searched attribute
Keywords
tolerance : float
tolerance used when searching for matching numerical
attributes . If the v... | found_paths = [ ]
gen = self . attr_gen ( attr )
for path_attr_pair in gen : # if attribute is numerical use numerical _ value _ tolerance in
# value comparison . If attribute is string require exact match
if isinstance ( path_attr_pair . value , str ) :
type_name = 'str'
else :
type_name = path... |
def status_counter ( self ) :
"""Returns a ` Counter ` object that counts the number of task with
given status ( use the string representation of the status as key ) .""" | counter = collections . Counter ( )
for task in self :
counter [ str ( task . status ) ] += 1
return counter |
def convex_hull ( obj , qhull_options = 'QbB Pp QJn' ) :
"""Get a new Trimesh object representing the convex hull of the
current mesh , with proper normals and watertight .
Requires scipy > . 12.
Arguments
obj : Trimesh , or ( n , 3 ) float
Mesh or cartesian points
Returns
convex : Trimesh
Mesh of c... | from . base import Trimesh
if isinstance ( obj , Trimesh ) :
points = obj . vertices . view ( np . ndarray )
else : # will remove subclassing
points = np . asarray ( obj , dtype = np . float64 )
if not util . is_shape ( points , ( - 1 , 3 ) ) :
raise ValueError ( 'Object must be Trimesh or (n,3) poi... |
def sync ( self , models = None , ** context ) :
"""Syncs the database by calling its schema sync method . If
no specific schema has been set for this database , then
the global database schema will be used . If the dryRun
flag is specified , then all the resulting commands will
just be logged to the curren... | context = orb . Context ( ** context )
# collect the information for this database
conn = self . __connection
all_models = orb . system . models ( orb . Model ) . values ( )
all_models . sort ( cmp = lambda x , y : cmp ( x . schema ( ) , y . schema ( ) ) )
tables = [ model for model in all_models if issubclass ( model ... |
def crack ( mpub , priv , pathtopriv ) :
'''Input mpub is master xpub key string .
Input priv is xprv string .
Path is the path string ( e . g . ' m / 3/6/2 ' ) from the mpub to the
priv . Path cannot contain any hardened keys .''' | mpub = str ( mpub )
priv = b58d ( priv )
if int ( priv [ 18 : 26 ] , 16 ) >= 2147483648 :
raise Exception ( "Private key input is hardened. Cannot crack up a level from a hardened key." )
pathtopriv = pathtopriv . lower ( )
if 'h' in pathtopriv or "'" in pathtopriv :
raise Exception ( "Path input indicates a h... |
def AmiName ( ami_release_name , ubuntu_release_name , virtualization_type , mapr_version , role ) :
"""Returns AMI name using Cirrus ami naming convention .""" | if not role in valid_instance_roles :
raise RuntimeError ( 'Specified role (%s) not a valid role: %s' % ( role , valid_instance_roles ) )
if virtualization_type not in valid_virtualization_types :
raise RuntimeError ( 'Specified virtualization type (%s) not valid: %s' % ( virtualization_type , valid_virtualizat... |
def _expand_datasets ( test_functions ) :
"""Generator producing test _ methods , with an optional dataset .
: param test _ functions :
Iterator over tuples of test name and test unbound function .
: type test _ functions :
` iterator ` of ` tuple ` of ( ` unicode ` , ` function ` )
: return :
Generator... | for name , func in test_functions :
dataset_tuples = chain ( [ ( None , getattr ( func , 'genty_datasets' , { } ) ) ] , getattr ( func , 'genty_dataproviders' , [ ] ) , )
no_datasets = True
for dataprovider , datasets in dataset_tuples :
for dataset_name , dataset in six . iteritems ( datasets ) :
... |
def query ( self , query_dict : Dict [ str , Any ] ) -> None :
"""重写 query""" | self . parse_url . query = cast ( Any , query_dict ) |
def coerce_dt_awareness ( date_or_datetime , tz = None , t = None ) :
"""Coerce the given ` datetime ` or ` date ` object into a timezone - aware or
timezone - naive ` datetime ` result , depending on which is appropriate for
the project ' s settings .""" | if isinstance ( date_or_datetime , datetime ) :
dt = date_or_datetime
else :
dt = datetime . combine ( date_or_datetime , t or time . min )
is_project_tz_aware = settings . USE_TZ
if is_project_tz_aware :
return coerce_aware ( dt , tz )
elif not is_project_tz_aware :
return coerce_naive ( dt , tz )
# No... |
def _flow_for_request ( self ) :
"""Build a flow with the correct absolute callback URL for this request .
: return :""" | flow = copy ( self . flow )
redirect_uri = current_app . config [ 'OVERWRITE_REDIRECT_URI' ]
if not redirect_uri :
flow . redirect_uri = url_for ( '_oidc_callback' , _external = True )
else :
flow . redirect_uri = redirect_uri
return flow |
def num_spikes ( self ) :
"""Return total number of spikes .
Parameters
None
Returns
list""" | self . cursor . execute ( 'SELECT Count(*) from spikes' )
rows = self . cursor . fetchall ( ) [ 0 ]
# Check against ' wc - l * ex * . gdf '
if self . debug :
print ( 'DB has %d spikes' % rows )
return rows |
def add ( self , data_object_replica : DataObjectReplica ) :
"""Adds the given data object replica to this collection . Will raise a ` ValueError ` if a data object replica with
the same number already exists .
: param data _ object _ replica : the data object replica to add""" | if data_object_replica . number in self . _data :
raise ValueError ( "Data object replica with number %d already exists in this collection" % data_object_replica . number )
self . _data [ data_object_replica . number ] = data_object_replica |
def unregister ( self ) :
"""Unregister this system from the insights service""" | machine_id = generate_machine_id ( )
try :
logger . debug ( "Unregistering %s" , machine_id )
url = self . api_url + "/v1/systems/" + machine_id
net_logger . info ( "DELETE %s" , url )
self . session . delete ( url )
logger . info ( "Successfully unregistered from the Red Hat Insights Service" )
... |
def ToPhotlam ( self , wave , flux , ** kwargs ) :
"""Convert to ` ` photlam ` ` .
. . math : :
m = - 0.4 \\ ; ( \\ textnormal { ST } _ { \\ lambda } + 21.1)
\\ textnormal { photlam } = \\ frac { 10 ^ { m } \\ lambda } { hc }
where : math : ` h ` and : math : ` c ` are as defined in
: ref : ` pysynphot - ... | return wave / H / C * 10.0 ** ( - 0.4 * ( flux - STZERO ) ) |
def K_globe_valve_Crane ( D1 , D2 , fd = None ) :
r'''Returns the loss coefficient for all types of globe valve , ( reduced
seat or throttled ) as shown in [ 1 ] _ .
If β = 1:
. . math : :
K = K _ 1 = K _ 2 = 340 f _ d
Otherwise :
. . math : :
K _ 2 = \ frac { K + \ left [ 0.5(1 - \ beta ^ 2 ) + ( 1 -... | beta = D1 / D2
if fd is None :
fd = ft_Crane ( D2 )
K1 = 340.0 * fd
if beta == 1 :
return K1
# upstream and down
else :
return ( K1 + beta * ( 0.5 * ( 1 - beta ) ** 2 + ( 1 - beta ** 2 ) ** 2 ) ) / beta ** 4 |
def yesterday ( self , date_from = None , date_format = None ) :
"""Retourne la date d ' hier depuis maintenant ou depuis une date fournie
: param : : date _ from date de référence
: return datetime""" | # date d ' hier
return self . delta ( date_from = date_from , date_format = date_format , days = - 1 ) |
def close_curves ( * crvs , ** kw ) :
'''close _ curves ( crv1 , crv2 . . . ) yields a single curve that merges all of the given list of curves
together . The curves must be given in order , such that the i ' th curve should be connected to
to the ( i + 1 ) ' th curve circularly to form a perimeter .
The foll... | for k in six . iterkeys ( kw ) :
if k not in close_curves . default_options :
raise ValueError ( 'Unrecognized option: %s' % k )
kw = { k : ( kw [ k ] if k in kw else v ) for ( k , v ) in six . iteritems ( close_curves . default_options ) }
( grid , order ) = ( kw [ 'grid' ] , kw [ 'order' ] )
crvs = [ ( cr... |
def Add ( self , key , help = "" , default = None , validator = None , converter = None , ** kw ) :
"""Add an option .
@ param key : the name of the variable , or a list or tuple of arguments
@ param help : optional help text for the options
@ param default : optional default value
@ param validator : optio... | if SCons . Util . is_List ( key ) or isinstance ( key , tuple ) :
self . _do_add ( * key )
return
if not SCons . Util . is_String ( key ) or not SCons . Environment . is_valid_construction_var ( key ) :
raise SCons . Errors . UserError ( "Illegal Variables.Add() key `%s'" % str ( key ) )
self . _do_add ( ke... |
def combine_inputs_with_outputs ( nb_source , nb_outputs , fmt = None ) :
"""Copy outputs of the second notebook into
the first one , for cells that have matching inputs""" | output_code_cells = [ cell for cell in nb_outputs . cells if cell . cell_type == 'code' ]
output_other_cells = [ cell for cell in nb_outputs . cells if cell . cell_type != 'code' ]
fmt = long_form_one_format ( fmt )
text_repr = nb_source . metadata . get ( 'jupytext' , { } ) . get ( 'text_representation' , { } )
ext = ... |
def to_basis ( self , basis = None , start = None , stop = None , step = None , undefined = None ) :
"""Make a new curve in a new basis , given a basis , or a new start , step ,
and / or stop . You only need to set the parameters you want to change .
If the new extents go beyond the current extents , the curve ... | if basis is None :
if start is None :
new_start = self . start
else :
new_start = start
new_step = step or self . step
new_stop = stop or self . stop
# new _ adj _ stop = new _ stop + new _ step / 100 # To guarantee inclusion .
# basis = np . arange ( new _ start , new _ adj _ st... |
def plot ( self , width = 8 , height = None , plt = None , dpi = None , ** kwargs ) :
"""Plot the equation of state .
Args :
width ( float ) : Width of plot in inches . Defaults to 8in .
height ( float ) : Height of plot in inches . Defaults to width *
golden ratio .
plt ( matplotlib . pyplot ) : If plt i... | plt = pretty_plot ( width = width , height = height , plt = plt , dpi = dpi )
color = kwargs . get ( "color" , "r" )
label = kwargs . get ( "label" , "{} fit" . format ( self . __class__ . __name__ ) )
lines = [ "Equation of State: %s" % self . __class__ . __name__ , "Minimum energy = %1.2f eV" % self . e0 , "Minimum o... |
def get_predicted_class ( self , x , ** kwargs ) :
""": param x : A symbolic representation ( Tensor ) of the network input
: return : A symbolic representation ( Tensor ) of the predicted label""" | return tf . argmax ( self . get_logits ( x , ** kwargs ) , axis = 1 ) |
def showGridRows ( self ) :
"""Returns whether or not this delegate should draw rows when rendering \
the grid .
: return < bool >""" | delegate = self . itemDelegate ( )
if ( isinstance ( delegate , XTreeWidgetDelegate ) ) :
return delegate . showGridRows ( )
return None |
def types_and_weights_of_connections ( self ) :
"""Extract a dictionary summarizing the types and weights
of edges in the graph .
: return : A dictionary with keys specifying the
species involved in a connection in alphabetical order
( e . g . string ' Fe - O ' ) and values which are a list of
weights for... | def get_label ( u , v ) :
u_label = self . structure [ u ] . species_string
v_label = self . structure [ v ] . species_string
return "-" . join ( sorted ( ( u_label , v_label ) ) )
types = defaultdict ( list )
for u , v , d in self . graph . edges ( data = True ) :
label = get_label ( u , v )
types ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.