signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def delete_instance ( self , name , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) : """Deletes a specific Redis instance . Instance stops serving and data is deleted . Example : > > > from google . cloud import redis _...
# Wrap the transport method to add retry and timeout logic . if "delete_instance" not in self . _inner_api_calls : self . _inner_api_calls [ "delete_instance" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . delete_instance , default_retry = self . _method_configs [ "DeleteInstance" ] . ...
def _fetch_error_descriptions ( self , error_dict ) : """: type error _ dict : dict [ str , list [ dict [ str , str ] ] : rtype : list [ str ]"""
error_descriptions = [ ] for error in error_dict [ self . _FIELD_ERROR ] : description = error [ self . _FIELD_ERROR_DESCRIPTION ] error_descriptions . append ( description ) return error_descriptions
def get_files_in_current_directory ( file_type ) : """Gets the list of files in the current directory and subdirectories . Respects . floydignore file if present"""
local_files = [ ] total_file_size = 0 ignore_list , whitelist = FloydIgnoreManager . get_lists ( ) floyd_logger . debug ( "Ignoring: %s" , ignore_list ) floyd_logger . debug ( "Whitelisting: %s" , whitelist ) file_paths = get_unignored_file_paths ( ignore_list , whitelist ) for file_path in file_paths : local_files...
async def open ( self ) : """Register with the publisher ."""
self . store . register ( self ) while not self . finished : message = await self . messages . get ( ) await self . publish ( message )
def create_object ( request , model = None , template_name = None , template_loader = loader , extra_context = None , post_save_redirect = None , login_required = False , context_processors = None , form_class = None ) : """Generic object - creation function . Templates : ` ` < app _ label > / < model _ name > _ ...
if extra_context is None : extra_context = { } if login_required and not request . user . is_authenticated : return redirect_to_login ( request . path ) model , form_class = get_model_and_form_class ( model , form_class ) if request . method == 'POST' : form = form_class ( request . POST , request . FILES )...
def pipeline_repr ( obj ) : """Returns a string representation of an object , including pieshell pipelines ."""
if not hasattr ( repr_state , 'in_repr' ) : repr_state . in_repr = 0 repr_state . in_repr += 1 try : return standard_repr ( obj ) finally : repr_state . in_repr -= 1
def _set_session_cookie ( self ) : """Set the session data cookie ."""
LOGGER . debug ( 'Setting session cookie for %s' , self . session . id ) self . set_secure_cookie ( name = self . _session_cookie_name , value = self . session . id , expires = self . _cookie_expiration )
def search ( self , spec , operator ) : '''Query PYPI via XMLRPC interface using search spec'''
return self . xmlrpc . search ( spec , operator . lower ( ) )
def isClientCert ( self , name ) : '''Checks if a user client certificate ( PKCS12 ) exists . Args : name ( str ) : The name of the user keypair . Examples : Check if the client certificate " myuser " exists : exists = cdir . isClientCert ( ' myuser ' ) Returns : bool : True if the certificate is pres...
crtpath = self . _getPathJoin ( 'users' , '%s.p12' % name ) return os . path . isfile ( crtpath )
def printFunc ( name , m ) : """prints results"""
print ( "* %s *" % name ) objSet = bool ( m . getObjective ( ) . terms . keys ( ) ) print ( "* Is objective set? %s" % objSet ) if objSet : print ( "* Sense: %s" % m . getObjectiveSense ( ) ) for v in m . getVars ( ) : if v . name != "n" : print ( "%s: %d" % ( v , round ( m . getVal ( v ) ) ) ) print ( ...
def __ensure_provisioning_writes ( table_name , key_name , num_consec_write_checks ) : """Ensure that provisioning of writes is correct : type table _ name : str : param table _ name : Name of the DynamoDB table : type key _ name : str : param key _ name : Configuration option key name : type num _ consec...
if not get_table_option ( key_name , 'enable_writes_autoscaling' ) : logger . info ( '{0} - Autoscaling of writes has been disabled' . format ( table_name ) ) return False , dynamodb . get_provisioned_table_write_units ( table_name ) , 0 update_needed = False try : lookback_window_start = get_table_option (...
def shutdown ( self , message = None ) : """Disconnect all servers with a message . Args : message ( str ) : Quit message to use on each connection ."""
for name , server in self . servers . items ( ) : server . quit ( message )
def count_collision ( number_of_cars : int ) : """This function simulates an infinite road where cars move against each other from two directions . There are ' n ' cars coming from left heading toward right and ' n ' cars from right heading to left , with same speed . Two cars are said to meet when a car moving...
return number_of_cars ** 2
def decode_dict_keys ( d , coding = "utf-8" ) : """Convert all keys to unicde ( recursively ) ."""
assert compat . PY2 res = { } for k , v in d . items ( ) : if type ( k ) is str : k = k . decode ( coding ) if type ( v ) is dict : v = decode_dict_keys ( v , coding ) res [ k ] = v return res
def do_work ( self ) : """Run a single connection iteration . This will return ` True ` if the connection is still open and ready to be used for further work , or ` False ` if it needs to be shut down . : rtype : bool : raises : TimeoutError or ~ uamqp . errors . ClientTimeout if CBS authentication timeou...
if self . _shutdown : return False if not self . client_ready ( ) : return True return self . _client_run ( )
def bulk_create_awards ( objects , batch_size = 500 , post_save_signal = True ) : """Saves award objects ."""
count = len ( objects ) if not count : return badge = objects [ 0 ] . badge try : Award . objects . bulk_create ( objects , batch_size = batch_size ) if post_save_signal : for obj in objects : signals . post_save . send ( sender = obj . __class__ , instance = obj , created = True ) excep...
def build ( self , ** kwargs ) : """create the operation and associate tasks : param dict kwargs : operation data : return : the controller : rtype : kser . sequencing . controller . OperationController"""
self . tasks += self . compute_tasks ( ** kwargs ) return self . finalize ( )
def init_optimizer ( self ) : """Initializes query optimizer state . There are 4 internals hash tables : 1 . from type to declarations 2 . from type to declarations for non - recursive queries 3 . from type to name to declarations 4 . from type to name to declarations for non - recursive queries Almost ...
if self . name == '::' : self . _logger . debug ( "preparing data structures for query optimizer - started" ) start_time = timeit . default_timer ( ) self . clear_optimizer ( ) for dtype in scopedef_t . _impl_all_decl_types : self . _type2decls [ dtype ] = [ ] self . _type2decls_nr [ dtype ] = [ ] self ...
def _array_safe_dict_eq ( one_dict , other_dict ) : """Dicts containing arrays are hard to compare . This function uses numpy . allclose to compare arrays , and does normal comparison for all other types . : param one _ dict : : param other _ dict : : return : bool"""
for key in one_dict : try : assert one_dict [ key ] == other_dict [ key ] except ValueError as err : # When dealing with arrays , we need to use numpy for comparison if isinstance ( one_dict [ key ] , dict ) : assert FitResults . _array_safe_dict_eq ( one_dict [ key ] , other_dict [ ...
def _statsd_address ( self ) : """Return a tuple of host and port for the statsd server to send stats to . : return : tuple ( host , port )"""
return ( self . application . settings . get ( 'statsd' , { } ) . get ( 'host' , self . STATSD_HOST ) , self . application . settings . get ( 'statsd' , { } ) . get ( 'port' , self . STATSD_PORT ) )
def print_markdown ( data , title = None ) : """Print data in GitHub - flavoured Markdown format for issues etc . data ( dict or list of tuples ) : Label / value pairs . title ( unicode or None ) : Title , will be rendered as headline 2."""
def excl_value ( value ) : # contains path , i . e . personal info return isinstance ( value , basestring_ ) and Path ( value ) . exists ( ) if isinstance ( data , dict ) : data = list ( data . items ( ) ) markdown = [ "* **{}:** {}" . format ( l , unicode_ ( v ) ) for l , v in data if not excl_value ( v ) ] if...
def are_collinear ( magmoms ) : """Method checks to see if a set of magnetic moments are collinear with each other . : param magmoms : list of magmoms ( Magmoms , scalars or vectors ) : return : bool"""
magmoms = [ Magmom ( magmom ) for magmom in magmoms ] if not Magmom . have_consistent_saxis ( magmoms ) : magmoms = Magmom . get_consistent_set ( magmoms ) # convert to numpy array for convenience magmoms = np . array ( [ list ( magmom ) for magmom in magmoms ] ) magmoms = magmoms [ np . any ( magmoms , axis = 1 ) ...
def get ( self , zone_id ) : """Retrieve the information for a zone entity ."""
path = '/' . join ( [ 'zone' , zone_id ] ) return self . rachio . get ( path )
def clean_upload ( self , query = '/content/uploads/' ) : """pulp leaves droppings if you don ' t specifically tell it to clean up after itself . use this to do so ."""
query = query + self . uid + '/' _r = self . connector . delete ( query ) if _r . status_code == Constants . PULP_DELETE_OK : juicer . utils . Log . log_info ( "Cleaned up after upload request." ) else : _r . raise_for_status ( )
def zoom ( self , zoom , center = ( 0 , 0 , 0 ) , mapped = True ) : """Update the transform such that its scale factor is changed , but the specified center point is left unchanged . Parameters zoom : array - like Values to multiply the transform ' s current scale factors . center : array - like The c...
zoom = as_vec4 ( zoom , default = ( 1 , 1 , 1 , 1 ) ) center = as_vec4 ( center , default = ( 0 , 0 , 0 , 0 ) ) scale = self . scale * zoom if mapped : trans = center - ( center - self . translate ) * zoom else : trans = self . scale * ( 1 - zoom ) * center + self . translate self . _set_st ( scale = scale , tr...
def normalize_ip ( ip ) : """Transform the address into a fixed - length form , such as : : 192.168.0.1 - > 192.168.000.001 : type ip : string : param ip : An IP address . : rtype : string : return : The normalized IP ."""
theip = ip . split ( '.' ) if len ( theip ) != 4 : raise ValueError ( 'ip should be 4 tuples' ) return '.' . join ( str ( int ( l ) ) . rjust ( 3 , '0' ) for l in theip )
def hash_str ( data , hasher = None ) : """Checksum hash a string ."""
hasher = hasher or hashlib . sha1 ( ) hasher . update ( data ) return hasher
def find_files ( self , ignore_policies = True ) : """Search shared and private assemblies and return a list of files . If any files are not found , return an empty list . IMPORTANT NOTE : For the purpose of getting the dependent assembly files of an executable , the publisher configuration ( aka policy ) s...
# Shared Assemblies : # http : / / msdn . microsoft . com / en - us / library / aa375996%28VS . 85%29 . aspx # Private Assemblies : # http : / / msdn . microsoft . com / en - us / library / aa375674%28VS . 85%29 . aspx # Assembly Searching Sequence : # http : / / msdn . microsoft . com / en - us / library / aa374224%28...
def get ( self , uri_pattern , headers = None , parameters = None , ** kwargs ) : """Launch HTTP GET request to the API with given arguments : param uri _ pattern : string pattern of the full API url with keyword arguments ( format string syntax ) : param headers : HTTP header ( dict ) : param parameters : Qu...
print uri_pattern print headers return self . _call_api ( uri_pattern , HTTP_VERB_GET , headers = headers , parameters = parameters , ** kwargs )
def smart_scrubb ( df , col_name , error_rate = 0 ) : """Scrubs from the back of an ' object ' column in a DataFrame until the scrub would semantically alter the contents of the column . If only a subset of the elements in the column are scrubbed , then a boolean array indicating which elements have been scru...
scrubbed = "" while True : valcounts = df [ col_name ] . str [ - len ( scrubbed ) - 1 : ] . value_counts ( ) if not len ( valcounts ) : break if not valcounts [ 0 ] >= ( 1 - error_rate ) * _utils . rows ( df ) : break scrubbed = valcounts . index [ 0 ] if scrubbed == '' : return None...
def set_metadata ( self , metadata_dict ) : """Set the metadata on a dataset * * metadata _ dict * * : A dictionary of metadata key - vals . Transforms this dict into an array of metadata objects for storage in the DB ."""
if metadata_dict is None : return existing_metadata = [ ] for m in self . metadata : existing_metadata . append ( m . key ) if m . key in metadata_dict : if m . value != metadata_dict [ m . key ] : m . value = metadata_dict [ m . key ] for k , v in metadata_dict . items ( ) : if k no...
def _crawl_attribute ( this_data , this_attr ) : '''helper function to crawl an attribute specified for retrieval'''
if isinstance ( this_data , list ) : t_list = [ ] for d in this_data : t_list . append ( _crawl_attribute ( d , this_attr ) ) return t_list else : if isinstance ( this_attr , dict ) : t_dict = { } for k in this_attr : if hasattr ( this_data , k ) : t_d...
def import_one_to_many ( self , file_path , column_index , parent_table , column_in_one2many_table ) : """: param file _ path : : param column _ index : : param parent _ table : : param column _ in _ one2many _ table :"""
chunks = pd . read_table ( file_path , usecols = [ column_index ] , header = None , comment = '#' , index_col = False , chunksize = 1000000 , dtype = self . get_dtypes ( parent_table . model ) ) for chunk in chunks : child_values = [ ] parent_id_values = [ ] chunk . dropna ( inplace = True ) chunk . ind...
def delete_pre_subscriptions ( self , ** kwargs ) : # noqa : E501 """Remove pre - subscriptions # noqa : E501 Removes pre - subscriptions . * * Example usage : * * curl - X DELETE https : / / api . us - east - 1 . mbedcloud . com / v2 / subscriptions - H ' authorization : Bearer { api - key } ' # noqa : E501 Th...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'asynchronous' ) : return self . delete_pre_subscriptions_with_http_info ( ** kwargs ) # noqa : E501 else : ( data ) = self . delete_pre_subscriptions_with_http_info ( ** kwargs ) # noqa : E501 return data
def get_header ( mesh ) : """For now we only know Element types 1 ( line ) and 2 ( triangle )"""
nr_all_nodes = len ( mesh [ 'nodes' ] ) nr_types = 1 # triangles # compute bandwidth bandwidth = - 1 for triangle in mesh [ 'elements' ] [ '2' ] : diff1 = abs ( triangle [ 0 ] - triangle [ 1 ] ) diff2 = abs ( triangle [ 0 ] - triangle [ 2 ] ) diff3 = abs ( triangle [ 1 ] - triangle [ 2 ] ) diffm = max (...
def create ( self , ** kwargs ) : """Create the resource on the BIG - IP ® . Uses HTTP POST to the ` collection ` URI to create a resource associated with a new unique URI on the device . As proxyServerPool parameter will be required only if useProxyServer is set to ' enabled ' we have to use conditional ...
if kwargs [ 'useProxyServer' ] == 'enabled' : tup_par = ( 'proxyServerPool' , 'trustedCa' , 'useProxyServer' ) else : tup_par = ( 'dnsResolver' , 'trustedCa' , 'useProxyServer' ) self . _meta_data [ 'required_creation_parameters' ] . update ( tup_par ) return self . _create ( ** kwargs )
def dumps ( self , obj ) : """Serializes obj to an avro - format byte array and returns it ."""
out = BytesIO ( ) try : self . dump ( obj , out ) return out . getvalue ( ) finally : out . close ( )
def circle_circle_intersection ( C_a , r_a , C_b , r_b ) : '''Finds the coordinates of the intersection points of two circles A and B . Circle center coordinates C _ a and C _ b , should be given as tuples ( or 1x2 arrays ) . Returns a 2x2 array result with result [ 0 ] being the first intersection point ( to t...
C_a , C_b = np . asarray ( C_a , float ) , np . asarray ( C_b , float ) v_ab = C_b - C_a d_ab = np . linalg . norm ( v_ab ) if np . abs ( d_ab ) < tol : # No intersection points or infinitely many of them ( circle centers coincide ) return None cos_gamma = ( d_ab ** 2 + r_a ** 2 - r_b ** 2 ) / 2.0 / d_ab / r_a if a...
def guess_leb_size ( path ) : """Get LEB size from superblock Arguments : Str : path - - Path to file . Returns : Int - - LEB size . Searches file for superblock and retrieves leb size ."""
f = open ( path , 'rb' ) f . seek ( 0 , 2 ) file_size = f . tell ( ) + 1 f . seek ( 0 ) block_size = None for _ in range ( 0 , file_size , FILE_CHUNK_SZ ) : buf = f . read ( FILE_CHUNK_SZ ) for m in re . finditer ( UBIFS_NODE_MAGIC , buf ) : start = m . start ( ) chdr = nodes . common_hdr ( buf ...
def printStatistics ( completion , concordance , tpedSamples , oldSamples , prefix ) : """Print the statistics in a file . : param completion : the completion of each duplicated samples . : param concordance : the concordance of each duplicated samples . : param tpedSamples : the updated position of the sampl...
# Compute the completion percentage on none zero values none_zero_indexes = np . where ( completion [ 1 ] != 0 ) completionPercentage = np . zeros ( len ( completion [ 0 ] ) , dtype = float ) completionPercentage [ none_zero_indexes ] = np . true_divide ( completion [ 0 , none_zero_indexes ] , completion [ 1 , none_zer...
def make_table ( self ) : """Make numpy array from timeseries data ."""
num_records = int ( np . sum ( [ 1 for frame in self . timeseries ] ) ) dtype = [ ( "frame" , float ) , ( "time" , float ) , ( "proteinring" , list ) , ( "ligand_ring_ids" , list ) , ( "distance" , float ) , ( "angle" , float ) , ( "offset" , float ) , ( "type" , "|U4" ) , ( "resid" , int ) , ( "resname" , "|U4" ) , ( ...
def get_unique_record ( self , sql , parameters = None , quiet = False , locked = False ) : '''I use this pattern a lot . Return the single record corresponding to the query .'''
results = self . execute_select ( sql , parameters = parameters , quiet = quiet , locked = locked ) assert ( len ( results ) == 1 ) return results [ 0 ]
def devices ( opts = [ ] ) : """Get list of all available devices including emulators : param opts : list command options ( e . g . [ " - r " , " - a " ] ) : return : result of _ exec _ command ( ) execution"""
adb_full_cmd = [ v . ADB_COMMAND_PREFIX , v . ADB_COMMAND_DEVICES , _convert_opts ( opts ) ] return _exec_command ( adb_full_cmd )
def _archive_tp_file_done_tasks ( self , taskpaperPath ) : """* archive tp file done tasks * * * Key Arguments : * * - ` ` taskpaperPath ` ` - - path to a taskpaper file * * Return : * * - None"""
self . log . info ( 'starting the ``_archive_tp_file_done_tasks`` method' ) self . log . info ( "archiving taskpaper file %(taskpaperPath)s" % locals ( ) ) taskLog = { } mdArchiveFile = taskpaperPath . replace ( ".taskpaper" , "-tasklog.md" ) exists = os . path . exists ( mdArchiveFile ) if exists : pathToReadFile ...
def _handle_properties ( self , stmt : Statement , sctx : SchemaContext ) -> None : """Handle * * enum * * statements ."""
nextval = 0 for est in stmt . find_all ( "enum" ) : if not sctx . schema_data . if_features ( est , sctx . text_mid ) : continue label = est . argument vst = est . find1 ( "value" ) if vst : val = int ( vst . argument ) self . enum [ label ] = val if val > nextval : ...
def _name ( iris_obj , default = 'unknown' ) : """Mimicks ` iris _ obj . name ( ) ` but with different name resolution order . Similar to iris _ obj . name ( ) method , but using iris _ obj . var _ name first to enable roundtripping ."""
return ( iris_obj . var_name or iris_obj . standard_name or iris_obj . long_name or default )
def return_dat ( self , chan , begsam , endsam ) : """Return the data as 2D numpy . ndarray . Parameters chan : int or list index ( indices ) of the channels to read begsam : int index of the first sample endsam : int index of the last sample Returns numpy . ndarray A 2d matrix , with dimension ...
TRL = 0 try : ft_data = loadmat ( self . filename , struct_as_record = True , squeeze_me = True ) ft_data = ft_data [ VAR ] data = ft_data [ 'trial' ] . item ( TRL ) except NotImplementedError : from h5py import File with File ( self . filename ) as f : data = f [ f [ VAR ] [ 'trial' ] [ TRL...
def main ( ) : '''main entry'''
cli = docker . from_env ( ) try : opts , args = getopt . gnu_getopt ( sys . argv [ 1 : ] , "pcv" , [ "pretty" , "compose" ] ) except getopt . GetoptError as _ : print ( "Usage: docker-parse [--pretty|-p|--compose|-c] [containers]" ) sys . exit ( 2 ) if len ( args ) == 0 : containers = cli . containers ....
def expand ( self , string ) : """Expand ."""
self . expanding = False empties = [ ] found_literal = False if string : i = iter ( StringIter ( string ) ) for x in self . get_literals ( next ( i ) , i , 0 ) : # We don ' t want to return trailing empty strings . # Store empty strings and output only when followed by a literal . if not x : ...
def get_class ( self , name ) : """Return a specific class : param name : the name of the class : rtype : a : class : ` ClassDefItem ` object"""
for i in self . classes . class_def : if i . get_name ( ) == name : return i return None
def command_gen ( tool_installations , tool_executable , args = None , node_paths = None ) : """Generate a Command object with required tools installed and paths set up . : param list tool _ installations : A list of functions to install required tools . Those functions should take no parameter and return an in...
node_module_bin_dir = 'node_modules/.bin' extra_paths = [ ] for t in tool_installations : # Calling tool _ installation [ i ] ( ) triggers installation if tool is not installed extra_paths . append ( t ( ) ) if node_paths : for node_path in node_paths : if not node_path . endswith ( node_module_bin_dir ...
def fetch_token ( self , code , state ) : """Fetch the token , using the verification code . Also , make sure the state received in the response matches the one in the request . Returns the access _ token ."""
if self . state != state : raise MismatchingStateError ( ) self . token = self . oauth . fetch_token ( '%saccess_token/' % OAUTH_URL , code = code , client_secret = self . client_secret ) return self . token [ 'access_token' ]
def CreateJob ( self , cron_args = None , job_id = None , enabled = True , token = None ) : """Creates a cron job that runs given flow with a given frequency . Args : cron _ args : A protobuf of type rdf _ cronjobs . CreateCronJobArgs . job _ id : Use this job _ id instead of an autogenerated unique name ( us...
# TODO ( amoser ) : Remove the token from this method once the aff4 # cronjobs are gone . del token if not job_id : uid = random . UInt16 ( ) job_id = "%s_%s" % ( cron_args . flow_name , uid ) args = rdf_cronjobs . CronJobAction ( action_type = rdf_cronjobs . CronJobAction . ActionType . HUNT_CRON_ACTION , hunt...
async def _incoming_from_rtm ( self , url : str , bot_id : str ) -> AsyncIterator [ events . Event ] : """Connect and discard incoming RTM event if necessary . : param url : Websocket url : param bot _ id : Bot ID : return : Incoming events"""
async for data in self . _rtm ( url ) : event = events . Event . from_rtm ( json . loads ( data ) ) if sansio . need_reconnect ( event ) : break elif sansio . discard_event ( event , bot_id ) : continue else : yield event
def request ( self , response_queue , payload , timeout_s = None , poll = POLL_QUEUES ) : '''Send Parameters device : serial . Serial Serial instance . response _ queue : Queue . Queue Queue to wait for response on . payload : str or bytes Payload to send . timeout _ s : float , optional Maximum t...
self . connected . wait ( timeout_s ) return request ( self , response_queue , payload , timeout_s = timeout_s , poll = poll )
def start ( self ) : """Initialize websockets , say hello , and start listening for events"""
self . connect ( ) if not self . isAlive ( ) : super ( WAMPClient , self ) . start ( ) self . hello ( ) return self
def evaluate ( self , verbose = False , decode = True , passes = None , num_threads = 1 , apply_experimental = True ) : """Evaluates by creating an Index containing evaluated data . See ` LazyResult ` Returns Index Index with evaluated data ."""
evaluated_data = super ( Index , self ) . evaluate ( verbose , decode , passes , num_threads , apply_experimental ) return Index ( evaluated_data , self . dtype , self . name )
def write_file ( self , blob , dest ) : '''Using the blob object , write the file to the destination path'''
with salt . utils . files . fopen ( dest , 'wb+' ) as fp_ : fp_ . write ( blob . data )
def SetTimelineOwner ( self , username ) : """Sets the username of the user that should own the timeline . Args : username ( str ) : username ."""
self . _timeline_owner = username logger . info ( 'Owner of the timeline: {0!s}' . format ( self . _timeline_owner ) )
def removereadergroup ( self , group ) : """Remove a reader group"""
hresult , hcontext = SCardEstablishContext ( SCARD_SCOPE_USER ) if 0 != hresult : raise error ( 'Failed to establish context: ' + SCardGetErrorMessage ( hresult ) ) try : hresult = SCardForgetReaderGroup ( hcontext , group ) if hresult != 0 : raise error ( 'Unable to forget reader group: ' + SCardGe...
def match ( self , other , psd = None , low_frequency_cutoff = None , high_frequency_cutoff = None ) : """Return the match between the two TimeSeries or FrequencySeries . Return the match between two waveforms . This is equivelant to the overlap maximized over time and phase . By default , the other vector will...
return self . to_frequencyseries ( ) . match ( other , psd = psd , low_frequency_cutoff = low_frequency_cutoff , high_frequency_cutoff = high_frequency_cutoff )
def check_constraint_convergence ( X , L , LX , Z , U , R , S , step_f , step_g , e_rel , e_abs ) : """Calculate if all constraints have converged . Using the stopping criteria from Boyd 2011 , Sec 3.3.1 , calculate whether the variables for each constraint have converged ."""
if isinstance ( L , list ) : M = len ( L ) convergence = True errors = [ ] # recursive call for i in range ( M ) : c , e = check_constraint_convergence ( X , L [ i ] , LX [ i ] , Z [ i ] , U [ i ] , R [ i ] , S [ i ] , step_f , step_g [ i ] , e_rel , e_abs ) convergence &= c ...
def filter_grounded_only ( ) : """Filter to grounded Statements only ."""
if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) stmts_json = body . get ( 'statements' ) score_threshold = body . get ( 'score_threshold' ) if score_threshold is not None : score_threshold = float ( score_threshold ) stmts ...
def from_Composition ( composition ) : """Return the LilyPond equivalent of a Composition in a string ."""
# warning Throw exception if not hasattr ( composition , 'tracks' ) : return False result = '\\header { title = "%s" composer = "%s" opus = "%s" } ' % ( composition . title , composition . author , composition . subtitle ) for track in composition . tracks : result += from_Track ( track ) + ' ' return result [ ...
def download_source_dists ( self , arguments , use_wheels = False ) : """Download missing source distributions . : param arguments : The command line arguments to ` ` pip install . . . ` ` ( a list of strings ) . : param use _ wheels : Whether pip and pip - accel are allowed to use wheels _ ( : data : ` Fal...
download_timer = Timer ( ) logger . info ( "Downloading missing distribution(s) .." ) requirements = self . get_pip_requirement_set ( arguments , use_remote_index = True , use_wheels = use_wheels ) logger . info ( "Finished downloading distribution(s) in %s." , download_timer ) return requirements
def nla_len ( self , value ) : """Length setter ."""
self . bytearray [ self . _get_slicers ( 0 ) ] = bytearray ( c_uint16 ( value or 0 ) )
def database ( state , host , name , # Desired database settings present = True , collate = None , charset = None , user = None , user_hostname = 'localhost' , user_privileges = 'ALL' , # Details for speaking to MySQL via ` mysql ` CLI mysql_user = None , mysql_password = None , mysql_host = None , mysql_port = None , ...
current_databases = host . fact . mysql_databases ( mysql_user , mysql_password , mysql_host , mysql_port , ) is_present = name in current_databases if not present : if is_present : yield make_execute_mysql_command ( 'DROP DATABASE {0}' . format ( name ) , user = mysql_user , password = mysql_password , hos...
def _get_session_timeout_seconds ( cls , session_server ) : """: type session _ server : core . SessionServer : rtype : int"""
if session_server . user_company is not None : return session_server . user_company . session_timeout elif session_server . user_person is not None : return session_server . user_person . session_timeout elif session_server . user_api_key is not None : return session_server . user_api_key . requested_by_use...
def addObject ( self , featureIndices , name = None ) : """Adds a sequence ( list of feature indices ) to the Machine ."""
if name is None : name = len ( self . objects ) sequence = [ ] for f in featureIndices : sequence += [ ( 0 , f , ) ] self . objects [ name ] = sequence
def changeNickname ( self , nickname , user_id , thread_id = None , thread_type = ThreadType . USER ) : """Changes the nickname of a user in a thread : param nickname : New nickname : param user _ id : User that will have their nickname changed : param thread _ id : User / Group ID to change color of . See : ...
thread_id , thread_type = self . _getThread ( thread_id , thread_type ) data = { "nickname" : nickname , "participant_id" : user_id , "thread_or_other_fbid" : thread_id , } j = self . _post ( self . req_url . THREAD_NICKNAME , data , fix_request = True , as_json = True )
def initialize ( self , training_info , model , environment , device ) : """Initialize policy gradient from reinforcer settings"""
self . target_model = self . model_factory . instantiate ( action_space = environment . action_space ) . to ( device ) self . target_model . load_state_dict ( model . state_dict ( ) ) self . target_model . eval ( ) histogram_info = model . histogram_info ( ) self . vmin = histogram_info [ 'vmin' ] self . vmax = histogr...
def ltcube ( self , ** kwargs ) : """return the name of a livetime cube file"""
kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) kwargs_copy [ 'dataset' ] = kwargs . get ( 'dataset' , self . dataset ( ** kwargs ) ) localpath = NameFactory . ltcube_format . format ( ** kwargs_copy ) if kwargs . get ( 'fullpath' , False ) : return self . fullpath ( localpath = localpa...
def _get_file_size ( file_path ) : """Returns the size of the file at the specified file path , formatted as a 4 - byte unsigned integer bytearray ."""
size = getsize ( file_path ) file_size = bytearray ( 4 ) pack_into ( b"I" , file_size , 0 , size ) return file_size
def new ( self , boot_system_id ) : # type : ( bytes ) - > None '''A method to create a new Boot Record . Parameters : boot _ system _ id - The system identifier to associate with this Boot Record . Returns : Nothing .'''
if self . _initialized : raise Exception ( 'Boot Record already initialized' ) self . boot_system_identifier = boot_system_id . ljust ( 32 , b'\x00' ) self . boot_identifier = b'\x00' * 32 self . boot_system_use = b'\x00' * 197 # This will be set later self . _initialized = True
def is_sw_readable ( self ) : """Field is readable by software"""
sw = self . get_property ( 'sw' ) return sw in ( rdltypes . AccessType . rw , rdltypes . AccessType . rw1 , rdltypes . AccessType . r )
def return_hdr ( self ) : """Return the header for further use . Returns subj _ id : str subject identification code start _ time : datetime start time of the dataset s _ freq : float sampling frequency chan _ name : list of str list of all the channels n _ samples : int number of samples in t...
subj_id = self . _header [ 'name' ] + ' ' + self . _header [ 'surname' ] chan_name = [ ch [ 'chan_name' ] for ch in self . _header [ 'chans' ] ] return subj_id , self . _header [ 'start_time' ] , self . _header [ 's_freq' ] , chan_name , self . _n_smp , self . _header
def connect ( self ) : """Connect to vCenter server"""
try : context = ssl . SSLContext ( ssl . PROTOCOL_TLSv1_2 ) if self . config [ 'no_ssl_verify' ] : requests . packages . urllib3 . disable_warnings ( ) context . verify_mode = ssl . CERT_NONE self . si = SmartConnectNoSSL ( host = self . config [ 'server' ] , user = self . config [ 'user...
def get_hidden_signups ( self ) : """Return a list of Users who are * not * in the All Students list but have signed up for an activity . This is usually a list of signups for z - Withdrawn from TJ"""
return EighthSignup . objects . filter ( scheduled_activity__block = self ) . exclude ( user__in = User . objects . get_students ( ) )
def num_mode_groups ( self ) : """Most devices only provide a single mode group , however devices such as the Wacom Cintiq 22HD provide two mode groups . If multiple mode groups are available , a caller should use : meth : ` ~ libinput . define . TabletPadModeGroup . has _ button ` , : meth : ` ~ libinput ....
num = self . _libinput . libinput_device_tablet_pad_get_num_mode_groups ( self . _handle ) if num < 0 : raise AttributeError ( 'This device is not a tablet pad device' ) return num
def resize ( self , package ) : """POST / : login / machines / : id ? action = resize Initiate resizing of the remote machine to a new package ."""
if isinstance ( package , dict ) : package = package [ 'name' ] action = { 'action' : 'resize' , 'package' : package } j , r = self . datacenter . request ( 'POST' , self . path , params = action ) r . raise_for_status ( )
def compare_changes ( obj , ** kwargs ) : '''Compare two dicts returning only keys that exist in the first dict and are different in the second one'''
changes = { } for key , value in obj . items ( ) : if key in kwargs : if value != kwargs [ key ] : changes [ key ] = kwargs [ key ] return changes
def get_active_terms_ids ( ) : """Returns a list of the IDs of of all terms and conditions"""
active_terms_ids = cache . get ( 'tandc.active_terms_ids' ) if active_terms_ids is None : active_terms_dict = { } active_terms_ids = [ ] active_terms_set = TermsAndConditions . objects . filter ( date_active__isnull = False , date_active__lte = timezone . now ( ) ) . order_by ( 'date_active' ) for activ...
def _next_ontology ( self ) : """Dynamically retrieves the next ontology in the list"""
currentfile = self . current [ 'file' ] try : idx = self . all_ontologies . index ( currentfile ) return self . all_ontologies [ idx + 1 ] except : return self . all_ontologies [ 0 ]
def get ( cls , parent , name ) : """Get an instance matching the parent and name"""
return cls . query . filter_by ( parent = parent , name = name ) . one_or_none ( )
def create ( cls , interface_id , logical_interface_ref , second_interface_id = None , zone_ref = None , ** kwargs ) : """: param str interface _ id : two interfaces , i . e . ' 1-2 ' , ' 4-5 ' , ' 7-10 ' , etc : param str logical _ ref : logical interface reference : param str zone _ ref : reference to zone , ...
data = { 'inspect_unspecified_vlans' : True , 'nicid' : '{}-{}' . format ( str ( interface_id ) , str ( second_interface_id ) ) if second_interface_id else str ( interface_id ) , 'logical_interface_ref' : logical_interface_ref , 'zone_ref' : zone_ref } for k , v in kwargs . items ( ) : data . update ( { k : v } ) r...
def sort_by_distance ( self , ps : Union [ "Units" , List [ "Point2" ] ] ) -> List [ "Point2" ] : """This returns the target points sorted as list . You should not pass a set or dict since those are not sortable . If you want to sort your units towards a point , use ' units . sorted _ by _ distance _ to ( point )...
if len ( ps ) == 1 : return ps [ 0 ] # if ps and all ( isinstance ( p , Point2 ) for p in ps ) : # return sorted ( ps , key = lambda p : self . _ distance _ squared ( p ) ) return sorted ( ps , key = lambda p : self . _distance_squared ( p . position ) )
def eval_objfn ( self ) : """Compute components of regularisation function as well as total contribution to objective function ."""
dfd = self . obfn_g0 ( self . obfn_g0var ( ) ) cns = self . obfn_g1 ( self . obfn_g1var ( ) ) return ( dfd , cns )
def assertEqual ( first , second , message = None ) : """Assert that first equals second . : param first : First part to evaluate : param second : Second part to evaluate : param message : Failure message : raises : TestStepFail if not first = = second"""
if not first == second : raise TestStepFail ( format_message ( message ) if message is not None else "Assert: %s != %s" % ( str ( first ) , str ( second ) ) )
def timeline ( self ) : """Get timeline , reloading the site if needed ."""
rev = int ( self . db . get ( 'site:rev' ) ) if rev != self . revision : self . reload_site ( ) return self . _timeline
def _latex_ ( self ) : r"""The representation routine for transitions . > > > g1 = State ( " Cs " , 133 , 6 , 0 , 1 / Integer ( 2 ) , 3) > > > g2 = State ( " Cs " , 133 , 6 , 0 , 1 / Integer ( 2 ) , 4) > > > Transition ( g2 , g1 ) . _ latex _ ( ) ' ^ { 133 } \ \ mathrm { Cs } \ \ 6S _ { 1/2 } ^ { 4 } \ \ \ ...
if self . allowed : return self . e1 . _latex_ ( ) + '\\ \\rightarrow \\ ' + self . e2 . _latex_ ( ) elif not self . allowed : return self . e1 . _latex_ ( ) + '\\ \\nrightarrow \\ ' + self . e2 . _latex_ ( ) else : return self . e1 . _latex_ ( ) + '\\ \\rightarrow^? \\ ' + self . e2 . _latex_ ( ) return se...
def delete_mapping ( self , index , doc_type ) : """Delete a typed JSON document type from a specific index . ( See : ref : ` es - guide - reference - api - admin - indices - delete - mapping ` )"""
path = make_path ( index , doc_type ) return self . conn . _send_request ( 'DELETE' , path )
def _transform_index ( index , func , level = None ) : """Apply function to all values found in index . This includes transforming multiindex entries separately . Only apply function to one level of the MultiIndex if level is specified ."""
if isinstance ( index , MultiIndex ) : if level is not None : items = [ tuple ( func ( y ) if i == level else y for i , y in enumerate ( x ) ) for x in index ] else : items = [ tuple ( func ( y ) for y in x ) for x in index ] return MultiIndex . from_tuples ( items , names = index . names ) ...
def _create_prefix_notification ( outgoing_msg , rpc_session ) : """Constructs prefix notification with data from given outgoing message . Given RPC session is used to create RPC notification message ."""
assert outgoing_msg path = outgoing_msg . path assert path vpn_nlri = path . nlri assert path . source is not None if path . source != VRF_TABLE : # Extract relevant info for update - add / update - delete . params = [ { ROUTE_DISTINGUISHER : outgoing_msg . route_dist , PREFIX : vpn_nlri . prefix , NEXT_HOP : path ...
def goback ( self , days = 1 ) : """Go back days 刪除最新天數資料數據 days 代表刪除多少天數 ( 倒退幾天 )"""
for i in xrange ( days ) : self . raw_data . pop ( ) self . data_date . pop ( ) self . stock_range . pop ( ) self . stock_vol . pop ( ) self . stock_open . pop ( ) self . stock_h . pop ( ) self . stock_l . pop ( )
def create_prj_browser ( self , ) : """Create the project browser This creates a combobox brower for projects and adds it to the ui : returns : the created combo box browser : rtype : : class : ` jukeboxcore . gui . widgets . browser . ComboBoxBrowser ` : raises : None"""
prjbrws = ComboBoxBrowser ( 1 , headers = [ 'Project:' ] ) self . central_vbox . insertWidget ( 0 , prjbrws ) return prjbrws
def from_hsv ( h , s , v , alpha = 1.0 , wref = _DEFAULT_WREF ) : """Create a new instance based on the specifed HSV values . Parameters : The Hus component value [ 0 . . . 1] The Saturation component value [ 0 . . . 1] The Value component [ 0 . . . 1] : alpha : The color transparency [ 0 . . . 1 ] , de...
h2 , s , l = rgb_to_hsl ( * hsv_to_rgb ( h , s , v ) ) return Color ( ( h , s , l ) , 'hsl' , alpha , wref )
def recordtype ( typename , field_names , verbose = False , ** default_kwds ) : '''Returns a new class with named fields . @ keyword field _ defaults : A mapping from ( a subset of ) field names to default values . @ keyword default : If provided , the default value for all fields without an explicit defaul...
# Parse and validate the field names . Validation serves two purposes , # generating informative error messages and preventing template injection attacks . if isinstance ( field_names , str ) : # names separated by whitespace and / or commas field_names = field_names . replace ( ',' , ' ' ) . split ( ) field_names ...
def edge2geoff ( from_node , to_node , properties , edge_relationship_name , encoder ) : """converts a NetworkX edge into a Geoff string . Parameters from _ node : str or int the ID of a NetworkX source node to _ node : str or int the ID of a NetworkX target node properties : dict a dictionary of edge...
edge_string = None if properties : args = [ from_node , edge_relationship_name , encoder . encode ( properties ) , to_node ] edge_string = '({0})-[:{1} {2}]->({3})' . format ( * args ) else : args = [ from_node , edge_relationship_name , to_node ] edge_string = '({0})-[:{1}]->({2})' . format ( * args ) ...
def unpickle_stats ( stats ) : """Unpickle a pstats . Stats object"""
stats = cPickle . loads ( stats ) stats . stream = True return stats
def strip_encoding_cookie ( filelike ) : """Generator to pull lines from a text - mode file , skipping the encoding cookie if it is found in the first two lines ."""
it = iter ( filelike ) try : first = next ( it ) if not cookie_comment_re . match ( first ) : yield first second = next ( it ) if not cookie_comment_re . match ( second ) : yield second except StopIteration : return for line in it : yield line