signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def learnPlaceCode ( self , runs , dir = 1 , periodic = False , recurrent = True , randomSpeed = False , learnRecurrent = False ) :
"""Traverses a sinusoidal trajectory across the environment , learning during
the process . A pair of runs across the environment ( one in each direction )
takes 10 seconds if in a... | # Simulate for a second to get nice starting activation bumps .
# Turn plotting off so as not to confuse the viewer
self . plotting = False
self . simulate ( 10 , 1 , 1 , 0 , envelope = False , inputNoise = None )
self . plotting = True
# Set up plotting
if self . plotting :
self . fig = plt . figure ( )
self .... |
def depth ( self ) -> int :
"""Depth of the citation scheme
. . example : : If we have a Book , Poem , Line system , and the citation we are looking at is Poem , depth is 1
: rtype : int
: return : Depth of the citation scheme""" | if len ( self . children ) :
return 1 + max ( [ child . depth for child in self . children ] )
else :
return 1 |
def update_rtfilters ( self ) :
"""Updates RT filters for each peer .
Should be called if a new RT Nlri ' s have changed based on the setting .
Currently only used by ` Processor ` to update the RT filters after it
has processed a RT destination . If RT filter has changed for a peer we
call RT filter change... | # Update RT filter for all peers
# TODO ( PH ) : Check if getting this map can be optimized ( if expensive )
new_peer_to_rtfilter_map = self . _compute_rtfilter_map ( )
# If we have new best path for RT NLRI , we have to update peer RT
# filters and take appropriate action of sending them NLRIs for other
# address - fa... |
def collect_nsarg_norms ( self ) :
"""Adds canonical and decanonical values to NSArgs in AST
This prepares the AST object for ( de ) canonicalization""" | start_time = datetime . datetime . now ( )
self . ast = bel_utils . populate_ast_nsarg_defaults ( self . ast , self . ast )
self . ast . collected_nsarg_norms = True
if ( hasattr ( self . ast , "bel_object" ) and self . ast . bel_object and self . ast . bel_object . type == "BELAst" ) :
self . ast . bel_object . co... |
def download_file ( url , file_name ) :
"""Helper for downloading a remote file to disk .""" | logger . info ( "Downloading URL: %s" , url )
file_size = 0
if not os . path . isfile ( file_name ) :
response = requests . get ( url , stream = True )
with open ( file_name , "wb" ) as fp :
if not response . ok :
raise Exception ( "Download exception. Will fail." )
for block in resp... |
def maxval_pos ( self ) :
"""The ` ` ( y , x ) ` ` coordinate of the maximum pixel value of the
` ` data ` ` within the source segment .
If there are multiple occurrences of the maximum value , only the
first occurence is returned .""" | if self . _is_completely_masked :
return ( np . nan , np . nan ) * u . pix
else :
yp , xp = self . maxval_cutout_pos . value
return ( yp + self . _slice [ 0 ] . start , xp + self . _slice [ 1 ] . start ) * u . pix |
def get_objective_bank_nodes ( self , objective_bank_id = None , ancestor_levels = None , descendant_levels = None , include_siblings = None ) :
"""Gets a portion of the hierarchy for the given objective bank .
arg : includeSiblings ( boolean ) : true to include the siblings
of the given node , false to omit th... | if descendant_levels :
url_path = self . _urls . nodes ( alias = objective_bank_id , depth = descendant_levels )
else :
url_path = self . _urls . nodes ( alias = objective_bank_id )
return self . _get_request ( url_path ) |
def val ( self ) :
"""The ` ` < c : val > ` ` XML for this series , as an oxml element .""" | xml = self . _val_tmpl . format ( ** { 'nsdecls' : ' %s' % nsdecls ( 'c' ) , 'values_ref' : self . _series . values_ref , 'number_format' : self . _series . number_format , 'val_count' : len ( self . _series ) , 'val_pt_xml' : self . _val_pt_xml , } )
return parse_xml ( xml ) |
def get_api_service ( self , name = None ) :
"""Returns the specific service config definition""" | try :
svc = self . services_by_name . get ( name , None )
if svc is None :
raise ValueError ( f"Couldn't find the API service configuration" )
return svc
except : # NOQA
raise Exception ( f"Failed to retrieve the API service configuration" ) |
def get_exps ( self , path = '.' ) :
"""go through all subdirectories starting at path and return the experiment
identifiers ( = directory names ) of all existing experiments . A directory
is considered an experiment if it contains a experiment . cfg file .""" | exps = [ ]
for dp , dn , fn in os . walk ( path ) :
if 'experiment.cfg' in fn :
subdirs = [ os . path . join ( dp , d ) for d in os . listdir ( dp ) if os . path . isdir ( os . path . join ( dp , d ) ) ]
if all ( map ( lambda s : self . get_exps ( s ) == [ ] , subdirs ) ) :
exps . append... |
def fft ( arr_obj , res_g = None , inplace = False , inverse = False , axes = None , plan = None , fast_math = True ) :
"""( inverse ) fourier trafo of 1-3D arrays
creates a new plan or uses the given plan
the transformed arr _ obj should be either a
- numpy array :
returns the fft as numpy array ( inplace ... | if plan is None :
plan = fft_plan ( arr_obj . shape , arr_obj . dtype , axes = axes , fast_math = fast_math )
if isinstance ( arr_obj , np . ndarray ) :
return _ocl_fft_numpy ( plan , arr_obj , inverse = inverse )
elif isinstance ( arr_obj , OCLArray ) :
if not arr_obj . dtype . type is np . complex64 :
... |
def add_error ( self , group , term , sub_term , value ) :
"""For records that are not defined as terms , either add it to the
errors list .""" | self . _errors [ ( group , term , sub_term ) ] = value |
def gen_date_by_year ( year ) :
"""获取当前年的随机时间字符串
: param :
* year : ( string ) 长度为 4 位的年份字符串
: return :
* date _ str : ( string ) 传入年份的随机合法的日期
举例如下 : :
print ( ' - - - GetRandomTime . gen _ date _ by _ year demo - - - ' )
print ( GetRandomTime . gen _ date _ by _ year ( " 2010 " ) )
print ( ' - - - ... | if isinstance ( year , int ) and len ( str ( year ) ) != 4 :
raise ValueError ( "year should be int year like 2018, but we got {}, {}" . format ( year , type ( year ) ) )
if isinstance ( year , str ) and len ( year ) != 4 :
raise ValueError ( "year should be string year like '2018', but we got {}, {}" . format ... |
def threat ( self , name , owner = None , ** kwargs ) :
"""Create the Threat TI object .
Args :
owner :
name :
* * kwargs :
Return :""" | return Threat ( self . tcex , name , owner = owner , ** kwargs ) |
def map_values ( f , D ) :
'''Map each value in the dictionary D to f ( value ) .''' | return { key : f ( val ) for key , val in D . iteritems ( ) } |
def delete ( self , table ) :
"""Deletes record in table
> > > yql . delete ( ' yql . storage ' ) . where ( [ ' name ' , ' = ' , ' store : / / YEl70PraLLMSMuYAauqNc7 ' ] )""" | self . _table = table
self . _limit = None
self . _query = "DELETE FROM {0}" . format ( self . _table )
return self |
def main ( ) :
"""Main""" | lic = ( 'License :: OSI Approved :: GNU Affero ' 'General Public License v3 or later (AGPLv3+)' )
version = load_source ( "version" , os . path . join ( "spamc" , "version.py" ) )
opts = dict ( name = "spamc" , version = version . __version__ , description = "Python spamassassin spamc client library" , long_description... |
def col_to_numeric ( df , col_name , dest = False ) :
"""Coerces a column in a DataFrame to numeric
Parameters :
df - DataFrame
DataFrame to operate on
col _ name - string
Name of column to coerce
dest - bool , default False
Whether to apply the result to the DataFrame or return it .
True is apply ,... | new_col = _pd . to_numeric ( df [ col_name ] , errors = 'coerce' )
if dest :
set_col ( df , col_name , new_col )
else :
return new_col |
def _makemask ( self , dest , res , pos ) :
"""Create a bitmask .
The value being masked is of width ` res ` .
Limb number ` pos ` of ` dest ` is being assigned to .""" | if ( res is None or dest . bitwidth < res ) and 0 < ( dest . bitwidth - 64 * pos ) < 64 :
return '&0x{:X}' . format ( ( 1 << ( dest . bitwidth % 64 ) ) - 1 )
return '' |
def setColumnType ( self , columnType ) :
"""Sets the column type for this widget to the inputed type value .
This will reset the widget to use one of the plugins for editing the
value of the column .
: param columnType | < orb . ColumnType >""" | if ( columnType == self . _columnType ) :
return False
self . _columnType = columnType
self . rebuild ( )
return True |
def get_angle_difference ( v1 , v2 ) :
"""returns angular difference in degrees between two vectors . takes in cartesian coordinates .""" | v1 = numpy . array ( v1 )
v2 = numpy . array ( v2 )
angle = numpy . arccos ( old_div ( ( numpy . dot ( v1 , v2 ) ) , ( numpy . sqrt ( math . fsum ( v1 ** 2 ) ) * numpy . sqrt ( math . fsum ( v2 ** 2 ) ) ) ) )
return math . degrees ( angle ) |
def guess_extension ( amimetype , normalize = False ) :
"""Tries to guess extension for a mimetype .
@ param amimetype : name of a mimetype
@ time amimetype : string
@ return : the extension
@ rtype : string""" | ext = _mimes . guess_extension ( amimetype )
if ext and normalize : # Normalize some common magic mis - interpreation
ext = { '.asc' : '.txt' , '.obj' : '.bin' } . get ( ext , ext )
from invenio . legacy . bibdocfile . api_normalizer import normalize_format
return normalize_format ( ext )
return ext |
def update_from_element ( self , elem ) :
"""Reset this ` Resource ` instance to represent the values in
the given XML element .""" | self . _elem = elem
for attrname in self . attributes :
try :
delattr ( self , attrname )
except AttributeError :
pass
document_url = elem . attrib . get ( 'href' )
if document_url is not None :
self . _url = document_url
return self |
def include_flags ( self , arch ) :
'''Returns a string with the include folders''' | openssl_includes = join ( self . get_build_dir ( arch . arch ) , 'include' )
return ( ' -I' + openssl_includes + ' -I' + join ( openssl_includes , 'internal' ) + ' -I' + join ( openssl_includes , 'openssl' ) ) |
def setProfiles ( self , profiles ) :
"""Sets a list of profiles to be the options for the manager .
: param profiles | [ < XViewProfile > , . . ]""" | self . blockSignals ( True )
self . _profileCombo . blockSignals ( True )
self . _profiles = profiles [ : ]
self . _profileCombo . clear ( )
self . _profileCombo . addItems ( map ( lambda x : x . name ( ) , profiles ) )
self . _profileCombo . blockSignals ( False )
self . blockSignals ( False ) |
def keys ( self ) :
"""Keys
Returns a list of the node names in the parent
Returns :
list""" | if hasattr ( self . _nodes , 'iterkeys' ) :
return self . _nodes . keys ( )
else :
return tuple ( self . _nodes . keys ( ) ) |
def request ( method , url , ** kwargs ) :
"""Wrapper for the ` requests . request ( ) ` function .
It accepts the same arguments as the original , plus an optional ` retries `
that overrides the default retry mechanism .""" | retries = kwargs . pop ( 'retries' , None )
with Session ( retries = retries ) as session :
return session . request ( method = method , url = url , ** kwargs ) |
def log ( self , metric ) :
"""Format and output metric .
Args :
metric ( dict ) : Complete metric .""" | message = self . LOGFMT . format ( ** metric )
if metric [ 'context' ] :
message += ' context: {context}' . format ( context = metric [ 'context' ] )
self . _logger . log ( self . level , message ) |
def main ( ) :
global modem
modem = bm ( port = '/dev/ttyACM0' , incomingcallback = callback )
if modem . state == modem . STATE_FAILED :
print ( 'Unable to initialize modem, exiting.' )
return
"""Print modem information .""" | resp = modem . sendcmd ( 'ATI3' )
for line in resp :
if line :
print ( line )
try :
input ( 'Wait for call, press enter to exit' )
except ( SyntaxError , EOFError , KeyboardInterrupt ) :
pass
modem . close ( ) |
def _calc_rms ( mol1 , mol2 , clabel1 , clabel2 ) :
"""Calculate the RMSD .
Args :
mol1 : The first molecule . OpenBabel OBMol or pymatgen Molecule
object
mol2 : The second molecule . OpenBabel OBMol or pymatgen Molecule
object
clabel1 : The atom indices that can reorder the first molecule to
uniform ... | obmol1 = BabelMolAdaptor ( mol1 ) . openbabel_mol
obmol2 = BabelMolAdaptor ( mol2 ) . openbabel_mol
cmol1 = ob . OBMol ( )
for i in clabel1 :
oa1 = obmol1 . GetAtom ( i )
a1 = cmol1 . NewAtom ( )
a1 . SetAtomicNum ( oa1 . GetAtomicNum ( ) )
a1 . SetVector ( oa1 . GetVector ( ) )
cmol2 = ob . OBMol ( )
f... |
def run ( self , calc_bleu = True , epoch = None , iteration = None , eval_path = None , summary = False , reference_path = None ) :
"""Runs translation on test dataset .
: param calc _ bleu : if True compares results with reference and computes
BLEU score
: param epoch : index of the current epoch
: param ... | if self . cuda :
test_bleu = torch . cuda . FloatTensor ( [ 0 ] )
break_training = torch . cuda . LongTensor ( [ 0 ] )
else :
test_bleu = torch . FloatTensor ( [ 0 ] )
break_training = torch . LongTensor ( [ 0 ] )
if eval_path is None :
eval_path = self . build_eval_path ( epoch , iteration )
detok_... |
def run_map ( self , dmap ) :
'''Execute the contents of the VM map''' | if self . _has_loop ( dmap ) :
msg = 'Uh-oh, that cloud map has a dependency loop!'
log . error ( msg )
raise SaltCloudException ( msg )
# Go through the create list and calc dependencies
for key , val in six . iteritems ( dmap [ 'create' ] ) :
log . info ( 'Calculating dependencies for %s' , key )
... |
def present ( name , auth = None , ** kwargs ) :
'''Ensure a security group rule exists
defaults : port _ range _ min = None , port _ range _ max = None , protocol = None ,
remote _ ip _ prefix = None , remote _ group _ id = None , direction = ' ingress ' ,
ethertype = ' IPv4 ' , project _ id = None
name
... | ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' }
kwargs = __utils__ [ 'args.clean_kwargs' ] ( ** kwargs )
__salt__ [ 'neutronng.setup_clouds' ] ( auth )
if 'project_name' in kwargs :
kwargs [ 'project_id' ] = kwargs [ 'project_name' ]
del kwargs [ 'project_name' ]
project = __salt__ ... |
async def ehlo ( self , from_host = None ) :
"""Sends a SMTP ' EHLO ' command . - Identifies the client and starts the
session .
If given ` ` from ` _ host ` ` is None , defaults to the client FQDN .
For further details , please check out ` RFC 5321 § 4.1.1.1 ` _ .
Args :
from _ host ( str or None ) : Nam... | if from_host is None :
from_host = self . fqdn
code , message = await self . do_cmd ( "EHLO" , from_host )
self . last_ehlo_response = ( code , message )
extns , auths = SMTP . parse_esmtp_extensions ( message )
self . esmtp_extensions = extns
self . auth_mechanisms = auths
self . supports_esmtp = True
return code ... |
def add_user_rating ( self , item_type , item_id , item_rating ) :
"""Adds the rating for the item indicated for the current user .
: param item _ type : One of : series , episode , banner .
: param item _ id : The TheTVDB id of the item .
: param item _ rating : The rating from 0 to 10.
: return :""" | raw_response = requests_util . run_request ( 'put' , self . API_BASE_URL + '/user/ratings/%s/%d/%d' % ( item_type , item_id , item_rating ) , headers = self . __get_header_with_auth ( ) )
return self . parse_raw_response ( raw_response ) |
def run ( inputs , program , outputs ) :
"""Creates temp symlink tree , runs program , and copies back outputs .
Args :
inputs : List of fake paths to real paths , which are used for symlink tree .
program : List containing real path of program and its arguments . The
execroot directory will be appended as ... | root = tempfile . mkdtemp ( )
try :
cwd = os . getcwd ( )
for fake , real in inputs :
parent = os . path . join ( root , os . path . dirname ( fake ) )
if not os . path . exists ( parent ) :
os . makedirs ( parent )
# Use symlink if possible and not on Windows , since on Wind... |
def create_shipping_address ( self , shipping_address ) :
"""Creates a shipping address on an existing account . If you are
creating an account , you can embed the shipping addresses with the
request""" | url = urljoin ( self . _url , '/shipping_addresses' )
return shipping_address . post ( url ) |
def should_do_final_get ( self ) :
"""Check whether the polling should end doing a final GET .
: param requests . Response response : latest REST call response .
: rtype : bool""" | return ( ( self . async_url or not self . resource ) and self . method in { 'PUT' , 'PATCH' } ) or ( self . lro_options [ 'final-state-via' ] == _LOCATION_FINAL_STATE and self . location_url and self . async_url and self . method == 'POST' ) |
def fit ( self , X , y = None , ** fit_params ) :
"""Fit the model
Fit all the transforms one after the other and transform the
data , then fit the transformed data using the final estimator .
Parameters
X : iterable
Training data . Must fulfill input requirements of first step of the
pipeline .
y : i... | Xt , yt , fit_params = self . _fit ( X , y , ** fit_params )
self . N_train = len ( yt )
if self . _final_estimator is not None :
fitres = self . _final_estimator . fit ( Xt , yt , ** fit_params )
if hasattr ( fitres , 'history' ) :
self . history = fitres
return self |
def calculate_heartbeats ( shb , chb ) :
"""Given a heartbeat string from the server , and a heartbeat tuple from the client ,
calculate what the actual heartbeat settings should be .
: param ( str , str ) shb : server heartbeat numbers
: param ( int , int ) chb : client heartbeat numbers
: rtype : ( int , ... | ( sx , sy ) = shb
( cx , cy ) = chb
x = 0
y = 0
if cx != 0 and sy != '0' :
x = max ( cx , int ( sy ) )
if cy != 0 and sx != '0' :
y = max ( cy , int ( sx ) )
return x , y |
def add_to_manifest ( self , manifest ) :
"""Add useful details to the manifest about this service
so that it can be used in an application .
: param manifest : An predix . admin . app . Manifest object
instance that manages reading / writing manifest config
for a cloud foundry app .""" | # Add this service to list of services
manifest . add_service ( self . service . name )
# Add environment variables
zone_id = predix . config . get_env_key ( self . use_class , 'zone_id' )
manifest . add_env_var ( zone_id , self . service . settings . data [ 'zone' ] [ 'http-header-value' ] )
uri = predix . config . ge... |
def create_fct_file ( self ) :
'''Emits examples in fct format .''' | fct_str = ''
fct_str += self . fct_rec ( self . db . target_table )
return fct_str |
def delete ( self , adjustEstimate = None , newEstimate = None , increaseBy = None ) :
"""Delete this worklog entry from its associated issue .
: param adjustEstimate : one of ` ` new ` ` , ` ` leave ` ` , ` ` manual ` ` or ` ` auto ` ` .
` ` auto ` ` is the default and adjusts the estimate automatically .
` ... | params = { }
if adjustEstimate is not None :
params [ 'adjustEstimate' ] = adjustEstimate
if newEstimate is not None :
params [ 'newEstimate' ] = newEstimate
if increaseBy is not None :
params [ 'increaseBy' ] = increaseBy
super ( Worklog , self ) . delete ( params ) |
def handle_argv ( self , prog_name , argv ) :
"""Parses command line arguments from ` ` argv ` ` and dispatches
to : meth : ` run ` .
: param prog _ name : The program name ( ` ` argv [ 0 ] ` ` ) .
: param argv : Command arguments .""" | options , args = self . parse_options ( prog_name , argv )
return self . run ( * args , ** vars ( options ) ) |
def set_env ( user , name , value = None ) :
'''Set up an environment variable in the crontab .
CLI Example :
. . code - block : : bash
salt ' * ' cron . set _ env root MAILTO user @ example . com''' | lst = list_tab ( user )
for env in lst [ 'env' ] :
if name == env [ 'name' ] :
if value != env [ 'value' ] :
rm_env ( user , name )
jret = set_env ( user , name , value )
if jret == 'new' :
return 'updated'
else :
return jret
... |
def get_word_before_cursor ( self , WORD = False ) :
"""Give the word before the cursor .
If we have whitespace before the cursor this returns an empty string .""" | if self . text_before_cursor [ - 1 : ] . isspace ( ) :
return ''
else :
return self . text_before_cursor [ self . find_start_of_previous_word ( WORD = WORD ) : ] |
def add_to_stage ( self , paths ) :
"""Stage given files
: param paths :
: return :""" | cmd = self . _command . add ( paths )
( code , stdout , stderr ) = self . _exec ( cmd )
if code :
raise errors . VCSError ( 'Can\'t add paths to VCS. Process exited with code %d and message: %s' % ( code , stderr + stdout ) ) |
def make_gettext_patterns ( ) :
"Strongly inspired from idlelib . ColorDelegator . make _ pat" | kwstr = 'msgid msgstr'
kw = r"\b" + any ( "keyword" , kwstr . split ( ) ) + r"\b"
fuzzy = any ( "builtin" , [ r"#,[^\n]*" ] )
links = any ( "normal" , [ r"#:[^\n]*" ] )
comment = any ( "comment" , [ r"#[^\n]*" ] )
number = any ( "number" , [ r"\b[+-]?[0-9]+[lL]?\b" , r"\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b" , r"\b[+-]?[0-9]+... |
def _preprocess_sqlite_view ( asql_query , library , backend , connection ) :
"""Finds view or materialized view in the asql query and converts it to create table / insert rows .
Note :
Assume virtual tables for all partitions already created .
Args :
asql _ query ( str ) : asql query
library ( ambry . Li... | new_query = None
if 'create materialized view' in asql_query . lower ( ) or 'create view' in asql_query . lower ( ) :
logger . debug ( '_preprocess_sqlite_view: materialized view found.\n asql query: {}' . format ( asql_query ) )
view = parse_view ( asql_query )
tablename = view . name . replace ( '-' , ... |
def module_refresh ( self , force_refresh = False , notify = False ) :
'''Refresh the functions and returners .''' | log . debug ( 'Refreshing modules. Notify=%s' , notify )
self . functions , self . returners , _ , self . executors = self . _load_modules ( force_refresh , notify = notify )
self . schedule . functions = self . functions
self . schedule . returners = self . returners |
def _utilized ( n , node , other_attrs , unsuppressedPrefixes ) :
'''_ utilized ( n , node , other _ attrs , unsuppressedPrefixes ) - > boolean
Return true if that nodespace is utilized within the node''' | if n . startswith ( 'xmlns:' ) :
n = n [ 6 : ]
elif n . startswith ( 'xmlns' ) :
n = n [ 5 : ]
if ( n == "" and node . prefix in [ "#default" , None ] ) or n == node . prefix or n in unsuppressedPrefixes :
return 1
for attr in other_attrs :
if n == attr . prefix :
return 1
# For exclusive need t... |
def validate ( self , schema ) :
"""Validate VDOM against given JSON Schema
Raises ValidationError if schema does not match""" | try :
validate ( instance = self . to_dict ( ) , schema = schema , cls = Draft4Validator )
except ValidationError as e :
raise ValidationError ( _validate_err_template . format ( VDOM_SCHEMA , e ) ) |
def getRecentlyUpdatedSets ( self , minutesAgo ) :
'''Gets the information of recently updated sets .
: param int minutesAgo : The amount of time ago that the set was updated .
: returns : A list of Build instances that were updated within the given time .
: rtype : list
. . warning : : An empty list will b... | params = { 'apiKey' : self . apiKey , 'minutesAgo' : minutesAgo }
url = Client . ENDPOINT . format ( 'getRecentlyUpdatedSets' )
returned = get ( url , params = params )
self . checkResponse ( returned )
# Parse them in to build objects
root = ET . fromstring ( returned . text )
return [ Build ( i , self ) for i in root... |
def _new_conn ( self ) :
"""Establish a new connection via the SOCKS proxy .""" | extra_kw = { }
if self . source_address :
extra_kw [ 'source_address' ] = self . source_address
if self . socket_options :
extra_kw [ 'socket_options' ] = self . socket_options
try :
conn = socks . create_connection ( ( self . host , self . port ) , proxy_type = self . _socks_options [ 'socks_version' ] , p... |
def _update_field ( self , natvalue ) :
"""Update this NATValue if values are different
: rtype : bool""" | updated = False
if natvalue . element and natvalue . element != self . element :
self . update ( element = natvalue . element )
self . pop ( 'ip_descriptor' , None )
updated = True
elif natvalue . ip_descriptor and self . ip_descriptor and natvalue . ip_descriptor != self . ip_descriptor :
self . update... |
def combine_dictionaries ( dicts : List [ Dict [ str , Any ] ] ) -> Dict [ str , Any ] :
"""Merge a list of dictionaries into a single dictionary .
Where there are collisions the first value in the list will be set
as this function is using ChainMap to combine the dicts .""" | return dict ( ChainMap ( * dicts ) ) |
def register_piece ( self , from_address , to_address , hash , password , min_confirmations = 6 , sync = False , ownership = True ) :
"""Register a piece
Args :
from _ address ( Tuple [ str ] ) : Federation address . All register transactions
originate from the the Federation wallet
to _ address ( str ) : A... | file_hash , file_hash_metadata = hash
path , from_address = from_address
verb = Spoolverb ( )
unsigned_tx = self . simple_spool_transaction ( from_address , [ file_hash , file_hash_metadata , to_address ] , op_return = verb . piece , min_confirmations = min_confirmations )
signed_tx = self . _t . sign_transaction ( uns... |
def _zforce ( self , R , z , phi = 0. , t = 0. , v = None ) :
"""NAME :
_ zforce
PURPOSE :
evaluate the vertical force for this potential
INPUT :
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
v = current velocity in cylindrical coordinates
OUTPUT :
the vertic... | new_hash = hashlib . md5 ( numpy . array ( [ R , phi , z , v [ 0 ] , v [ 1 ] , v [ 2 ] , t ] ) ) . hexdigest ( )
if new_hash != self . _force_hash :
self . _calc_force ( R , phi , z , v , t )
return self . _cached_force * v [ 2 ] |
def faz ( input_file , variables = None ) :
"""FAZ entry point .""" | logging . debug ( "input file:\n {0}\n" . format ( input_file ) )
tasks = parse_input_file ( input_file , variables = variables )
print ( "Found {0} tasks." . format ( len ( tasks ) ) )
graph = DependencyGraph ( tasks )
graph . show_tasks ( )
graph . execute ( ) |
async def create ( cls , fsm_context : FSMContext ) :
""": param fsm _ context :
: return :""" | proxy = cls ( fsm_context )
await proxy . load ( )
return proxy |
def size ( self ) :
"""Returns the sizes of the groups as series .
Returns :
TYPE : Description""" | if len ( self . grouping_column_types ) > 1 :
index_type = WeldStruct ( [ self . grouping_column_types ] )
# Figure out what to use for multi - key index name
# index _ name = ? ?
else :
index_type = self . grouping_column_types [ 0 ]
index_name = self . grouping_column_names [ 0 ]
return SeriesWeld... |
def _add ( self , uri , methods , handler , host = None ) :
"""Add a handler to the route list
: param uri : path to match
: param methods : sequence of accepted method names . If none are
provided , any method is allowed
: param handler : request handler function .
When executed , it should provide a res... | if host is not None :
if isinstance ( host , str ) :
uri = host + uri
self . hosts . add ( host )
else :
if not isinstance ( host , Iterable ) :
raise ValueError ( "Expected either string or Iterable of " "host strings, not {!r}" . format ( host ) )
for host_ in host ... |
def set_memcached_backend ( self , config ) :
"""Select the most suitable Memcached backend based on the config and
on what ' s installed""" | # This is the preferred backend as it is the fastest and most fully
# featured , so we use this by default
config [ 'BACKEND' ] = 'django_pylibmc.memcached.PyLibMCCache'
if is_importable ( config [ 'BACKEND' ] ) :
return
# Otherwise , binary connections can use this pure Python implementation
if config . get ( 'BIN... |
def define_operators ( cls , operators ) :
"""Bind operators to specified functions for the scope of the context :
Example
model = Model ( )
other = Model ( )
with Model . define _ operators ( { " + " : lambda self , other : " plus " } ) :
print ( model + other )
# " plus "
print ( model + other )
#... | old_ops = dict ( cls . _operators )
for op , func in operators . items ( ) :
cls . _operators [ op ] = func
yield
cls . _operators = old_ops |
def wait_for_instance ( instance ) :
"""wait for instance status to be ' running ' in which case return True , False otherwise""" | status = None
print ( "getting status for instance {} ..." . format ( instance . id ) )
while status is None :
try :
status = instance . update ( )
if status is None :
time . sleep ( 2 )
except EC2ResponseError :
time . sleep ( 2 )
print ( "waiting for instance {} ..." . form... |
def push ( self , my_dict , key , element ) :
'''Push an element onto an array that may not have been defined in
the dict''' | group_info = my_dict . setdefault ( key , [ ] )
if isinstance ( group_info , dict ) :
host_list = group_info . setdefault ( 'hosts' , [ ] )
host_list . append ( element )
else :
group_info . append ( element ) |
def generate_menu ( ) :
"""Generate ` ` menu ` ` with the rebuild link .
: return : HTML fragment
: rtype : str""" | if db is not None :
needs_rebuild = db . get ( 'site:needs_rebuild' )
else :
needs_rebuild = site . coil_needs_rebuild
if needs_rebuild not in ( u'0' , u'-1' , b'0' , b'-1' ) :
return ( '</li><li><a href="{0}"><i class="fa fa-fw ' 'fa-warning"></i> <strong>Rebuild</strong></a></li>' . format ( url_for ( 're... |
def itoint ( f , G , y0 , tspan ) :
"""Numerically integrate the Ito equation dy = f ( y , t ) dt + G ( y , t ) dW
where y is the d - dimensional state vector , f is a vector - valued function ,
G is an d x m matrix - valued function giving the noise coefficients and
dW ( t ) = ( dW _ 1 , dW _ 2 , . . . dW _ ... | # In future versions we can automatically choose here the most suitable
# Ito algorithm based on properties of the system and noise .
( d , m , f , G , y0 , tspan , __ , __ ) = _check_args ( f , G , y0 , tspan , None , None )
chosenAlgorithm = itoSRI2
return chosenAlgorithm ( f , G , y0 , tspan ) |
def getnamedargs ( * args , ** kwargs ) :
"""allows you to pass a dict and named args
so you can pass ( { ' a ' : 5 , ' b ' : 3 } , c = 8 ) and get
dict ( a = 5 , b = 3 , c = 8)""" | adict = { }
for arg in args :
if isinstance ( arg , dict ) :
adict . update ( arg )
adict . update ( kwargs )
return adict |
def taxonomy_from_node_name ( self , node_name ) :
'''return the taxonomy incorporated at a particular node , or None
if it does not encode any taxonomy
Parameters
node _ name : str
a node label .
Returns
Taxonomy as a string , or None if there is no taxonomy''' | def is_float ( s ) :
try :
float ( s )
return True
except ValueError :
return False
if node_name is None :
return None
elif is_float ( node_name ) : # no name , just a bootstrap
return None
else :
bootstrap_regex = re . compile ( r'[\d\.]+:(.*)' )
reg = bootstrap_regex . ... |
def get_jwt_data_from_app_context ( ) :
"""Fetches a dict of jwt token data from the top of the flask app ' s context""" | ctx = flask . _app_ctx_stack . top
jwt_data = getattr ( ctx , 'jwt_data' , None )
PraetorianError . require_condition ( jwt_data is not None , """
No jwt_data found in app context.
Make sure @auth_required decorator is specified *first* for route
""" , )
return jwt_data |
def capture_or_cache ( target_url , user_agent = "savepagenow (https://github.com/pastpages/savepagenow)" ) :
"""Archives the provided URL using archive . org ' s Wayback Machine , unless
the page has been recently captured .
Returns a tuple with the archive . org URL where the capture is stored ,
along with ... | try :
return capture ( target_url , user_agent = user_agent , accept_cache = False ) , True
except CachedPage :
return capture ( target_url , user_agent = user_agent , accept_cache = True ) , False |
def eager_partial_regardless ( self , fn , * a , ** kw ) :
"""Like ` eager _ partial ` , but applies if callable is not annotated .""" | if self . has_annotations ( fn ) :
return self . eager_partial ( fn , * a , ** kw )
return functools . partial ( fn , * a , ** kw ) |
def _set_sflow_profile ( self , v , load = False ) :
"""Setter method for sflow _ profile , mapped from YANG variable / sflow _ profile ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ sflow _ profile is considered as a private
method . Backends looking to pop... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "profile_name" , sflow_profile . sflow_profile , yang_name = "sflow-profile" , rest_name = "sflow-profile" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , ya... |
def poll ( self ) :
"""Wait for packets to send to the client .""" | queue_empty = self . server . get_queue_empty_exception ( )
try :
packets = [ self . queue . get ( timeout = self . server . ping_timeout ) ]
self . queue . task_done ( )
except queue_empty :
raise exceptions . QueueEmpty ( )
if packets == [ None ] :
return [ ]
while True :
try :
packets . a... |
def upload_from_fs ( fn , profile = None , label = None ) :
"""Saves image from fn with TMP prefix and returns img _ id .""" | if not os . path . isfile ( fn ) :
raise ValueError ( 'File is not exists: {}' . format ( fn ) )
if profile is None :
profile = 'default'
conf = get_profile_configs ( profile )
with open ( fn , 'rb' ) as f :
if not is_image ( f , types = conf [ 'TYPES' ] ) :
msg = ( ( 'Format of uploaded file "%(nam... |
def get_plan ( self , nodes = None ) :
"""Retrieve a plan , e . g . a list of fixtures to be loaded sorted on
dependency .
: param list nodes : list of nodes to be loaded .
: return :""" | if nodes :
plan = self . graph . resolve_nodes ( nodes )
else :
plan = self . graph . resolve_node ( )
return plan |
def solve_sparse ( self , B ) :
"""Solve linear equation of the form A X = B . Where B and X are sparse matrices .
Parameters
B : any scipy . sparse matrix
Right - hand side of the matrix equation .
Note : it will be converted to csc _ matrix via ` . tocsc ( ) ` .
Returns
X : csc _ matrix
Solution to ... | B = B . tocsc ( )
cols = list ( )
for j in xrange ( B . shape [ 1 ] ) :
col = self . solve ( B [ : , j ] )
cols . append ( csc_matrix ( col ) )
return hstack ( cols ) |
def update_universe ( id_or_symbols ) :
"""该方法用于更新现在关注的证券的集合 ( e . g . : 股票池 ) 。 PS : 会在下一个bar事件触发时候产生 ( 新的关注的股票池更新 ) 效果 。 并且update _ universe会是覆盖 ( overwrite ) 的操作而不是在已有的股票池的基础上进行增量添加 。 比如已有的股票池为 [ ' 000001 . XSHE ' , ' 000024 . XSHE ' ] 然后调用了update _ universe ( [ ' 000030 . XSHE ' ] ) 之后 , 股票池就会变成000030 . XSHE一个股... | if isinstance ( id_or_symbols , ( six . string_types , Instrument ) ) :
id_or_symbols = [ id_or_symbols ]
order_book_ids = set ( assure_order_book_id ( order_book_id ) for order_book_id in id_or_symbols )
if order_book_ids != Environment . get_instance ( ) . get_universe ( ) :
Environment . get_instance ( ) . u... |
def list ( self , source_ids = None , seniority = "all" , stage = None , date_start = "1494539999" , date_end = TIMESTAMP_NOW , filter_id = None , page = 1 , limit = 30 , sort_by = 'ranking' , filter_reference = None , order_by = None ) :
"""Retreive all profiles that match the query param .
Args :
date _ end :... | query_params = { }
query_params [ "date_end" ] = _validate_timestamp ( date_end , "date_end" )
query_params [ "date_start" ] = _validate_timestamp ( date_start , "date_start" )
if filter_id :
query_params [ "filter_id" ] = _validate_filter_id ( filter_id )
if filter_reference :
query_params [ "filter_reference"... |
def release_lock ( self , verbose = VERBOSE , raiseError = RAISE_ERROR ) :
"""Release the lock when set and close file descriptor if opened .
: Parameters :
# . verbose ( bool ) : Whether to be verbose about errors when encountered
# . raiseError ( bool ) : Whether to raise error exception when encountered
... | if not os . path . isfile ( self . __lockPath ) :
released = True
code = 0
else :
try :
with open ( self . __lockPath , 'rb' ) as fd :
lock = fd . readlines ( )
except Exception as err :
code = Exception ( "Unable to read release lock file '%s' (%s)" % ( self . __lockPath , s... |
def set_display ( self , brightness = 100 , brightness_mode = "auto" ) :
"""allows to modify display state ( change brightness )
: param int brightness : display brightness [ 0 , 100 ] ( default : 100)
: param str brightness _ mode : the brightness mode of the display
[ auto , manual ] ( default : auto )""" | assert ( brightness_mode in ( "auto" , "manual" ) )
assert ( brightness in range ( 101 ) )
log . debug ( "setting display information..." )
cmd , url = DEVICE_URLS [ "set_display" ]
json_data = { "brightness_mode" : brightness_mode , "brightness" : brightness }
return self . _exec ( cmd , url , json_data = json_data ) |
def option_in_select ( browser , select_name , option ) :
"""Returns the Element specified by @ option or None
Looks at the real < select > not the select2 widget , since that doesn ' t
create the DOM until we click on it .""" | select = find_field ( browser , 'select' , select_name )
assert select , "Cannot find a '{}' select." . format ( select_name )
try :
return select . find_element_by_xpath ( str ( './/option[normalize-space(text())=%s]' % string_literal ( option ) ) )
except NoSuchElementException :
return None |
async def status ( self , * args , ** kwargs ) :
"""Get task status
Get task status structure from ` taskId `
This method gives output : ` ` v1 / task - status - response . json # ` `
This method is ` ` stable ` `""" | return await self . _makeApiCall ( self . funcinfo [ "status" ] , * args , ** kwargs ) |
def bind_socket ( self , config ) :
""": meth : ` . WNetworkNativeTransportProto . bind _ socket ` method implementation""" | address = config [ self . __bind_socket_config . section ] [ self . __bind_socket_config . address_option ]
port = config . getint ( self . __bind_socket_config . section , self . __bind_socket_config . port_option )
return WIPV4SocketInfo ( address , port ) |
def write_named_socket ( self , socket_name , socket_info ) :
"""A multi - tenant , named alternative to ProcessManager . write _ socket ( ) .""" | self . write_metadata_by_name ( self . _name , 'socket_{}' . format ( socket_name ) , str ( socket_info ) ) |
def write ( cls , table , order = None , header = None , output = "table" , sort_keys = True , show_none = "" ) :
"""writes the information given in the table
: param table : the table of values
: param order : the order of the columns
: param header : the header for the columns
: param output : the format ... | if output == "raw" :
return table
elif table is None :
return None
elif type ( table ) in [ dict , dotdict ] :
return cls . dict ( table , order = order , header = header , output = output , sort_keys = sort_keys , show_none = show_none )
elif type ( table ) == list :
return cls . list ( table , order =... |
def objectify_uri ( relative_uri ) :
'''Converts uris from path syntax to a json - like object syntax .
In addition , url escaped characters are unescaped , but non - ascii
characters a romanized using the unidecode library .
Examples :
" / blog / 3 / comments " becomes " blog [ 3 ] . comments "
" car / e... | def path_clean ( chunk ) :
if not chunk :
return chunk
if re . match ( r'\d+$' , chunk ) :
return '[{0}]' . format ( chunk )
else :
return '.' + chunk
if six . PY2 :
byte_arr = relative_uri . encode ( 'utf-8' )
else :
byte_arr = relative_uri
unquoted = decode ( unquote ( byte... |
def save_profile_id ( self , profile : Profile ) :
"""Store ID of profile locally .
. . versionadded : : 4.0.6""" | os . makedirs ( self . dirname_pattern . format ( profile = profile . username , target = profile . username ) , exist_ok = True )
with open ( self . _get_id_filename ( profile . username ) , 'w' ) as text_file :
text_file . write ( str ( profile . userid ) + "\n" )
self . context . log ( "Stored ID {0} for pro... |
def ensure_path_exists ( dir_path ) :
"""Make sure that a path exists""" | if not os . path . exists ( dir_path ) :
os . makedirs ( dir_path )
return True
return False |
def django_admin ( request ) :
'''Adds additional information to the context :
` ` django _ admin ` ` - boolean variable indicating whether the current
page is part of the django admin or not .
` ` ADMIN _ URL ` ` - normalized version of settings . ADMIN _ URL ; starts with a slash , ends without a slash
NO... | # ensure that adminurl always starts with a ' / ' but never ends with a ' / '
if settings . ADMIN_URL . endswith ( '/' ) :
admin_url = settings . ADMIN_URL [ : - 1 ]
if not settings . ADMIN_URL . startswith ( '/' ) :
admin_url = '/' + settings . ADMIN_URL
# add ADMIN _ URL and django _ admin to context
if reque... |
def tempo_account_get_all_account_by_customer_id ( self , customer_id ) :
"""Get un - archived Accounts by customer . The Caller must have the Browse Account permission for the Account .
: param customer _ id : the Customer id .
: return :""" | url = 'rest/tempo-accounts/1/account/customer/{customerId}/' . format ( customerId = customer_id )
return self . get ( url ) |
def _func_addrs_from_prologues ( self ) :
"""Scan the entire program image for function prologues , and start code scanning at those positions
: return : A list of possible function addresses""" | # Pre - compile all regexes
regexes = list ( )
for ins_regex in self . project . arch . function_prologs :
r = re . compile ( ins_regex )
regexes . append ( r )
# EDG says : I challenge anyone bothering to read this to come up with a better
# way to handle CPU modes that affect instruction decoding .
# Since th... |
def ssh_cmdline ( self , cmd ) :
"""Get argument list for meth : ` subprocess . Popen ( ) ` to run ssh .
: param cmd :
a list of arguments to pass to ssh
: returns :
argument list to pass as the first argument to subprocess . Popen ( )
. . note : :
you must call : meth : ` connect ( ) ` at least once
... | if not isinstance ( cmd , list ) :
raise TypeError ( "cmd needs to be a list" )
if not all ( isinstance ( item , str ) for item in cmd ) :
raise TypeError ( "cmd needs to be a list of strings" )
if self . _port is None :
raise ProgrammingError ( "run connect() first" )
ssh_cmd = [ 'ssh' ]
for opt in self . ... |
def serialize_args ( self ) :
"""Returns ( args , kwargs ) to be used when deserializing this parameter .""" | args , kwargs = super ( ListParameter , self ) . serialize_args ( )
args . insert ( 0 , [ self . param_type . id , self . param_type . serialize_args ( ) ] ) |
def get_axis_value_discrete ( self , axis ) :
"""Return the axis value in discrete steps for a given axis event .
How a value translates into a discrete step depends on the source .
If the source is : attr : ` ~ libinput . constant . PointerAxisSource . WHEEL ` ,
the discrete value correspond to the number of... | if self . type != EventType . POINTER_AXIS :
raise AttributeError ( _wrong_meth . format ( self . type ) )
return self . _libinput . libinput_event_pointer_get_axis_value_discrete ( self . _handle , axis ) |
def client ( whyrun = False , localmode = False , logfile = None , ** kwargs ) :
'''Execute a chef client run and return a dict with the stderr , stdout ,
return code , and pid .
CLI Example :
. . code - block : : bash
salt ' * ' chef . client server = https : / / localhost
server
The chef server URL
... | if logfile is None :
logfile = _default_logfile ( 'chef-client' )
args = [ 'chef-client' , '--no-color' , '--once' , '--logfile "{0}"' . format ( logfile ) , '--format doc' ]
if whyrun :
args . append ( '--why-run' )
if localmode :
args . append ( '--local-mode' )
return _exec_cmd ( * args , ** kwargs ) |
def to_dp ( self ) :
"""Convert to darkplaces color format
: return :""" | text = self . text . replace ( '^' , '^^' )
return '%s%s' % ( self . color . to_dp ( ) , text ) |
def get_nc_attrs ( nc ) :
"""Gets netCDF file metadata attributes .
Arguments :
nc ( netCDF4 . Dataset ) : an open NetCDF4 Dataset to pull attributes from .
Returns :
dict : Metadata as extracted from the netCDF file .""" | meta = { 'experiment' : nc . experiment_id , 'frequency' : nc . frequency , 'institute' : nc . institute_id , 'model' : nc . model_id , 'modeling_realm' : nc . modeling_realm , 'ensemble_member' : 'r{}i{}p{}' . format ( nc . realization , nc . initialization_method , nc . physics_version ) , }
variable_name = get_var_n... |
def _get_firmware_update_xml_for_file_and_component ( self , filename , component ) :
"""Creates the dynamic xml for flashing the device firmware via iLO .
This method creates the dynamic xml for flashing the firmware , based
on the component type so passed .
: param filename : location of the raw firmware fi... | if component == 'ilo' :
cmd_name = 'UPDATE_RIB_FIRMWARE'
else : # Note ( deray ) : Not explicitly checking for all other supported
# devices ( components ) , as those checks have already happened
# in the invoking methods and may seem redundant here .
cmd_name = 'UPDATE_FIRMWARE'
fwlen = os . path . getsize ( f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.