signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def set_reboot_required_witnessed ( ) : '''This function is used to remember that an event indicating that a reboot is required was witnessed . This function writes to a temporary filesystem so the event gets cleared upon reboot . Returns : bool : ` ` True ` ` if successful , otherwise ` ` False ` ` . . c...
errcode = - 1 dir_path = os . path . dirname ( NILRT_REBOOT_WITNESS_PATH ) if not os . path . exists ( dir_path ) : try : os . makedirs ( dir_path ) except OSError as ex : raise SaltInvocationError ( 'Error creating {0} (-{1}): {2}' . format ( dir_path , ex . errno , ex . strerror ) ) rdict ...
def get_default_config ( self ) : """Returns default collector settings ."""
config = super ( UPSCollector , self ) . get_default_config ( ) config . update ( { 'path' : 'ups' , 'ups_name' : 'cyberpower' , 'bin' : '/bin/upsc' , 'use_sudo' : False , 'sudo_cmd' : '/usr/bin/sudo' , } ) return config
async def get_file ( self , file_id : base . String ) -> types . File : """Use this method to get basic info about a file and prepare it for downloading . For the moment , bots can download files of up to 20MB in size . Note : This function may not preserve the original file name and MIME type . You should sa...
payload = generate_payload ( ** locals ( ) ) result = await self . request ( api . Methods . GET_FILE , payload ) return types . File ( ** result )
def printSysLog ( self , logString ) : """Log one or more lines . Optionally , add them to logEntries list . Input : Strings to be logged ."""
if zvmsdklog . LOGGER . getloglevel ( ) <= logging . DEBUG : # print log only when debug is enabled if self . daemon == '' : self . logger . debug ( self . requestId + ": " + logString ) else : self . daemon . logger . debug ( self . requestId + ": " + logString ) if self . captureLogs is True :...
def get_matches ( self , code , start = 0 , end = None , skip = None ) : """Search for ` code ` in source and return a list of ` Match ` \ es ` code ` can contain wildcards . ` ` $ { name } ` ` matches normal names and ` ` $ { ? name } can match any expression . You can use ` Match . get _ ast ( ) ` for getti...
if end is None : end = len ( self . source ) for match in self . _get_matched_asts ( code ) : match_start , match_end = match . get_region ( ) if start <= match_start and match_end <= end : if skip is not None and ( skip [ 0 ] < match_end and skip [ 1 ] > match_start ) : continue ...
def __FindSupportedVersion ( protocol , server , port , path , preferredApiVersions , sslContext ) : """Private method that returns the most preferred API version supported by the specified server , @ param protocol : What protocol to use for the connection ( e . g . https or http ) . @ type protocol : string...
serviceVersionDescription = __GetServiceVersionDescription ( protocol , server , port , path , sslContext ) if serviceVersionDescription is None : return None if not isinstance ( preferredApiVersions , list ) : preferredApiVersions = [ preferredApiVersions ] for desiredVersion in preferredApiVersions : if _...
def finite_datetimes ( self , finite_start , finite_stop ) : """Simply returns the points in time that correspond to a whole number of minutes intervals ."""
# Validate that the minutes _ interval can divide 60 and it is greater than 0 and lesser than 60 if not ( 0 < self . minutes_interval < 60 ) : raise ParameterException ( 'minutes-interval must be within 0..60' ) if ( 60 / self . minutes_interval ) * self . minutes_interval != 60 : raise ParameterException ( 'mi...
def hijack_require_http_methods ( fn ) : """Wrapper for " require _ http _ methods " decorator . POST required by default , GET can optionally be allowed"""
required_methods = [ 'POST' ] if hijack_settings . HIJACK_ALLOW_GET_REQUESTS : required_methods . append ( 'GET' ) return require_http_methods ( required_methods ) ( fn )
def _container_init ( self ) : """Check if sos is running in a container and perform container specific initialisation based on ENV _ HOST _ SYSROOT ."""
if ENV_CONTAINER in os . environ : if os . environ [ ENV_CONTAINER ] in [ 'docker' , 'oci' ] : self . _in_container = True if ENV_HOST_SYSROOT in os . environ : self . _host_sysroot = os . environ [ ENV_HOST_SYSROOT ] use_sysroot = self . _in_container and self . _host_sysroot != '/' if use_sysroot : ...
def validate_authorization_request ( self , uri , http_method = 'GET' , body = None , headers = None ) : """Extract response _ type and route to the designated handler ."""
request = Request ( uri , http_method = http_method , body = body , headers = headers ) request . scopes = utils . scope_to_list ( request . scope ) response_type_handler = self . response_types . get ( request . response_type , self . default_response_type_handler ) return response_type_handler . validate_authorizatio...
def shift_by_n_processors ( self , x , mesh_axis , offset , wrap ) : """Receive the slice from processor pcoord - offset . Args : x : a LaidOutTensor mesh _ axis : an integer offset : an integer wrap : a boolean . If True , then wrap around . Otherwise , pad with zeros ."""
n = self . shape [ mesh_axis ] . size source_pcoord = [ ] for i in xrange ( n ) : c = i - offset if c != c % n : if wrap : c = c % n else : c = None source_pcoord . append ( c ) return self . receive ( x , mesh_axis , source_pcoord )
def run ( self , ** kwargs ) : """Drive servo to the position set in the ` position _ sp ` attribute ."""
for key in kwargs : setattr ( self , key , kwargs [ key ] ) self . command = self . COMMAND_RUN
def natsorted ( seq , cmp = natcmp ) : "Returns a copy of seq , sorted by natural string sort ."
import copy temp = copy . copy ( seq ) natsort ( temp , cmp ) return temp
def get_soft_bounds ( self ) : """For each soft bound ( upper and lower ) , if there is a defined bound ( not equal to None ) then it is returned , otherwise it defaults to the hard bound . The hard bound could still be None ."""
if self . bounds is None : hl , hu = ( None , None ) else : hl , hu = self . bounds if self . _softbounds is None : sl , su = ( None , None ) else : sl , su = self . _softbounds if sl is None : l = hl else : l = sl if su is None : u = hu else : u = su return ( l , u )
def remove_cached_item ( self , path ) : """Remove cached resource item : param path : str : return : PIL . Image"""
item_path = '%s/%s' % ( self . cache_folder , path . strip ( '/' ) ) self . blob_service . delete_blob ( self . container_name , item_path ) while self . blob_service . exists ( self . container_name , item_path ) : time . sleep ( 0.5 ) return True
def create ( self , name , status , description = "" , link = "" , order = 0 , group_id = 0 , enabled = True ) : """Create a new component : param str name : Name of the component : param int status : Status of the component ; 1-4 : param str description : Description of the component ( optional ) : param s...
data = ApiParams ( ) data [ 'name' ] = name data [ 'status' ] = status data [ 'description' ] = description data [ 'link' ] = link data [ 'order' ] = order data [ 'group_id' ] = group_id data [ 'enabled' ] = enabled return self . _post ( 'components' , data = data ) [ 'data' ]
def cross_entropy_loss ( inputs , labels , rescale_loss = 1 ) : """cross entropy loss with a mask"""
criterion = mx . gluon . loss . SoftmaxCrossEntropyLoss ( weight = rescale_loss ) loss = criterion ( inputs , labels ) mask = S . var ( 'mask' ) loss = loss * S . reshape ( mask , shape = ( - 1 , ) ) return S . make_loss ( loss . mean ( ) )
def _patch_redirect ( session ) : # type : ( requests . Session ) - > None """Whether redirect policy should be applied based on status code . HTTP spec says that on 301/302 not HEAD / GET , should NOT redirect . But requests does , to follow browser more than spec https : / / github . com / requests / reques...
def enforce_http_spec ( resp , request ) : if resp . status_code in ( 301 , 302 ) and request . method not in [ 'GET' , 'HEAD' ] : return False return True redirect_logic = session . resolve_redirects def wrapped_redirect ( resp , req , ** kwargs ) : attempt = enforce_http_spec ( resp , req ) re...
def irreducible_effects ( self ) : """The set of irreducible effects in this | Account | ."""
return tuple ( link for link in self if link . direction is Direction . EFFECT )
def CDSReader ( fh , format = 'gff' ) : """yield chrom , strand , cds _ exons , name"""
known_formats = ( 'gff' , 'gtf' , 'bed' ) if format not in known_formats : print ( '%s format not in %s' % ( format , "," . join ( known_formats ) ) , file = sys . stderr ) raise Exception ( '?' ) if format == 'bed' : for line in fh : f = line . strip ( ) . split ( ) chrom = f [ 0 ] ...
def print_lamps ( ) : """Print all lamp devices as JSON"""
print ( "Printing information about all lamps paired to the Gateway" ) lights = [ dev for dev in devices if dev . has_light_control ] if len ( lights ) == 0 : exit ( bold ( "No lamps paired" ) ) container = [ ] for l in lights : container . append ( l . raw ) print ( jsonify ( container ) )
def pay ( self , transactionAmount , senderTokenId , recipientTokenId = None , callerTokenId = None , chargeFeeTo = "Recipient" , callerReference = None , senderReference = None , recipientReference = None , senderDescription = None , recipientDescription = None , callerDescription = None , metadata = None , transactio...
params = { } params [ 'SenderTokenId' ] = senderTokenId # this is for 2008-09-17 specification params [ 'TransactionAmount.Amount' ] = str ( transactionAmount ) params [ 'TransactionAmount.CurrencyCode' ] = "USD" # params [ ' TransactionAmount ' ] = str ( transactionAmount ) params [ 'ChargeFeeTo' ] = chargeFeeTo param...
def sort_by_float_value ( items ) : """This function sorts a list of tuples by the float value of the second element of each tuple . Examples : > > > sort _ by _ float _ value ( [ ( ' item1 ' , ' 12.20 ' ) , ( ' item2 ' , ' 15.10 ' ) , ( ' item3 ' , ' 24.5 ' ) ] ) [ ( ' item3 ' , ' 24.5 ' ) , ( ' item2 ' , ' ...
sorted_items = sorted ( items , key = lambda item : float ( item [ 1 ] ) , reverse = True ) return sorted_items
def detect_events ( dat , method , value = None ) : """Detect events using ' above _ thresh ' , ' below _ thresh ' or ' maxima ' method . Parameters dat : ndarray ( dtype = ' float ' ) vector with the data after transformation method : str ' above _ thresh ' , ' below _ thresh ' or ' maxima ' value : ...
if 'thresh' in method or 'custom' == method : if method == 'above_thresh' : above_det = dat >= value detected = _detect_start_end ( above_det ) if method == 'below_thresh' : below_det = dat < value detected = _detect_start_end ( below_det ) if method == 'between_thresh' : ...
def clear_unforced_dependencies ( self ) : """Remove all dependencies not forced by a comment . This is useful when existing analysis can infer exactly what the correct dependencies should be . Typical use is to call ` clear _ unforced _ dependencies ` , then call ` add _ dependency ` for each dependency infe...
self . _dependencies_by_address = dict ( ( address , dep ) for address , dep in self . _dependencies_by_address . items ( ) if dep . has_comment ( ) )
def zipalign ( source , dist , build_tool = None , version = '4' , path = None ) : """Uses zipalign based on a provided build tool version ( defaulit is 23.0.2 ) . : param source ( str ) - source apk file to be zipaligned : param dist ( str ) - zipaligned apk file path to be created : param build _ tool ( str...
if build_tool is None : build_tool = config . build_tool_version android_home = os . environ . get ( 'AG_MOBILE_SDK' , os . environ . get ( 'ANDROID_HOME' ) ) cmd_path = [ android_home , '/build-tools' , '/%s' % build_tool , '/zipalign' ] cmd = [ '' . join ( cmd_path ) , '-v' , version , source , dist , ] common . ...
def stage ( x , staging ) : """Stage an object to the ` staging ` directory . If the object is a Track and is one of the types that needs an index file ( bam , vcfTabix ) , then the index file will be staged as well . Returns a list of the linknames created ."""
linknames = [ ] # Objects that don ' t represent a file shouldn ' t be staged non_file_objects = ( track . ViewTrack , track . CompositeTrack , track . AggregateTrack , track . SuperTrack , genome . Genome , ) if isinstance ( x , non_file_objects ) : return linknames # If it ' s an object representing a file , then...
def form_invalid ( self , form ) : """Processes an invalid form submittal . : param form : the form instance . : rtype : django . http . HttpResponse ."""
context = self . get_context_data ( form = form ) # noinspection PyUnresolvedReferences return render_modal_workflow ( self . request , '{0}/chooser.html' . format ( self . template_dir ) , '{0}/chooser.js' . format ( self . template_dir ) , context )
def calculate_timeout ( http_date ) : """Extract request timeout from e . g . ` ` Retry - After ` ` header . Notes : Per : rfc : ` 2616 # section - 14.37 ` , the ` ` Retry - After ` ` header can be either an integer number of seconds or an HTTP date . This function can handle either . Arguments : http _...
try : return int ( http_date ) except ValueError : date_after = parse ( http_date ) utc_now = datetime . now ( tz = timezone . utc ) return int ( ( date_after - utc_now ) . total_seconds ( ) )
def get_input_column_attributes ( self , extra_classes = None ) : """: param extra _ classes : String with space separated list of classes or None"""
all_classes = [ ] css_class = self . input_column_class if css_class : all_classes . append ( css_class ) if extra_classes : all_classes . append ( extra_classes ) style = self . input_column_style parts = [ ] if all_classes : parts . append ( 'class="{}"' . format ( ' ' . join ( all_classes ) ) ) if style ...
def _execute ( self , code ) : """Override of litre . _ execute ; sets up variable context before evaluating code"""
self . globals [ 'example' ] = self . example eval ( code , self . globals )
def int2mjd ( d , loc ) : """Function to convert segment + integration into mjd seconds ."""
# needs to take merge pkl dict if len ( loc ) : intcol = d [ 'featureind' ] . index ( 'int' ) segmentcol = d [ 'featureind' ] . index ( 'segment' ) if d . has_key ( 'segmenttimesdict' ) : # using merged pkl scancol = d [ 'featureind' ] . index ( 'scan' ) t0 = np . array ( [ d [ 'segmenttimes...
def create_curiosity_encoders ( self ) : """Creates state encoders for current and future observations . Used for implementation of Curiosity - driven Exploration by Self - supervised Prediction See https : / / arxiv . org / abs / 1705.05363 for more details . : return : current and future state encoder tenso...
encoded_state_list = [ ] encoded_next_state_list = [ ] if self . vis_obs_size > 0 : self . next_visual_in = [ ] visual_encoders = [ ] next_visual_encoders = [ ] for i in range ( self . vis_obs_size ) : # Create input ops for next ( t + 1 ) visual observations . next_visual_input = self . create_...
def query_sum ( queryset , field ) : """Let the DBMS perform a sum on a queryset"""
return queryset . aggregate ( s = models . functions . Coalesce ( models . Sum ( field ) , 0 ) ) [ 's' ]
def value_eq ( self , other ) : """Sorted comparison of values ."""
self_sorted = ordered . ordered ( self . getvalues ( ) ) other_sorted = ordered . ordered ( repeated . getvalues ( other ) ) return self_sorted == other_sorted
def param_converter ( * decorator_args , ** decorator_kwargs ) : """Call with the url parameter names as keyword argument keys , their values being the model to convert to . Models will be looked up by the url param names . If a url param name is prefixed with the snake - cased model name , the prefix will be...
def wrapped ( fn ) : @ wraps ( fn ) def decorated ( * view_args , ** view_kwargs ) : view_kwargs = _convert_models ( view_kwargs , decorator_kwargs ) view_kwargs = _convert_query_params ( view_kwargs , decorator_kwargs ) return fn ( * view_args , ** view_kwargs ) return decorated if ...
def cli_plugin ( func = None , ** kwargs ) : """Decorator that wraps the given function in a : class : ` CLIPlugin ` Args : func ( callable ) : function / class to decorate * * kwargs : Any other arg to use when initializing the parser ( like help , or prefix _ chars ) Returns : CLIPlugin : cli plugin t...
# this allows calling this function as a decorator generator if func is None : return functools . partial ( cli_plugin , ** kwargs ) if not isinstance ( func , CLIPluginFuncWrapper ) : func = CLIPluginFuncWrapper ( do_run = func , init_args = kwargs ) else : func . set_init_args ( kwargs ) return func
def add_conditional_clause ( self , clause ) : """Adds a iff clause to this statement : param clause : The clause that will be added to the iff statement : type clause : ConditionalClause"""
clause . set_context_id ( self . context_counter ) self . context_counter += clause . get_context_size ( ) self . conditionals . append ( clause )
def get_domain_config ( self , domain ) : """Makes a discovery of domain name and resolves configuration of DNS provider : param domain : str domain name : return : DomainConnectConfig domain connect config : raises : NoDomainConnectRecordException when no _ domainconnect record found : raises : NoDom...
domain_root = self . identify_domain_root ( domain ) host = '' if len ( domain_root ) != len ( domain ) : host = domain . replace ( '.' + domain_root , '' ) domain_connect_api = self . _identify_domain_connect_api ( domain_root ) ret = self . _get_domain_config_for_root ( domain_root , domain_connect_api ) return D...
def start_end ( data , num_start = 250 , num_end = 100 , full_output = False ) : """Gate out first and last events . Parameters data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters ( aka channels ) . num _ start , num _ end : int , optiona...
if num_start < 0 : num_start = 0 if num_end < 0 : num_end = 0 if data . shape [ 0 ] < ( num_start + num_end ) : raise ValueError ( 'Number of events to discard greater than total' + ' number of events.' ) mask = np . ones ( shape = data . shape [ 0 ] , dtype = bool ) mask [ : num_start ] = False if num_end ...
def calculateImpliedVolatility ( self , reqId , contract , optionPrice , underPrice ) : """calculateImpliedVolatility ( EClient self , TickerId reqId , Contract contract , double optionPrice , double underPrice )"""
return _swigibpy . EClient_calculateImpliedVolatility ( self , reqId , contract , optionPrice , underPrice )
def process_request ( self , request ) : """Checks whether the page is already cached and returns the cached version if available ."""
celery_task = getattr ( request , '_cache_update_cache' , False ) if not request . method in ( 'GET' , 'HEAD' ) : request . _cache_update_cache = False return None # Don ' t bother checking the cache . request . _cache_update_cache = True if self . should_bypass_cache ( request ) : return None response , ex...
def version ( self , version_str : str ) -> None : """param version Version version number property . Must be a string consisting of three non - negative integers delimited by periods ( eg . ' 1.0.1 ' ) ."""
ver = [ ] for i in version_str . split ( '.' ) : ver . append ( int ( i ) ) self . filter_negatives ( int ( i ) ) self . _major , self . _minor , self . _patch = ver [ 0 ] , ver [ 1 ] , ver [ 2 ]
def motion_correction ( image , fixed = None , type_of_transform = "Rigid" , mask = None , fdOffset = 50 , verbose = False , ** kwargs ) : """Correct time - series data for motion . ANTsR function : ` antsrMotionCalculation ` Arguments image : antsImage , usually ND where D = 4. fixed : Fixed image to regis...
idim = image . dimension ishape = image . shape nTimePoints = ishape [ idim - 1 ] if fixed is None : wt = 1.0 / nTimePoints fixed = utils . slice_image ( image , axis = idim - 1 , idx = 0 ) * 0 for k in range ( nTimePoints ) : temp = utils . slice_image ( image , axis = idim - 1 , idx = k ) ...
def solveConsKinkedR ( solution_next , IncomeDstn , LivPrb , DiscFac , CRRA , Rboro , Rsave , PermGroFac , BoroCnstArt , aXtraGrid , vFuncBool , CubicBool ) : '''Solves a single period consumption - saving problem with CRRA utility and risky income ( subject to permanent and transitory shocks ) , and different in...
solver = ConsKinkedRsolver ( solution_next , IncomeDstn , LivPrb , DiscFac , CRRA , Rboro , Rsave , PermGroFac , BoroCnstArt , aXtraGrid , vFuncBool , CubicBool ) solver . prepareToSolve ( ) solution = solver . solve ( ) return solution
def getContactUIDForUser ( self ) : """get the UID of the contact associated with the authenticated user"""
user = self . REQUEST . AUTHENTICATED_USER user_id = user . getUserName ( ) r = self . portal_catalog ( portal_type = 'Contact' , getUsername = user_id ) if len ( r ) == 1 : return r [ 0 ] . UID
def name_for_number ( numobj , lang , script = None , region = None ) : """Returns a carrier name for the given PhoneNumber object , in the language provided . The carrier name is the one the number was originally allocated to , however if the country supports mobile number portability the number might not ...
ntype = number_type ( numobj ) if _is_mobile ( ntype ) : return name_for_valid_number ( numobj , lang , script , region ) return U_EMPTY_STRING
def delete_ip4 ( self , id_ip ) : """Delete an IP4 : param id _ ip : Ipv4 identifier . Integer value and greater than zero . : return : None : raise IpNotFoundError : IP is not registered . : raise DataBaseError : Networkapi failed to access the database ."""
if not is_valid_int_param ( id_ip ) : raise InvalidParameterError ( u'Ipv4 identifier is invalid or was not informed.' ) url = 'ip4/delete/' + str ( id_ip ) + "/" code , xml = self . submit ( None , 'DELETE' , url ) return self . response ( code , xml )
def aead_filename ( aead_dir , key_handle , public_id ) : """Return the filename of the AEAD for this public _ id , and create any missing directorys ."""
parts = [ aead_dir , key_handle ] + pyhsm . util . group ( public_id , 2 ) path = os . path . join ( * parts ) if not os . path . isdir ( path ) : os . makedirs ( path ) return os . path . join ( path , public_id )
def run_migrations_offline ( ) : """Run migrations in ' offline ' mode . This configures the context with just a URL and not an Engine , though an Engine is acceptable here as well . By skipping the Engine creation we don ' t even need a DBAPI to be available . Calls to context . execute ( ) here emit the...
url = get_url ( ) context . configure ( url = url , version_table = "alembic_ziggurat_foundations_version" , transaction_per_migration = True , ) with context . begin_transaction ( ) : context . run_migrations ( )
def sort ( self , search ) : """Add sorting information to the request ."""
if self . _sort : search = search . sort ( * self . _sort ) return search
def remove ( path , ** kwargs ) : '''Remove the named file . If a directory is supplied , it will be recursively deleted . CLI Example : . . code - block : : bash salt ' * ' file . remove / tmp / foo'''
path = os . path . expanduser ( path ) if not os . path . isabs ( path ) : raise SaltInvocationError ( 'File path must be absolute: {0}' . format ( path ) ) try : if os . path . isfile ( path ) or os . path . islink ( path ) : os . remove ( path ) return True elif os . path . isdir ( path ) ...
def get_context_data ( self , * args , ** kwargs ) : """Inject is _ plans _ plural and customer into context _ data ."""
context = super ( ) . get_context_data ( ** kwargs ) context [ "is_plans_plural" ] = Plan . objects . count ( ) > 1 context [ "customer" ] , _created = Customer . get_or_create ( subscriber = djstripe_settings . subscriber_request_callback ( self . request ) ) context [ "subscription" ] = context [ "customer" ] . subsc...
def parse_fields ( fields , as_dict = False ) : '''Given a list of fields ( or several other variants of the same ) , return back a consistent , normalized form of the same . To forms are currently supported : dictionary form : dict ' key ' is the field name and dict ' value ' is either 1 ( include ) or 0...
_fields = { } if fields in [ '~' , None , False , True , { } , [ ] ] : # all these signify ' all fields ' _fields = { } elif isinstance ( fields , dict ) : _fields . update ( { unicode ( k ) . strip ( ) : int ( v ) for k , v in fields . iteritems ( ) } ) elif isinstance ( fields , basestring ) : _fields . u...
def parse_duration ( duration , timestamp = None ) : """Interprets a ISO8601 duration value relative to a given timestamp . : param duration : The duration , as a string . : type : string : param timestamp : The unix timestamp we should apply the duration to . Optional , default to the current time . : ty...
assert isinstance ( duration , basestring ) assert timestamp is None or isinstance ( timestamp , int ) timedelta = duration_parser ( duration ) if timestamp is None : data = datetime . utcnow ( ) + timedelta else : data = datetime . utcfromtimestamp ( timestamp ) + timedelta return calendar . timegm ( data . ut...
def write ( self , data ) : """Write data to serial port ."""
for chunk in chunks ( data , 512 ) : self . wait_to_write ( ) self . comport . write ( chunk ) self . comport . flush ( )
def get_commit ( self , sha ) : """: calls : ` GET / repos / : owner / : repo / commits / : sha < http : / / developer . github . com / v3 / repos / commits > ` _ : param sha : string : rtype : : class : ` github . Commit . Commit `"""
assert isinstance ( sha , ( str , unicode ) ) , sha headers , data = self . _requester . requestJsonAndCheck ( "GET" , self . url + "/commits/" + sha ) return github . Commit . Commit ( self . _requester , headers , data , completed = True )
def SUB ( classical_reg , right ) : """Produce a SUB instruction . : param classical _ reg : Left operand for the arithmetic operation . Also serves as the store target . : param right : Right operand for the arithmetic operation . : return : A ClassicalSub instance ."""
left , right = unpack_reg_val_pair ( classical_reg , right ) return ClassicalSub ( left , right )
def call_parallel ( self , cdata , low ) : '''Call the state defined in the given cdata in parallel'''
# There are a number of possibilities to not have the cdata # populated with what we might have expected , so just be smart # enough to not raise another KeyError as the name is easily # guessable and fallback in all cases to present the real # exception to the user name = ( cdata . get ( 'args' ) or [ None ] ) [ 0 ] o...
def _convert_ftp_time_to_iso ( ftp_time ) : """Convert datetime in the format 20160705042714 to a datetime object : return : datetime object"""
date_time = datetime ( int ( ftp_time [ : 4 ] ) , int ( ftp_time [ 4 : 6 ] ) , int ( ftp_time [ 6 : 8 ] ) , int ( ftp_time [ 8 : 10 ] ) , int ( ftp_time [ 10 : 12 ] ) , int ( ftp_time [ 12 : 14 ] ) ) return date_time
def translatePath ( path ) : '''Creates folders in the OS ' s temp directory . Doesn ' t touch any possible XBMC installation on the machine . Attempting to do as little work as possible to enable this function to work seamlessly .'''
valid_dirs = [ 'xbmc' , 'home' , 'temp' , 'masterprofile' , 'profile' , 'subtitles' , 'userdata' , 'database' , 'thumbnails' , 'recordings' , 'screenshots' , 'musicplaylists' , 'videoplaylists' , 'cdrips' , 'skin' , ] assert path . startswith ( 'special://' ) , 'Not a valid special:// path.' parts = path . split ( '/' ...
def asobject ( self ) : """Return object Series which contains boxed values . . . deprecated : : 0.23.0 Use ` ` astype ( object ) ` ` instead . * this is an internal non - public method *"""
warnings . warn ( "'asobject' is deprecated. Use 'astype(object)'" " instead" , FutureWarning , stacklevel = 2 ) return self . astype ( object ) . values
def update ( self ) : """Update | KI2 | based on | EQI2 | and | TInd | . > > > from hydpy . models . lland import * > > > parameterstep ( ' 1d ' ) > > > eqi2(1.0) > > > tind . value = 10.0 > > > derived . ki2 . update ( ) > > > derived . ki2 ki2(10.0)"""
con = self . subpars . pars . control self ( con . eqi2 * con . tind )
def location_purge ( location_id , delete = False , verbosity = 0 ) : """Print and conditionally delete files not referenced by meta data . : param location _ id : Id of the : class : ` ~ resolwe . flow . models . DataLocation ` model that data objects reference to . : param delete : If ` ` True ` ` , then ...
try : location = DataLocation . objects . get ( id = location_id ) except DataLocation . DoesNotExist : logger . warning ( "Data location does not exist" , extra = { 'location_id' : location_id } ) return unreferenced_files = set ( ) purged_data = Data . objects . none ( ) referenced_by_data = location . da...
def update ( self , values ) : """Add new declarations to this set / Args : values ( dict ( name , declaration ) ) : the declarations to ingest ."""
for k , v in values . items ( ) : root , sub = self . split ( k ) if sub is None : self . declarations [ root ] = v else : self . contexts [ root ] [ sub ] = v extra_context_keys = set ( self . contexts ) - set ( self . declarations ) if extra_context_keys : raise errors . InvalidDeclara...
def create_sparse_mapping ( id_array , unique_ids = None ) : """Will create a scipy . sparse compressed - sparse - row matrix that maps each row represented by an element in id _ array to the corresponding value of the unique ids in id _ array . Parameters id _ array : 1D ndarray of ints . Each element sh...
# Create unique _ ids if necessary if unique_ids is None : unique_ids = get_original_order_unique_ids ( id_array ) # Check function arguments for validity assert isinstance ( unique_ids , np . ndarray ) assert isinstance ( id_array , np . ndarray ) assert unique_ids . ndim == 1 assert id_array . ndim == 1 # Figure ...
def max_entries ( self ) : """Removes the maximum entry limit"""
self . _debug_log . info ( 'Removing maximum entries restriction' ) self . _log_entries ( deque ( self . _log_entries ) )
def element_wise_op ( array , other , op , ty ) : """Operation of series and other , element - wise ( binary operator add ) Args : array ( WeldObject / Numpy . ndarray ) : Input array other ( WeldObject / Numpy . ndarray ) : Second Input array op ( str ) : Op string used to compute element - wise operation ...
weld_obj = WeldObject ( encoder_ , decoder_ ) array_var = weld_obj . update ( array ) if isinstance ( array , WeldObject ) : array_var = array . obj_id weld_obj . dependencies [ array_var ] = array other_var = weld_obj . update ( other ) if isinstance ( other , WeldObject ) : other_var = other . obj_id ...
def prune ( self , wordlist ) : """Prune the current reach instance by removing items . Parameters wordlist : list of str A list of words to keep . Note that this wordlist need not include all words in the Reach instance . Any words which are in the wordlist , but not in the reach instance are ignored .""...
# Remove duplicates wordlist = set ( wordlist ) . intersection ( set ( self . items . keys ( ) ) ) indices = [ self . items [ w ] for w in wordlist if w in self . items ] if self . unk_index is not None and self . unk_index not in indices : raise ValueError ( "Your unknown item is not in your list of items. " "Set ...
def AddStatEntry ( self , stat_entry , timestamp ) : """Registers stat entry at a given timestamp ."""
if timestamp in self . _stat_entries : message = ( "Duplicated stat entry write for path '%s' of type '%s' at " "timestamp '%s'. Old: %s. New: %s." ) message %= ( "/" . join ( self . _components ) , self . _path_type , timestamp , self . _stat_entries [ timestamp ] , stat_entry ) raise db . Error ( message ...
def parent ( self ) : """Retrieve the parent in which this activity is defined . If this is a task on top level , it raises NotFounderror . : return : a : class : ` Activity2 ` : raises NotFoundError : when it is a task in the top level of a project : raises APIError : when other error occurs Example > ...
parent_id = self . _json_data . get ( 'parent_id' ) if parent_id is None : raise NotFoundError ( "Cannot find subprocess for this task '{}', " "as this task exist on top level." . format ( self . name ) ) return self . _client . activity ( pk = parent_id , scope = self . scope_id )
def crps_quadrature ( x , cdf_or_dist , xmin = None , xmax = None , tol = 1e-6 ) : """Compute the continuously ranked probability score ( CPRS ) for a given forecast distribution ( cdf ) and observation ( x ) using numerical quadrature . This implementation allows the computation of CRPS for arbitrary forecast ...
return _crps_cdf ( x , cdf_or_dist , xmin , xmax , tol )
def generate_dataset_shelve ( filename , number_items = 1000 ) : """Generate a dataset with number _ items elements ."""
if os . path . exists ( filename ) : os . remove ( filename ) data = shelve . open ( filename ) names = get_names ( ) totalnames = len ( names ) # init random seeder random . seed ( ) # calculate items # names = random . sample ( names , number _ items ) for i in range ( number_items ) : data [ str ( i + 1 ) ] ...
def _setup_mqs ( self ) : """* * Purpose * * : Setup RabbitMQ system on the client side . We instantiate queue ( s ) ' pendingq - * ' for communication between the enqueuer thread and the task manager process . We instantiate queue ( s ) ' completedq - * ' for communication between the task manager and dequeuer...
try : self . _prof . prof ( 'init mqs setup' , uid = self . _uid ) self . _logger . debug ( 'Setting up mq connection and channel' ) mq_connection = pika . BlockingConnection ( pika . ConnectionParameters ( host = self . _mq_hostname , port = self . _port ) ) mq_channel = mq_connection . channel ( ) ...
def clean_key_name ( key ) : """Makes ` ` key ` ` a valid and appropriate SQL column name : 1 . Replaces illegal characters in column names with ` ` _ ` ` 2 . Prevents name from beginning with a digit ( prepends ` ` _ ` ` ) 3 . Lowercases name . If you want case - sensitive table or column names , you are a...
result = _illegal_in_column_name . sub ( "_" , key . strip ( ) ) if result [ 0 ] . isdigit ( ) : result = '_%s' % result if result . upper ( ) in sql_reserved_words : result = '_%s' % key return result . lower ( )
def file_dict ( * packages , ** kwargs ) : '''List the files that belong to a package , grouped by package . Not specifying any packages will return a list of _ every _ file on the system ' s package database ( not generally recommended ) . CLI Examples : . . code - block : : bash salt ' * ' pkg . file _ ...
errors = [ ] ret = { } cmd_files = [ 'apk' , 'info' , '-L' ] if not packages : return 'Package name should be provided' for package in packages : files = [ ] cmd = cmd_files [ : ] cmd . append ( package ) out = __salt__ [ 'cmd.run_all' ] ( cmd , output_loglevel = 'trace' , python_shell = False ) ...
def _send_queries ( self ) : """Sends queries to multiple addresses . Returns the number of successful queries ."""
res = 0 addrs = _resolve_addrs ( self . addresses , self . port , self . ignore_senderrors , [ self . _sock . family ] ) for addr in addrs : try : self . _send_query ( addr [ 1 ] ) res += 1 except : if not self . ignore_senderrors : raise return res
def to_shcoeffs ( self , itaper , normalization = '4pi' , csphase = 1 ) : """Return the spherical harmonic coefficients of taper i as a SHCoeffs class instance . Usage clm = x . to _ shcoeffs ( itaper , [ normalization , csphase ] ) Returns clm : SHCoeffs class instance Parameters itaper : int Taper...
if type ( normalization ) != str : raise ValueError ( 'normalization must be a string. ' + 'Input type was {:s}' . format ( str ( type ( normalization ) ) ) ) if normalization . lower ( ) not in set ( [ '4pi' , 'ortho' , 'schmidt' ] ) : raise ValueError ( "normalization must be '4pi', 'ortho' " + "or 'schmidt'....
def create_perturb_params ( countsmat , transmat = None ) : '''Computes transition probabilities and standard errors of the transition probabilities due to finite sampling using the MSM counts matrix . First , the transition probabilities are computed by dividing the each element c _ ij by the row - sumemd coun...
norm = np . sum ( countsmat , axis = 1 ) if not transmat : transmat = ( countsmat . transpose ( ) / norm ) . transpose ( ) counts = ( np . ones ( ( len ( transmat ) , len ( transmat ) ) ) * norm ) . transpose ( ) scale = ( ( transmat - transmat ** 2 ) ** 0.5 / counts ** 0.5 ) + 10 ** - 15 return transmat , scale
def insert_extracted_value ( self , doc , extracted_value , output_field , original_output_field = None ) : """inserts the extracted value into doc at the field specified by output _ field"""
if not extracted_value : return doc metadata = self . extractor . get_metadata ( ) if not self . extractor . get_include_context ( ) : if isinstance ( extracted_value , list ) : result = list ( ) for ev in extracted_value : result . append ( { 'value' : ev } ) else : resu...
def minimum ( station_code ) : """Extreme Minimum Design Temperature for a location . Degrees in Celcius Args : station _ code ( str ) : Weather Station Code Returns : float degrees Celcius"""
temp = None fin = None try : fin = open ( '%s/%s' % ( env . WEATHER_DATA_PATH , _basename ( station_code , 'ddy' ) ) ) except IOError : logger . info ( "File not found" ) download_extract ( _eere_url ( station_code ) ) fin = open ( '%s/%s' % ( env . WEATHER_DATA_PATH , _basename ( station_code , 'ddy' )...
def histogram_day_counts ( df , variable ) : """Create a week - long histogram of counts of the variable for each day . It is assumed that the DataFrame index is datetime and that the variable ` weekday _ name ` exists ."""
if not df . index . dtype in [ "datetime64[ns]" , "<M8[ns]" , ">M8[ns]" ] : log . error ( "index is not datetime" ) return False counts = df . groupby ( df . index . weekday_name ) [ variable ] . count ( ) . reindex ( calendar . day_name [ 0 : ] ) counts . plot ( kind = "bar" , width = 1 , rot = 0 , alpha = 0.7...
def _update_parameters ( self ) : """Update parameters of the acquisition required to evaluate the function . In particular : * Sample representer points repr _ points * Compute their log values repr _ points _ log * Compute belief locations logP"""
self . repr_points , self . repr_points_log = self . sampler . get_samples ( self . num_repr_points , self . proposal_function , self . burn_in_steps ) if np . any ( np . isnan ( self . repr_points_log ) ) or np . any ( np . isposinf ( self . repr_points_log ) ) : raise RuntimeError ( "Sampler generated representer...
def set_proxy_pool ( self , proxies , auth = None , https = True ) : """设置代理池 : param proxies : proxy列表 , 形如 ` ` [ " ip1 : port1 " , " ip2 : port2 " ] ` ` : param auth : 如果代理需要验证身份 , 通过这个参数提供 , 比如 : param https : 默认为 True , 传入 False 则不设置 https 代理 . . code - block : : python from requests . auth import HTT...
from random import choice if https : self . proxies = [ { 'http' : p , 'https' : p } for p in proxies ] else : self . proxies = [ { 'http' : p } for p in proxies ] def get_with_random_proxy ( url , ** kwargs ) : proxy = choice ( self . proxies ) kwargs [ 'proxies' ] = proxy if auth : kwargs ...
def tree_prune_tax_ids ( self , tree , tax_ids ) : """Prunes a tree back to contain only the tax _ ids in the list and their parents . Parameters tree : ` skbio . tree . TreeNode ` The root node of the tree to perform this operation on . tax _ ids : ` list ` A ` list ` of taxonomic IDs to keep in the tree...
tax_ids_to_keep = [ ] for tax_id in tax_ids : tax_ids_to_keep . append ( tax_id ) tax_ids_to_keep . extend ( [ x . name for x in tree . find ( tax_id ) . ancestors ( ) ] ) tree = tree . copy ( ) tree . remove_deleted ( lambda n : n . name not in tax_ids_to_keep ) return tree
async def handler ( event ) : """# full : Advises to read " Accessing the full API " in the docs ."""
await asyncio . wait ( [ event . delete ( ) , event . respond ( READ_FULL , reply_to = event . reply_to_msg_id ) ] )
def c32encode ( input_hex , min_length = None ) : """> > > c32encode ( ' a46ff88886c2ef9762d970b4d2c63678835bd39d ' ) ' MHQZH246RBQSERPSE2TD5HHPF21NQMWX ' > > > c32encode ( ' ' ) > > > c32encode ( ' 00000 ' , 20) '00000' > > > c32encode ( ' 000001 ' , 20) '000001' > > > c32encode ( ' 1000001 ' , 32) ...
if len ( input_hex ) == 0 : return '' if not re . match ( r'^[0-9a-fA-F]+$' , input_hex ) : raise ValueError ( 'Requires a hex string' ) if len ( input_hex ) % 2 != 0 : input_hex = '0{}' . format ( input_hex ) input_hex = input_hex . lower ( ) res = [ ] carry = 0 for i in range ( len ( input_hex ) - 1 , - 1...
def _PrepareAttributeContainer ( self , attribute_container ) : """Prepares an attribute container for storage . Args : attribute _ container ( AttributeContainer ) : attribute container . Returns : AttributeContainer : copy of the attribute container to store in the fake storage ."""
attribute_values_hash = hash ( attribute_container . GetAttributeValuesString ( ) ) identifier = identifiers . FakeIdentifier ( attribute_values_hash ) attribute_container . SetIdentifier ( identifier ) # Make sure the fake storage preserves the state of the attribute container . return copy . deepcopy ( attribute_cont...
def remove_context ( self , name ) : """Remove a context from the suite . Args : name ( str ) : Name of the context to remove ."""
self . _context ( name ) del self . contexts [ name ] self . _flush_tools ( )
def get_table ( table_name ) : """Get a registered table . Decorated functions will be converted to ` DataFrameWrapper ` . Parameters table _ name : str Returns table : ` DataFrameWrapper `"""
table = get_raw_table ( table_name ) if isinstance ( table , TableFuncWrapper ) : table = table ( ) return table
def ParseMetadataFile ( self , parser_mediator , file_entry , data_stream_name ) : """Parses a metadata file . Args : parser _ mediator ( ParserMediator ) : parser mediator . file _ entry ( dfvfs . FileEntry ) : file entry . data _ stream _ name ( str ) : data stream name ."""
parent_path_spec = getattr ( file_entry . path_spec , 'parent' , None ) filename_upper = file_entry . name . upper ( ) if ( self . _mft_parser and parent_path_spec and filename_upper in ( '$MFT' , '$MFTMIRR' ) and not data_stream_name ) : self . _ParseDataStreamWithParser ( parser_mediator , self . _mft_parser , fi...
def resource_type ( self ) : """Get the CoRE Link Format rt attribute of the resource . : return : the CoRE Link Format rt attribute"""
value = "rt=" lst = self . _attributes . get ( "rt" ) if lst is None : value = "" else : value += "\"" + str ( lst ) + "\"" return value
def get_active_window ( ) : """Get the currently focused window"""
active_win = None default = wnck . screen_get_default ( ) while gtk . events_pending ( ) : gtk . main_iteration ( False ) window_list = default . get_windows ( ) if len ( window_list ) == 0 : print "No Windows Found" for win in window_list : if win . is_active ( ) : active_win = win . get_name ( ) r...
def start ( self ) : """schedule to start the greenlet that runs this thread ' s function : raises : ` RuntimeError ` if the thread has already been started"""
if self . _started : raise RuntimeError ( "thread already started" ) def run ( ) : try : self . run ( * self . _args , ** self . _kwargs ) except SystemExit : # only shut down the thread , not the whole process pass finally : self . _deactivate ( ) self . _glet = scheduler . gree...
def copy_and_update ( dictionary , update ) : """Returns an updated copy of the dictionary without modifying the original"""
newdict = dictionary . copy ( ) newdict . update ( update ) return newdict
def replace_multiple_in_file ( filename : str , replacements : List [ Tuple [ str , str ] ] ) -> None : """Replaces multiple from / to string pairs within a single file . Args : filename : filename to process ( modifying it in place ) replacements : list of ` ` ( from _ text , to _ text ) ` ` tuples"""
with open ( filename ) as infile : contents = infile . read ( ) for text_from , text_to in replacements : log . info ( "Amending {}: {} -> {}" , filename , repr ( text_from ) , repr ( text_to ) ) contents = contents . replace ( text_from , text_to ) with open ( filename , 'w' ) as outfile : outfile . wr...
def _generate_struct_cstor ( self , struct ) : """Emits struct standard constructor ."""
with self . block_func ( func = self . _cstor_name_from_fields ( struct . all_fields ) , args = fmt_func_args_from_fields ( struct . all_fields ) , return_type = 'instancetype' ) : for field in struct . all_fields : self . _generate_validator ( field ) self . emit ( ) super_fields = [ f for f in str...
def get_param ( self , param ) : """. . todo : : docstring for get _ param"""
# Imports import os from . . const import EnumAnharmRepoParam from . . error import RepoError as RErr # Must be a valid parameter name if not param in EnumAnharmRepoParam : raise ValueError ( "'{0}' is not a valid " + "parameter enum value" . format ( param ) ) # # end if # Get the params group , complaining if rep...
def make_executable ( query ) : """make _ executable ( query ) - - give executable permissions to a given file"""
filename = support . get_file_name ( query ) if ( os . path . isfile ( filename ) ) : os . system ( 'chmod +x ' + filename ) else : print 'file not found'
def get_authn_contexts ( self ) : """Gets the authentication contexts : returns : The authentication classes for the SAML Response : rtype : list"""
authn_context_nodes = self . __query_assertion ( '/saml:AuthnStatement/saml:AuthnContext/saml:AuthnContextClassRef' ) return [ OneLogin_Saml2_Utils . element_text ( node ) for node in authn_context_nodes ]