signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def post ( self , request , bot_id , format = None ) :
"""Add a new environment variable
serializer : EnvironmentVarSerializer
responseMessages :
- code : 401
message : Not authenticated
- code : 400
message : Not valid request""" | return super ( EnvironmentVarList , self ) . post ( request , bot_id , format ) |
def add_volume ( self , hostpath , contpath , options = None ) :
'''Add a volume ( bind - mount ) to the docker run invocation''' | if options is None :
options = [ ]
self . volumes . append ( ( hostpath , contpath , options ) ) |
def stop ( self ) :
"""Stop the config change monitoring thread .""" | self . observer_thread . stop ( )
self . observer_thread . join ( )
logging . info ( "Configfile watcher plugin: Stopped" ) |
def _build_offset ( offset , kwargs , default ) :
"""Builds the offset argument for event rules .""" | if offset is None :
if not kwargs :
return default
# use the default .
else :
return _td_check ( datetime . timedelta ( ** kwargs ) )
elif kwargs :
raise ValueError ( 'Cannot pass kwargs and an offset' )
elif isinstance ( offset , datetime . timedelta ) :
return _td_check ( offse... |
def fmt_type_name ( data_type , inside_namespace = None ) :
"""Produces a TypeScript type name for the given data type .
inside _ namespace should be set to the namespace that the reference
occurs in , or None if this parameter is not relevant .""" | if is_user_defined_type ( data_type ) or is_alias ( data_type ) :
if data_type . namespace == inside_namespace :
return data_type . name
else :
return '%s.%s' % ( data_type . namespace . name , data_type . name )
else :
fmted_type = _base_type_table . get ( data_type . __class__ , 'Object' )... |
def _ask ( self , answers ) :
"""Really ask the question .
We may need to populate multiple validators with answers here .
Then ask the question and insert the default value if
appropriate . Finally call the validate function to check all
validators for this question and returning the answer .""" | if isinstance ( self . validator , list ) :
for v in self . validator :
v . answers = answers
else :
self . validator . answers = answers
while ( True ) :
q = self . question % answers
if not self . choices ( ) :
logger . warn ( 'No choices were supplied for "%s"' % q )
return No... |
def _try_to_compute_deterministic_class_id ( cls , depth = 5 ) :
"""Attempt to produce a deterministic class ID for a given class .
The goal here is for the class ID to be the same when this is run on
different worker processes . Pickling , loading , and pickling again seems to
produce more consistent results... | # Pickling , loading , and pickling again seems to produce more consistent
# results than simply pickling . This is a bit
class_id = pickle . dumps ( cls )
for _ in range ( depth ) :
new_class_id = pickle . dumps ( pickle . loads ( class_id ) )
if new_class_id == class_id : # We appear to have reached a fix poi... |
def ListOutputModules ( self ) :
"""Lists the output modules .""" | table_view = views . ViewsFactory . GetTableView ( self . _views_format_type , column_names = [ 'Name' , 'Description' ] , title = 'Output Modules' )
for name , output_class in output_manager . OutputManager . GetOutputClasses ( ) :
table_view . AddRow ( [ name , output_class . DESCRIPTION ] )
table_view . Write ( ... |
def trim_variant_sequences ( variant_sequences , min_variant_sequence_coverage ) :
"""Trim VariantSequences to desired coverage and then combine any
subsequences which get generated .""" | n_total = len ( variant_sequences )
trimmed_variant_sequences = [ variant_sequence . trim_by_coverage ( min_variant_sequence_coverage ) for variant_sequence in variant_sequences ]
collapsed_variant_sequences = collapse_substrings ( trimmed_variant_sequences )
n_after_trimming = len ( collapsed_variant_sequences )
logge... |
def routing_feature ( app ) :
"""Add routing feature
Allows to define application routes un urls . py file and use lazy views .
Additionally enables regular exceptions in route definitions""" | # enable regex routes
app . url_map . converters [ 'regex' ] = RegexConverter
urls = app . name . rsplit ( '.' , 1 ) [ 0 ] + '.urls.urls'
# important issue ahead
# see : https : / / github . com / projectshift / shift - boiler / issues / 11
try :
urls = import_string ( urls )
except ImportError as e :
err = 'Fa... |
def _set_arg_generic ( self , argid , arg , cast = str ) :
"""Sets the value of the argument with the specified id using the argument passed
in from the shell session .""" | usable , filename , append = self . _redirect_split ( arg )
if usable != "" :
self . curargs [ argid ] = cast ( usable )
if argid in self . curargs :
result = "{}: '{}'" . format ( argid . upper ( ) , self . curargs [ argid ] )
self . _redirect_output ( result , filename , append , msg . info ) |
def ideal_gas ( target , pressure = 'pore.pressure' , temperature = 'pore.temperature' ) :
r"""Uses ideal gas law to calculate the molar density of an ideal gas
Parameters
target : OpenPNM Object
The object for which these values are being calculated . This
controls the length of the calculated array , and ... | R = 8.31447
P = target [ pressure ]
T = target [ temperature ]
value = P / ( R * T )
return value |
def saccade_detection ( samplemat , Hz = 200 , threshold = 30 , acc_thresh = 2000 , min_duration = 21 , min_movement = .35 , ignore_blinks = False ) :
'''Detect saccades in a stream of gaze location samples .
Coordinates in samplemat are assumed to be in degrees .
Saccades are detect by a velocity / acceleratio... | if ignore_blinks :
velocity , acceleration = get_velocity ( samplemat , float ( Hz ) , blinks = samplemat . blinks )
else :
velocity , acceleration = get_velocity ( samplemat , float ( Hz ) )
saccades = ( velocity > threshold )
# print velocity [ samplemat . blinks [ 1 : ] ]
# print saccades [ samplemat . blink... |
def handle_args_and_set_context ( args ) :
"""Args :
args : the command line args , probably passed from main ( ) as sys . argv [ 1 : ]
Returns :
a populated EFContext object
Raises :
IOError : if service registry file can ' t be found or can ' t be opened
RuntimeError : if repo or branch isn ' t as spe... | parser = argparse . ArgumentParser ( )
parser . add_argument ( "env" , help = ", " . join ( EFConfig . ENV_LIST ) )
parser . add_argument ( "--sr" , help = "optional /path/to/service_registry_file.json" , default = None )
parser . add_argument ( "--commit" , help = "Make changes in AWS (dry run if omitted)" , action = ... |
def shutdown ( self ) :
"""Shut down the entire application .""" | if self . configWindow is not None :
if self . configWindow . promptToSave ( ) :
return
self . configWindow . hide ( )
self . notifier . hide_icon ( )
t = threading . Thread ( target = self . __completeShutdown )
t . start ( ) |
def _with_inline ( func , admin_site , metadata_class , inline_class ) :
"""Decorator for register function that adds an appropriate inline .""" | def register ( model_or_iterable , admin_class = None , ** options ) : # Call the ( bound ) function we were given .
# We have to assume it will be bound to admin _ site
func ( model_or_iterable , admin_class , ** options )
_monkey_inline ( model_or_iterable , admin_site . _registry [ model_or_iterable ] , meta... |
async def removeHook ( self , * args , ** kwargs ) :
"""Delete a hook
This endpoint will remove a hook definition .
This method is ` ` stable ` `""" | return await self . _makeApiCall ( self . funcinfo [ "removeHook" ] , * args , ** kwargs ) |
def PCO_option_dispatcher ( s ) :
"""Choose the correct PCO element .""" | option = orb ( s [ 0 ] )
cls = PCO_OPTION_CLASSES . get ( option , Raw )
return cls ( s ) |
def tokenize_arabic_words ( text ) :
"""Tokenize text into words
@ param text : the input text .
@ type text : unicode .
@ return : list of words .
@ rtype : list .""" | specific_tokens = [ ]
if not text :
return specific_tokens
else :
specific_tokens = araby . tokenize ( text )
return specific_tokens |
def impulse_noise ( x , severity = 1 ) :
"""Impulse noise corruption to images .
Args :
x : numpy array , uncorrupted image , assumed to have uint8 pixel in [ 0,255 ] .
severity : integer , severity of corruption .
Returns :
numpy array , image with uint8 pixels in [ 0,255 ] . Added impulse noise .""" | c = [ .03 , .06 , .09 , 0.17 , 0.27 ] [ severity - 1 ]
x = tfds . core . lazy_imports . skimage . util . random_noise ( np . array ( x ) / 255. , mode = 's&p' , amount = c )
x_clip = np . clip ( x , 0 , 1 ) * 255
return around_and_astype ( x_clip ) |
def insert ( self , cert_p ) :
"""Insert certificate into certificate store in memory . Note that this
does not save the certificate to disk . To do that , use zcert _ save ( )
directly on the certificate . Takes ownership of zcert _ t object .""" | return lib . zcertstore_insert ( self . _as_parameter_ , byref ( zcert_p . from_param ( cert_p ) ) ) |
def message_proxy ( self , work_dir ) :
"""drone _ data _ inboud is for data comming from drones
drone _ data _ outbound is for commands to the drones , topic must either be a drone ID or all for sending
a broadcast message to all drones""" | public_keys_dir = os . path . join ( work_dir , 'certificates' , 'public_keys' )
secret_keys_dir = os . path . join ( work_dir , 'certificates' , 'private_keys' )
# start and configure auth worker
auth = IOLoopAuthenticator ( )
auth . start ( )
auth . allow ( '127.0.0.1' )
auth . configure_curve ( domain = '*' , locati... |
def login ( self ) :
"""Login entrance .""" | username = click . prompt ( 'Please enter your email or phone number' )
password = click . prompt ( 'Please enter your password' , hide_input = True )
pattern = re . compile ( r'^0\d{2,3}\d{7,8}$|^1[34578]\d{9}$' )
if pattern . match ( username ) : # use phone number to login
url = 'https://music.163.com/weapi/logi... |
def send ( self , wifs , txouts , change_address = None , lock_time = 0 , fee = 10000 ) :
"""TODO add doc string""" | # FIXME test ! !
rawtx = self . create_tx ( txouts = txouts , lock_time = lock_time )
rawtx = self . add_inputs ( rawtx , wifs , change_address = change_address , fee = fee )
return self . publish ( rawtx ) |
def run ( self ) :
"""Run command .""" | files = self . __zipped_files_data
hashes = { }
icons = { }
# Read icons . json ( from the webfont zip download )
data = json . loads ( files [ 'icons.json' ] )
# Group icons by style , since not all icons exist for all styles :
for icon , info in data . iteritems ( ) :
for style in info [ 'styles' ] :
icon... |
def from_xmrs ( cls , xmrs , predicate_modifiers = False , ** kwargs ) :
"""Instantiate an Eds from an Xmrs ( lossy conversion ) .
Args :
xmrs ( : class : ` ~ delphin . mrs . xmrs . Xmrs ` ) : Xmrs instance to
convert from
predicate _ modifiers ( function , bool ) : function that is
called as ` func ( xmr... | eps = xmrs . eps ( )
deps = _find_basic_dependencies ( xmrs , eps )
# if requested , find additional dependencies not captured already
if predicate_modifiers is True :
func = non_argument_modifiers ( role = 'ARG1' , only_connecting = True )
addl_deps = func ( xmrs , deps )
elif predicate_modifiers is False or p... |
def _dedentlines ( lines , tabsize = 8 , skip_first_line = False ) :
"""_ dedentlines ( lines , tabsize = 8 , skip _ first _ line = False ) - > dedented lines
" lines " is a list of lines to dedent .
" tabsize " is the tab width to use for indent width calculations .
" skip _ first _ line " is a boolean indic... | DEBUG = False
if DEBUG :
print ( "dedent: dedent(..., tabsize=%d, skip_first_line=%r)" % ( tabsize , skip_first_line ) )
indents = [ ]
margin = None
for i , line in enumerate ( lines ) :
if i == 0 and skip_first_line :
continue
indent = 0
for ch in line :
if ch == ' ' :
inden... |
def run ( itf ) :
"""run approximate functions
: param itf :
: return :""" | if not itf :
return 1
# access user input
options = SplitInput ( itf )
# read input
print ( " Reading input file ..." )
molecules = csv_interface . read_csv ( os . path . abspath ( options . inputpath ) , options )
if not molecules :
print ( "\n '{f} was unable to be parsed\n" . format ( f = os . path . basenam... |
def visibility ( vis : Number , unit : str = 'm' ) -> str :
"""Format visibility details into a spoken word string""" | if not vis :
return 'Visibility unknown'
if vis . value is None or '/' in vis . repr :
ret_vis = vis . spoken
else :
ret_vis = translate . visibility ( vis , unit = unit )
if unit == 'm' :
unit = 'km'
ret_vis = ret_vis [ : ret_vis . find ( ' (' ) ] . lower ( ) . replace ( unit , '' ) . strip... |
def set_or_clear_breakpoint ( self ) :
"""Set / Clear breakpoint""" | editorstack = self . get_current_editorstack ( )
if editorstack is not None :
self . switch_to_plugin ( )
editorstack . set_or_clear_breakpoint ( ) |
def process_message ( self , message , is_started = False ) :
"""Process incomming message from turret
: param dict message : incomming message
: param bool is _ started : test started indicator""" | if not self . master :
return False
if 'status' not in message :
return False
message [ 'name' ] = message [ 'turret' ]
del message [ 'turret' ]
if not self . add ( message , is_started ) :
return self . update ( message )
return True |
def email_url_config ( cls , url , backend = None ) :
"""Parses an email URL .""" | config = { }
url = urlparse ( url ) if not isinstance ( url , cls . URL_CLASS ) else url
# Remove query strings
path = url . path [ 1 : ]
path = unquote_plus ( path . split ( '?' , 2 ) [ 0 ] )
# Update with environment configuration
config . update ( { 'EMAIL_FILE_PATH' : path , 'EMAIL_HOST_USER' : _cast_urlstr ( url .... |
def get_instance ( self , payload ) :
"""Build an instance of EventInstance
: param dict payload : Payload response from the API
: returns : twilio . rest . taskrouter . v1 . workspace . event . EventInstance
: rtype : twilio . rest . taskrouter . v1 . workspace . event . EventInstance""" | return EventInstance ( self . _version , payload , workspace_sid = self . _solution [ 'workspace_sid' ] , ) |
def import_module ( uri , name = DEFAULT_MODULE_NAME , cache = None ) : # type : ( str , str , bool ) - > module
"""Download , prepare and install a compressed tar file from S3 or provided directory as a module .
SageMaker Python SDK saves the user provided scripts as compressed tar files in S3
https : / / gith... | _warning_cache_deprecation ( cache )
_files . download_and_extract ( uri , name , _env . code_dir )
prepare ( _env . code_dir , name )
install ( _env . code_dir )
try :
module = importlib . import_module ( name )
six . moves . reload_module ( module )
return module
except Exception as e :
six . reraise ... |
def array ( shape , dtype = _np . float64 , autolock = False ) :
"""Factory method for shared memory arrays supporting all numpy dtypes .""" | assert _NP_AVAILABLE , "To use the shared array object, numpy must be available!"
if not isinstance ( dtype , _np . dtype ) :
dtype = _np . dtype ( dtype )
# Not bothering to translate the numpy dtypes to ctype types directly ,
# because they ' re only partially supported . Instead , create a byte ctypes
# array of... |
def to_dict ( self ) :
"""Returns OrderedDict whose keys are self . attrs""" | ret = OrderedDict ( )
for attrname in self . attrs :
ret [ attrname ] = self . __getattribute__ ( attrname )
return ret |
def _create_actions ( self ) :
"""Create associated actions""" | self . action_to_lower = QtWidgets . QAction ( self . editor )
self . action_to_lower . triggered . connect ( self . to_lower )
self . action_to_upper = QtWidgets . QAction ( self . editor )
self . action_to_upper . triggered . connect ( self . to_upper )
self . action_to_lower . setText ( _ ( 'Convert to lower case' )... |
def update_params_for_auth ( self , headers , querys , auth_settings ) :
"""Updates header and query params based on authentication setting .
: param headers : Header parameters dict to be updated .
: param querys : Query parameters tuple list to be updated .
: param auth _ settings : Authentication setting i... | if self . auth_token_holder . token is not None :
headers [ Configuration . AUTH_TOKEN_HEADER_NAME ] = self . auth_token_holder . token
else :
headers [ 'Authorization' ] = self . configuration . get_basic_auth_token ( ) |
def _serve_image_metadata ( self , request ) :
"""Given a tag and list of runs , serve a list of metadata for images .
Note that the images themselves are not sent ; instead , we respond with URLs
to the images . The frontend should treat these URLs as opaque and should not
try to parse information about them... | tag = request . args . get ( 'tag' )
run = request . args . get ( 'run' )
sample = int ( request . args . get ( 'sample' , 0 ) )
response = self . _image_response_for_run ( run , tag , sample )
return http_util . Respond ( request , response , 'application/json' ) |
def preprocess_example ( self , example , mode , hparams ) :
"""Runtime preprocessing , e . g . , resize example [ " frame " ] .""" | if getattr ( hparams , "preprocess_resize_frames" , None ) is not None :
example [ "frame" ] = tf . image . resize_images ( example [ "frame" ] , hparams . preprocess_resize_frames , tf . image . ResizeMethod . BILINEAR )
return example |
def value_counts ( self , dropna = False ) :
"""Return a Series containing counts of unique values .
Parameters
dropna : boolean , default True
Don ' t include counts of NaT values .
Returns
Series""" | from pandas import Series , Index
if dropna :
values = self [ ~ self . isna ( ) ] . _data
else :
values = self . _data
cls = type ( self )
result = value_counts ( values , sort = False , dropna = dropna )
index = Index ( cls ( result . index . view ( 'i8' ) , dtype = self . dtype ) , name = result . index . nam... |
def start_monitor ( redis_address , stdout_file = None , stderr_file = None , autoscaling_config = None , redis_password = None ) :
"""Run a process to monitor the other processes .
Args :
redis _ address ( str ) : The address that the Redis server is listening on .
stdout _ file : A file handle opened for wr... | monitor_path = os . path . join ( os . path . dirname ( os . path . abspath ( __file__ ) ) , "monitor.py" )
command = [ sys . executable , "-u" , monitor_path , "--redis-address=" + str ( redis_address ) ]
if autoscaling_config :
command . append ( "--autoscaling-config=" + str ( autoscaling_config ) )
if redis_pas... |
def from_datetime ( self , dt ) :
"""generates a UUID for a given datetime
: param dt : datetime
: type dt : datetime
: return :""" | global _last_timestamp
epoch = datetime ( 1970 , 1 , 1 , tzinfo = dt . tzinfo )
offset = epoch . tzinfo . utcoffset ( epoch ) . total_seconds ( ) if epoch . tzinfo else 0
timestamp = ( dt - epoch ) . total_seconds ( ) - offset
node = None
clock_seq = None
nanoseconds = int ( timestamp * 1e9 )
timestamp = int ( nanoseco... |
def country_choices ( first = None , default_country_first = True ) :
"""Return a list of ( code , countries ) , alphabetically sorted on localized
country name .
: param first : Country code to be placed at the top
: param default _ country _ first :
: type default _ country _ first : bool""" | locale = _get_locale ( )
territories = [ ( code , name ) for code , name in locale . territories . items ( ) if len ( code ) == 2 ]
# skip 3 - digit regions
if first is None and default_country_first :
first = default_country ( )
def sortkey ( item ) :
if first is not None and item [ 0 ] == first :
retu... |
def _add_comparison_methods ( cls ) :
"""Add in comparison methods .""" | cls . __eq__ = _make_comparison_op ( operator . eq , cls )
cls . __ne__ = _make_comparison_op ( operator . ne , cls )
cls . __lt__ = _make_comparison_op ( operator . lt , cls )
cls . __gt__ = _make_comparison_op ( operator . gt , cls )
cls . __le__ = _make_comparison_op ( operator . le , cls )
cls . __ge__ = _make_comp... |
def run ( self ) :
"""For each file in noseOfYeti / specs , output nodes to represent each spec file""" | tokens = [ ]
section = nodes . section ( )
section [ 'ids' ] . append ( "available-tasks" )
title = nodes . title ( )
title += nodes . Text ( "Default tasks" )
section += title
task_finder = TaskFinder ( Collector ( ) )
for name , task in sorted ( task_finder . default_tasks ( ) . items ( ) , key = lambda x : len ( x [... |
def transplant_node ( self , node ) :
"""Transplant a node from another document to become a child of this node ,
removing it from the source document . The node to be transplanted can
be a : class : ` Node ` based on the same underlying XML library
implementation and adapter , or a " raw " node from that imp... | if isinstance ( node , xml4h . nodes . Node ) :
child_impl_node = node . impl_node
original_parent_impl_node = node . parent . impl_node
else :
child_impl_node = node
# Assume it ' s a valid impl node
original_parent_impl_node = self . adapter . get_node_parent ( node )
self . adapter . import_node ... |
def paragraph ( paratext , style = 'BodyText' , breakbefore = False , jc = 'left' ) :
"""Return a new paragraph element containing * paratext * . The paragraph ' s
default style is ' Body Text ' , but a new style may be set using the
* style * parameter .
@ param string jc : Paragraph alignment , possible val... | # Make our elements
paragraph = makeelement ( 'p' )
if not isinstance ( paratext , list ) :
paratext = [ ( paratext , '' ) ]
text_tuples = [ ]
for pt in paratext :
text , char_styles_str = ( pt if isinstance ( pt , ( list , tuple ) ) else ( pt , '' ) )
text_elm = makeelement ( 't' , tagtext = text )
if ... |
def create_repo ( self , name , description = github . GithubObject . NotSet , homepage = github . GithubObject . NotSet , private = github . GithubObject . NotSet , has_issues = github . GithubObject . NotSet , has_wiki = github . GithubObject . NotSet , has_downloads = github . GithubObject . NotSet , has_projects = ... | assert isinstance ( name , ( str , unicode ) ) , name
assert description is github . GithubObject . NotSet or isinstance ( description , ( str , unicode ) ) , description
assert homepage is github . GithubObject . NotSet or isinstance ( homepage , ( str , unicode ) ) , homepage
assert private is github . GithubObject .... |
def index_open ( index , allow_no_indices = True , expand_wildcards = 'closed' , ignore_unavailable = True , hosts = None , profile = None ) :
'''. . versionadded : : 2017.7.0
Open specified index .
index
Index to be opened
allow _ no _ indices
Whether to ignore if a wildcard indices expression resolves i... | es = _get_instance ( hosts , profile )
try :
result = es . indices . open ( index = index , allow_no_indices = allow_no_indices , expand_wildcards = expand_wildcards , ignore_unavailable = ignore_unavailable )
return result . get ( 'acknowledged' , False )
except elasticsearch . TransportError as e :
raise ... |
def Parse ( self , stat , file_object , knowledge_base ) :
"""Parse the History file .""" | _ , _ = stat , knowledge_base
# TODO ( user ) : Convert this to use the far more intelligent plaso parser .
ff = Firefox3History ( file_object )
for timestamp , unused_entry_type , url , title in ff . Parse ( ) :
yield rdf_webhistory . BrowserHistoryItem ( url = url , domain = urlparse . urlparse ( url ) . netloc ,... |
def retrieve_and_parse_profile ( handle ) :
"""Retrieve the remote user and return a Profile object .
: arg handle : User handle in username @ domain . tld format
: returns : ` ` federation . entities . Profile ` ` instance or None""" | hcard = retrieve_diaspora_hcard ( handle )
if not hcard :
return None
profile = parse_profile_from_hcard ( hcard , handle )
try :
profile . validate ( )
except ValueError as ex :
logger . warning ( "retrieve_and_parse_profile - found profile %s but it didn't validate: %s" , profile , ex )
return None
re... |
def get_status ( self ) :
"""[ NOT IMPLEMENTED ]""" | if self . _value == 'loaded' :
status = 'loaded'
elif not _is_server and self . _bundle is not None and self . _server_status is not None :
if not _can_requests :
raise ImportError ( "requests module required for external jobs" )
if self . _value in [ 'complete' ] : # then we have no need to bother ... |
def run ( self ) :
"""Esegue il montaggio delle varie condivisioni chiedendo all ' utente
username e password di dominio .""" | logging . info ( 'start run with "{}" at {}' . format ( self . username , datetime . datetime . now ( ) ) )
progress = Progress ( text = "Controllo requisiti software..." , pulsate = True , auto_close = True )
progress ( 1 )
try :
self . requirements ( )
except LockFailedException as lfe :
ErrorMessage ( 'Error... |
def main ( ) :
"""Main function for SPEAD sender module .""" | # Check command line arguments .
if len ( sys . argv ) != 2 :
raise RuntimeError ( 'Usage: python3 async_send.py <json config>' )
# Set up logging .
sip_logging . init_logger ( show_thread = False )
# Load SPEAD configuration from JSON file .
# _ path = os . path . dirname ( os . path . abspath ( _ _ file _ _ ) )
#... |
def _validate_arguments ( self ) :
"""method to sanitize model parameters
Parameters
None
Returns
None""" | # dtype
if self . dtype not in [ 'numerical' , 'categorical' ] :
raise ValueError ( "dtype must be in ['numerical','categorical'], " "but found dtype = {}" . format ( self . dtype ) )
# fit _ linear XOR fit _ splines
if self . fit_linear == self . fit_splines :
raise ValueError ( 'term must have fit_linear XOR ... |
def wm_msg ( self , module_name , command ) :
"""Execute the message with i3 - msg or swaymsg and log its output .""" | wm_msg = self . config [ "wm" ] [ "msg" ]
pipe = Popen ( [ wm_msg , command ] , stdout = PIPE )
self . py3_wrapper . log ( '{} module="{}" command="{}" stdout={}' . format ( wm_msg , module_name , command , pipe . stdout . read ( ) ) ) |
def filename ( self ) :
"""Return the filename of the BFD file being processed .""" | if not self . _ptr :
raise BfdException ( "BFD not initialized" )
return _bfd . get_bfd_attribute ( self . _ptr , BfdAttributes . FILENAME ) |
def send ( self , message_id , args = [ ] , kwargs = { } ) :
"""Send a message to this state machine .
To send a message to a state machine by its name , use
` stmpy . Driver . send ` instead .""" | self . _logger . debug ( 'Send {} in stm {}' . format ( message_id , self . id ) )
self . _driver . _add_event ( event_id = message_id , args = args , kwargs = kwargs , stm = self ) |
def record_deployed_values ( deployed_values , filename ) : # type : ( Dict [ str , Any ] , str ) - > None
"""Record deployed values to a JSON file .
This allows subsequent deploys to lookup previously deployed values .""" | final_values = { }
# type : Dict [ str , Any ]
if os . path . isfile ( filename ) :
with open ( filename , 'r' ) as f :
final_values = json . load ( f )
final_values . update ( deployed_values )
with open ( filename , 'wb' ) as f :
data = serialize_to_json ( final_values )
f . write ( data . encode ... |
def count_passed_edge_filter ( graph : BELGraph , edge_predicates : EdgePredicates ) -> int :
"""Return the number of edges passing a given set of predicates .""" | return sum ( 1 for _ in filter_edges ( graph , edge_predicates = edge_predicates ) ) |
def get_ports_by_name ( device_name ) :
'''Returns all serial devices with a given name''' | filtered_devices = filter ( lambda device : device_name in device [ 1 ] , list_ports . comports ( ) )
device_ports = [ device [ 0 ] for device in filtered_devices ]
return device_ports |
def reloader_thread ( softexit = False ) :
"""If ` ` soft _ exit ` ` is True , we use sys . exit ( ) ; otherwise ` ` os _ exit ` `
will be used to end the process .""" | while RUN_RELOADER :
if code_changed ( ) : # force reload
if softexit :
sys . exit ( 3 )
else :
os . _exit ( 3 )
time . sleep ( 1 ) |
def get_session ( self , notebook_dir = None , no_browser = True , ** kwargs ) :
'''Return handle to IPython session for specified notebook directory .
If an IPython notebook session has already been launched for the
notebook directory , reuse it . Otherwise , launch a new IPython notebook
session .
By defa... | if notebook_dir in self . sessions and self . sessions [ notebook_dir ] . is_alive ( ) : # Notebook process is already running for notebook directory ,
session = self . sessions [ notebook_dir ]
if 'daemon' in kwargs : # Override ` daemon ` setting of existing session .
session . daemon = kwargs [ 'daem... |
def next ( self ) :
"""( internal ) returns the next result from the ` ` itertools . tee ` ` object for
the wrapped ` ` Piper ` ` instance or re - raises an ` ` Exception ` ` .""" | # do not acquire lock if NuMap is not finished .
if self . finished :
raise StopIteration
# get per - tee lock
self . piper . tee_locks [ self . i ] . acquire ( )
# get result or exception
exception = True
try :
result = self . piper . tees [ self . i ] . next ( )
exception = False
except StopIteration , re... |
def build_sort ( self , ** kwargs ) :
'''Break url parameters and turn into sort arguments''' | sort = [ ]
order = kwargs . get ( 'order_by' , None )
if order :
if type ( order ) is list :
order = order [ 0 ]
if order [ : 1 ] == '-' :
sort . append ( ( order [ 1 : ] , - 1 ) )
else :
sort . append ( ( order , 1 ) )
return sort |
def click_partial_link_text ( self , partial_link_text , timeout = settings . SMALL_TIMEOUT ) :
"""This method clicks the partial link text on a page .""" | # If using phantomjs , might need to extract and open the link directly
if self . timeout_multiplier and timeout == settings . SMALL_TIMEOUT :
timeout = self . __get_new_timeout ( timeout )
if self . browser == 'phantomjs' :
if self . is_partial_link_text_visible ( partial_link_text ) :
element = self .... |
def subclass ( cls , vt_code , vt_args ) :
"""Return a dynamic subclass that has the extra parameters built in
: param vt _ code : The full VT code , privided to resolve _ type
: param vt _ args : The portion of the VT code to the right of the part that matched a ValueType
: return :""" | return type ( vt_code . replace ( '/' , '_' ) , ( cls , ) , { 'vt_code' : vt_code , 'vt_args' : vt_args } ) |
def add_fixed_lens ( self , kwargs_fixed_lens , kwargs_lens_init ) :
"""returns kwargs that are kept fixed during run , depending on options
: param kwargs _ options :
: param kwargs _ lens :
: return :""" | kwargs_fixed_lens = self . _solver . add_fixed_lens ( kwargs_fixed_lens , kwargs_lens_init )
return kwargs_fixed_lens |
def stepBy ( self , steps ) :
"""steps value up / down by a single step . Single step is defined in singleStep ( ) .
Args :
steps ( int ) : positiv int steps up , negativ steps down""" | self . setValue ( self . value ( ) + steps * self . singleStep ( ) ) |
def Collect ( self , knowledge_base ) :
"""Collects values from the knowledge base .
Args :
knowledge _ base ( KnowledgeBase ) : to fill with preprocessing information .
Raises :
PreProcessFail : if the preprocessing fails .""" | environment_variable = knowledge_base . GetEnvironmentVariable ( 'programdata' )
allusersappdata = getattr ( environment_variable , 'value' , None )
if not allusersappdata :
environment_variable = knowledge_base . GetEnvironmentVariable ( 'allusersprofile' )
allusersdata = getattr ( environment_variable , 'valu... |
def create_user ( self , username , email , password , active = False , send_email = True ) :
"""A simple wrapper that creates a new : class : ` User ` .
: param username :
String containing the username of the new user .
: param email :
String containing the email address of the new user .
: param passwo... | user = super ( AccountActivationManager , self ) . create_user ( username , email , password )
if isinstance ( user . username , str ) :
username = user . username . encode ( 'utf-8' )
salt , activation_key = generate_sha1 ( username )
user . is_active = active
user . activation_key = activation_key
user . save ( u... |
def contextMenuEvent ( self , event ) :
"""Override Qt method""" | self . setCurrentIndex ( self . tabBar ( ) . tabAt ( event . pos ( ) ) )
if self . menu :
self . menu . popup ( event . globalPos ( ) ) |
def update_exponential ( self , Z , eta , BDpair = None ) :
"""exponential update of C that guarantees positive definiteness , that is ,
instead of the assignment ` ` C = C + eta * Z ` ` ,
we have ` ` C = C * * . 5 * exp ( eta * C * * - . 5 * Z * C * * - . 5 ) * C * * . 5 ` ` .
Parameter ` Z ` should have exp... | if eta == 0 :
return
if BDpair :
B , D = BDpair
else :
D , B = self . opts [ 'CMA_eigenmethod' ] ( self . C )
self . count_eigen += 1
D **= 0.5
Cs = dot ( B , ( B * D ) . T )
# square root of C
Csi = dot ( B , ( B / D ) . T )
# square root of inverse of C
self . C = dot ( Cs , dot ( Mh . expms ( eta... |
def similarity ( self , M_c , X_L_list , X_D_list , given_row_id , target_row_id , target_columns = None ) :
"""Computes the similarity of the given row to the target row ,
averaged over all the column indexes given by target _ columns .
: param given _ row _ id : the id of one of the rows to measure similarity... | return su . similarity ( M_c , X_L_list , X_D_list , given_row_id , target_row_id , target_columns ) |
def make_worker_router ( config , obj , queue_name ) :
"""Makes MessageRouter which can listen to queue _ name sending lando _ worker specific messages to obj .
: param config : WorkerConfig / ServerConfig : settings for connecting to the queue
: param obj : object : implements lando _ worker specific methods
... | return MessageRouter ( config , obj , queue_name , VM_LANDO_WORKER_INCOMING_MESSAGES , processor_constructor = DisconnectingWorkQueueProcessor ) |
def execution_profile_clone_update ( self , ep , ** kwargs ) :
"""Returns a clone of the ` ` ep ` ` profile . ` ` kwargs ` ` can be specified to update attributes
of the returned profile .
This is a shallow clone , so any objects referenced by the profile are shared . This means Load Balancing Policy
is maint... | clone = copy ( self . _maybe_get_execution_profile ( ep ) )
for attr , value in kwargs . items ( ) :
setattr ( clone , attr , value )
return clone |
def dump_next ( self , obj ) :
"""Dump the parent of a PID .""" | if self . _is_child ( obj ) and not obj . is_last_child ( self . context [ 'pid' ] ) :
return self . _dump_relative ( obj . next_child ( self . context [ 'pid' ] ) ) |
def wiggle ( self , noiseLevel = .1 ) :
"""Slightly changes value of every cell in the worksheet . Used for testing .""" | noise = ( np . random . rand ( * self . data . shape ) ) - .5
self . data = self . data + noise * noiseLevel |
def reload_components_ui ( self ) :
"""Reloads user selected Components .
: return : Method success .
: rtype : bool
: note : May require user interaction .""" | selected_components = self . get_selected_components ( )
self . __engine . start_processing ( "Reloading Components ..." , len ( selected_components ) )
reload_failed_components = [ ]
for component in selected_components :
if component . interface . deactivatable :
success = self . reload_component ( compon... |
def save_controls ( self , parameterstep : 'timetools.PeriodConstrArg' = None , simulationstep : 'timetools.PeriodConstrArg' = None , auxfiler : 'Optional[auxfiletools.Auxfiler]' = None ) :
"""Save the control parameters of the | Model | object handled by
each | Element | object and eventually the ones handled by... | if auxfiler :
auxfiler . save ( parameterstep , simulationstep )
for element in printtools . progressbar ( self ) :
element . model . parameters . save_controls ( parameterstep = parameterstep , simulationstep = simulationstep , auxfiler = auxfiler ) |
def enumerations ( self , name = None , function = None , header_dir = None , header_file = None , recursive = None , allow_empty = None ) :
"""returns a set of enumeration declarations , that are matched
defined criteria""" | return ( self . _find_multiple ( self . _impl_matchers [ scopedef_t . enumeration ] , name = name , function = function , decl_type = self . _impl_decl_types [ scopedef_t . enumeration ] , header_dir = header_dir , header_file = header_file , recursive = recursive , allow_empty = allow_empty ) ) |
def _pool_get ( get , results , next_available , task_next_lock , to_skip , task_num , pool_size , id_self ) :
"""( internal ) Intended to be run in a separate thread and take results from
the pool and put them into queues depending on the task of the result .
It finishes if it receives termination - sentinels ... | log . debug ( 'NuMap(%s) started pool_getter' % id_self )
# should return when all workers have returned , each worker sends a
# sentinel before returning . Before returning it should send sentinels to
# all tasks but the next available queue should be released only if we
# know that no new results will arrive .
sentin... |
def is_pinned ( self , color : Color , square : Square ) -> bool :
"""Detects if the given square is pinned to the king of the given color .""" | return self . pin_mask ( color , square ) != BB_ALL |
def get_timerange_formatted ( self , now ) :
"""Return two ISO8601 formatted date strings , one for timeMin , the other for timeMax ( to be consumed by get _ events )""" | later = now + datetime . timedelta ( days = self . days )
return now . isoformat ( ) , later . isoformat ( ) |
def do_attr ( environment , obj , name ) :
"""Get an attribute of an object . ` ` foo | attr ( " bar " ) ` ` works like
` ` foo . bar ` ` just that always an attribute is returned and items are not
looked up .
See : ref : ` Notes on subscriptions < notes - on - subscriptions > ` for more details .""" | try :
name = str ( name )
except UnicodeError :
pass
else :
try :
value = getattr ( obj , name )
except AttributeError :
pass
else :
if environment . sandboxed and not environment . is_safe_attribute ( obj , name , value ) :
return environment . unsafe_undefined (... |
def elide_sequence ( s , flank = 5 , elision = "..." ) :
"""trim a sequence to include the left and right flanking sequences of
size ` flank ` , with the intervening sequence elided by ` elision ` .
> > > elide _ sequence ( " ABCDEFGHIJKLMNOPQRSTUVWXYZ " )
' ABCDE . . . VWXYZ '
> > > elide _ sequence ( " AB... | elided_sequence_len = flank + flank + len ( elision )
if len ( s ) <= elided_sequence_len :
return s
return s [ : flank ] + elision + s [ - flank : ] |
def delete ( self , save = True ) :
"""Deletes the original , plus any thumbnails . Fails silently if there
are errors deleting the thumbnails .""" | for thumb in self . field . thumbs :
thumb_name , thumb_options = thumb
thumb_filename = self . _calc_thumb_filename ( thumb_name )
self . storage . delete ( thumb_filename )
super ( ImageWithThumbsFieldFile , self ) . delete ( save ) |
def encode_cf_datetime ( dates , units = None , calendar = None ) :
"""Given an array of datetime objects , returns the tuple ` ( num , units ,
calendar ) ` suitable for a CF compliant time variable .
Unlike ` date2num ` , this function can handle datetime64 arrays .
See also
cftime . date2num""" | dates = np . asarray ( dates )
if units is None :
units = infer_datetime_units ( dates )
else :
units = _cleanup_netcdf_time_units ( units )
if calendar is None :
calendar = infer_calendar_name ( dates )
delta , ref_date = _unpack_netcdf_time_units ( units )
try :
if calendar not in _STANDARD_CALENDARS ... |
def create_missing ( self ) :
"""Create a bogus managed host .
The exact set of attributes that are required varies depending on
whether the host is managed or inherits values from a host group and
other factors . Unfortunately , the rules for determining which
attributes should be filled in are mildly comp... | # pylint : disable = no - member , too - many - branches , too - many - statements
super ( Host , self ) . create_missing ( )
# See : https : / / bugzilla . redhat . com / show _ bug . cgi ? id = 1227854
self . name = self . name . lower ( )
if not hasattr ( self , 'mac' ) :
self . mac = self . _fields [ 'mac' ] . ... |
def refresh ( self , state = None ) :
"""Refreshes the state of this entity .
If * state * is provided , load it as the new state for this
entity . Otherwise , make a roundtrip to the server ( by calling
the : meth : ` read ` method of ` ` self ` ` ) to fetch an updated state ,
plus at most two additional r... | if state is not None :
self . _state = state
else :
self . _state = self . read ( self . get ( ) )
return self |
def get_group_index_sorter ( group_index , ngroups ) :
"""algos . groupsort _ indexer implements ` counting sort ` and it is at least
O ( ngroups ) , where
ngroups = prod ( shape )
shape = map ( len , keys )
that is , linear in the number of combinations ( cartesian product ) of unique
values of groupby k... | count = len ( group_index )
alpha = 0.0
# taking complexities literally ; there may be
beta = 1.0
# some room for fine - tuning these parameters
do_groupsort = ( count > 0 and ( ( alpha + beta * ngroups ) < ( count * np . log ( count ) ) ) )
if do_groupsort :
sorter , _ = algos . groupsort_indexer ( ensure_int64 ( ... |
def delete ( name ) :
"""Delete a keypair resource policy .
NAME : NAME of a keypair resource policy to delete .""" | with Session ( ) as session :
if input ( 'Are you sure? (y/n): ' ) . lower ( ) . strip ( ) [ : 1 ] != 'y' :
print ( 'Canceled.' )
sys . exit ( 1 )
try :
data = session . ResourcePolicy . delete ( name )
except Exception as e :
print_error ( e )
sys . exit ( 1 )
if... |
def log_ ( message : str , logger : logging . Logger , level : str = "info" , extra : Optional [ Dict ] = None , trim : bool = False , ) -> None :
"""Log a request or response
Args :
message : JSON - RPC request or response string .
level : Log level .
extra : More details to include in the log entry .
tr... | if extra is None :
extra = { }
# Clean up the message for logging
if message :
message = message . replace ( "\n" , "" ) . replace ( " " , " " ) . replace ( "{ " , "{" )
if trim :
message = _trim_message ( message )
# Log .
getattr ( logger , level ) ( message , extra = extra ) |
def flatten_multidict ( multidict ) :
"""Return flattened dictionary from ` ` MultiDict ` ` .""" | return dict ( [ ( key , value if len ( value ) > 1 else value [ 0 ] ) for ( key , value ) in multidict . iterlists ( ) ] ) |
def extract_channel ( k , cdim ) :
"""Create a : class : ` CPermutation ` that extracts channel ` k `
Return a permutation circuit that maps the k - th ( zero - based )
input to the last output , while preserving the relative order of all other
channels .
Args :
k ( int ) : Extracted channel index
cdim ... | n = cdim
perm = tuple ( list ( range ( k ) ) + [ n - 1 ] + list ( range ( k , n - 1 ) ) )
return CPermutation . create ( perm ) |
def _initialize_manager ( self , runtime ) :
"""Sets the runtime , configuration and json client""" | if self . _runtime is not None :
raise errors . IllegalState ( 'this manager has already been initialized.' )
self . _runtime = runtime
self . _config = runtime . get_configuration ( )
set_json_client ( runtime ) |
def get_sds_by_id ( self , id ) :
"""Get ScaleIO SDS object by its id
: param name : ID of SDS
: return : ScaleIO SDS object
: raise KeyError : No SDS with specified id found
: rtype : SDS object""" | for sds in self . sds :
if sds . id == id :
return sds
raise KeyError ( "SDS with that ID not found" ) |
def transform ( instance , tokenizer , max_seq_length , max_predictions_per_seq , do_pad = True ) :
"""Transform instance to inputs for MLM and NSP .""" | pad = tokenizer . convert_tokens_to_ids ( [ '[PAD]' ] ) [ 0 ]
input_ids = tokenizer . convert_tokens_to_ids ( instance . tokens )
input_mask = [ 1 ] * len ( input_ids )
segment_ids = list ( instance . segment_ids )
assert len ( input_ids ) <= max_seq_length
valid_lengths = len ( input_ids )
masked_lm_positions = list (... |
def prompt_4_yes_no ( question , input = None ) :
"""Prompt for a yes / no or y / n answer
: param question : Question to be asked
: param input : Used for unit testing
: return : True for yes / y , False for no / n""" | count = 0
while True :
printError ( question + ' (y/n)? ' )
choice = prompt ( input ) . lower ( )
if choice == 'yes' or choice == 'y' :
return True
elif choice == 'no' or choice == 'n' :
return False
else :
count += 1
printError ( '\'%s\' is not a valid answer. Enter ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.