signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
async def start_task ( self , task : Task ) -> None : '''Initialize the task , queue it for execution , add the done callback , and keep track of it for when tasks need to be stopped .'''
try : Log . debug ( 'task %s starting' , task . name ) before = time . time ( ) task . counters [ 'last_run' ] = before task . running = True self . running_tasks . add ( task ) await task . run_task ( ) Log . debug ( 'task %s completed' , task . name ) except CancelledError : Log . debu...
def df_routes ( self , value ) : '''. . versionadded : : 0.11.3'''
self . _df_routes = value try : self . emit ( 'routes-set' , self . _df_routes . copy ( ) ) except TypeError : pass
def generate_section_signatures ( self , pe , name , sig_length = 512 ) : """Generates signatures for all the sections in a PE file . If the section contains any data a signature will be created for it . The signature name will be a combination of the parameter ' name ' and the section number and its name .""...
section_signatures = list ( ) for idx , section in enumerate ( pe . sections ) : if section . SizeOfRawData < sig_length : continue # offset = pe . get _ offset _ from _ rva ( section . VirtualAddress ) offset = section . PointerToRawData sig_name = '%s Section(%d/%d,%s)' % ( name , idx + 1 , le...
def load_settings_file ( self , settings_file = None ) : """Load our settings file ."""
if not settings_file : settings_file = self . get_json_or_yaml_settings ( ) if not os . path . isfile ( settings_file ) : raise ClickException ( "Please configure your zappa_settings file or call `zappa init`." ) path , ext = os . path . splitext ( settings_file ) if ext == '.yml' or ext == '.yaml' : with o...
def RGB_color_picker ( obj ) : """Build a color representation from the string representation of an object This allows to quickly get a color from some data , with the additional benefit that the color will be the same as long as the ( string representation of the ) data is the same : : > > > from colour im...
# # Turn the input into a by 3 - dividable string . SHA - 384 is good because it # # divides into 3 components of the same size , which will be used to # # represent the RGB values of the color . digest = hashlib . sha384 ( str ( obj ) . encode ( 'utf-8' ) ) . hexdigest ( ) # # Split the digest into 3 sub - strings of ...
def kill_application ( self , app_id , user = "" ) : """Kill an application . Parameters app _ id : str The id of the application to kill . user : str , optional The user to kill the application as . Requires the current user to have permissions to proxy as ` ` user ` ` . Default is the current user .""...
self . _call ( 'kill' , proto . KillRequest ( id = app_id , user = user ) )
def enc ( self , byts , asscd = None ) : '''Encrypt the given bytes and return an envelope dict in msgpack form . Args : byts ( bytes ) : The message to be encrypted . asscd ( bytes ) : Extra data that needs to be authenticated ( but not encrypted ) . Returns : bytes : The encrypted message . This is a ms...
iv = os . urandom ( 16 ) encryptor = AESGCM ( self . ekey ) byts = encryptor . encrypt ( iv , byts , asscd ) envl = { 'iv' : iv , 'data' : byts , 'asscd' : asscd } return s_msgpack . en ( envl )
def histogram ( self , axis = None , ** kargs ) : """- histogram ( axis = None , * * kargs ) : It computes and shows the histogram of the image . This is usefull for choosing a proper scale to the output , or for clipping some values . If axis is None , it selects the current axis to plot the histogram . Keyw...
if ( axis == None ) : axis = plt . gca ( ) axis . hist ( self . __image . ravel ( ) , ** kargs )
def next_batch ( self , _ ) : "Handler for ' Next Batch ' button click . Delete all flagged images and renders next batch ."
for img_widget , delete_btn , fp , in self . _batch : fp = delete_btn . file_path if ( delete_btn . flagged_for_delete == True ) : self . delete_image ( fp ) self . _deleted_fns . append ( fp ) self . _all_images = self . _all_images [ self . _batch_size : ] self . empty_batch ( ) self . render ...
def get_job_asset_url ( self , job_id , filename ) : """Get details about the static assets collected for a specific job ."""
return 'https://saucelabs.com/rest/v1/{}/jobs/{}/assets/{}' . format ( self . client . sauce_username , job_id , filename )
def from_config ( cls , config : dict ) : """Create an event object from an event dictionary object . Args : config ( dict ) : Event Configuration dictionary ."""
timestamp = config . get ( 'timestamp' , None ) return cls ( config . get ( 'id' ) , config . get ( 'type' ) , config . get ( 'data' , dict ( ) ) , config . get ( 'origin' , None ) , timestamp , config . get ( 'object_type' , None ) , config . get ( 'object_id' , None ) , config . get ( 'object_key' , None ) )
def export_features ( self , delimiter = '\\' ) : """Export the features from this namespace as a list of feature tokens with the namespace name prepended ( delimited by ' delimiter ' ) . Example : > > > namespace = Namespace ( ' name1 ' , features = [ ' feature1 ' , ' feature2 ' ] ) > > > print namespace ....
result_list = [ ] for feature in self . features : result = '{}{}{}' . format ( self . name , delimiter , feature ) result_list . append ( result ) return result_list
def get_fields_class ( self , class_name ) : """Return all fields of a specific class : param class _ name : the class name : type class _ name : string : rtype : a list with : class : ` EncodedField ` objects"""
l = [ ] for i in self . get_classes ( ) : for j in i . get_fields ( ) : if class_name == j . get_class_name ( ) : l . append ( j ) return l
def get_unknown_barcodes ( self , lane_unknown_barcode ) : """Python 2 . * dictionaries are not sorted . This function return an ` OrderedDict ` sorted by barcode count ."""
try : sorted_barcodes = OrderedDict ( sorted ( lane_unknown_barcode . items ( ) , key = operator . itemgetter ( 1 ) , reverse = True ) ) except AttributeError : sorted_barcodes = None return sorted_barcodes
def cleanup ( self ) : """remove all members without reconfig"""
for item in self . server_map : self . member_del ( item , reconfig = False ) self . server_map . clear ( )
def get_init_container ( self , init_command , init_args , env_vars , context_mounts , persistence_outputs , persistence_data ) : """Pod init container for setting outputs path ."""
env_vars = to_list ( env_vars , check_none = True ) if self . original_name is not None and self . cloning_strategy == CloningStrategy . RESUME : return [ ] if self . original_name is not None and self . cloning_strategy == CloningStrategy . COPY : command = InitCommands . COPY original_outputs_path = store...
def hagen_poiseuille ( target , pore_area = 'pore.area' , throat_area = 'throat.area' , pore_viscosity = 'pore.viscosity' , throat_viscosity = 'throat.viscosity' , conduit_lengths = 'throat.conduit_lengths' , conduit_shape_factors = 'throat.flow_shape_factors' ) : r"""Calculate the hydraulic conductance of conduits...
return generic_conductance ( target = target , transport_type = 'flow' , pore_area = pore_area , throat_area = throat_area , pore_diffusivity = pore_viscosity , throat_diffusivity = throat_viscosity , conduit_lengths = conduit_lengths , conduit_shape_factors = conduit_shape_factors )
def _column_type ( strings , has_invisible = True ) : """The least generic type all column values are convertible to . > > > _ column _ type ( [ " 1 " , " 2 " ] ) is _ int _ type True > > > _ column _ type ( [ " 1 " , " 2.3 " ] ) is _ float _ type True > > > _ column _ type ( [ " 1 " , " 2.3 " , " four " ...
types = [ _type ( s , has_invisible ) for s in strings ] return reduce ( _more_generic , types , int )
def view_for_image_named ( image_name ) : """Create an ImageView for the given image ."""
image = resource . get_image ( image_name ) if not image : return None return ImageView ( pygame . Rect ( 0 , 0 , 0 , 0 ) , image )
def setup ( ) : """Creates shared and upload directory then fires setup to recipes ."""
init_tasks ( ) run_hook ( "before_setup" ) # Create shared folder env . run ( "mkdir -p %s" % ( paths . get_shared_path ( ) ) ) env . run ( "chmod 755 %s" % ( paths . get_shared_path ( ) ) ) # Create backup folder env . run ( "mkdir -p %s" % ( paths . get_backup_path ( ) ) ) env . run ( "chmod 750 %s" % ( paths . get_b...
def exists_course_list ( curriculum_abbr , course_number , section_id , quarter , year , joint = False ) : """Return True if the corresponding mailman list exists for the course"""
return exists ( get_course_list_name ( curriculum_abbr , course_number , section_id , quarter , year , joint ) )
def sub_for ( expr , substitutions ) : """Substitute subexpressions in ` expr ` with expression to expression mapping ` substitutions ` . Parameters expr : ibis . expr . types . Expr An Ibis expression substitutions : List [ Tuple [ ibis . expr . types . Expr , ibis . expr . types . Expr ] ] A mapping f...
mapping = { k . op ( ) : v for k , v in substitutions } substitutor = Substitutor ( ) return substitutor . substitute ( expr , mapping )
def calc_motif_enrichment ( sample , background , mtc = None , len_sample = None , len_back = None ) : """Calculate enrichment based on hypergeometric distribution"""
INF = "Inf" if mtc not in [ None , "Bonferroni" , "Benjamini-Hochberg" , "None" ] : raise RuntimeError ( "Unknown correction: %s" % mtc ) sig = { } p_value = { } n_sample = { } n_back = { } if not ( len_sample ) : len_sample = sample . seqn ( ) if not ( len_back ) : len_back = background . seqn ( ) for moti...
def get_properties ( self , packet , bt_addr ) : """Get properties of beacon depending on type ."""
if is_one_of ( packet , [ EddystoneTLMFrame , EddystoneURLFrame , EddystoneEncryptedTLMFrame , EddystoneEIDFrame ] ) : # here we retrieve the namespace and instance which corresponds to the # eddystone beacon with this bt address return self . properties_from_mapping ( bt_addr ) else : return packet . propertie...
def wgs84_to_utm ( lng , lat , utm_crs = None ) : """Convert WGS84 coordinates to UTM . If UTM CRS is not set it will be calculated automatically . : param lng : longitude in WGS84 system : type lng : float : param lat : latitude in WGS84 system : type lat : float : param utm _ crs : UTM coordinate refere...
if utm_crs is None : utm_crs = get_utm_crs ( lng , lat ) return transform_point ( ( lng , lat ) , CRS . WGS84 , utm_crs )
def energy_prof ( step ) : """Energy flux . This computation takes sphericity into account if necessary . Args : step ( : class : ` ~ stagpy . stagyydata . _ Step ` ) : a step of a StagyyData instance . Returns : tuple of : class : ` numpy . array ` : the energy flux and the radial position at which i...
diff , rad = diffs_prof ( step ) adv , _ = advts_prof ( step ) return ( diff + np . append ( adv , 0 ) ) , rad
def call_release ( self , arborted = False ) : """DEV : Must be call when the object becomes ready to read . Relesases the lock of _ wait _ non _ ressources"""
self . was_ended = arborted try : self . trigger . release ( ) except ( threading . ThreadError , AttributeError ) : pass
def dumps ( ms , single = False , pretty_print = False , ** kwargs ) : """Serialize an Xmrs object to the Prolog representation Args : ms : an iterator of Xmrs objects to serialize ( unless the * single * option is ` True ` ) single : if ` True ` , treat * ms * as a single Xmrs object instead of as an ite...
if single : ms = [ ms ] return serialize ( ms , pretty_print = pretty_print , ** kwargs )
def inherit ( name , objectType , clear_existing_acl = False ) : '''Ensure an object is inheriting ACLs from its parent'''
ret = { 'name' : name , 'result' : True , 'changes' : { } , 'comment' : '' } tRet = __salt__ [ 'win_dacl.check_inheritance' ] ( name , objectType ) if tRet [ 'result' ] : if not tRet [ 'Inheritance' ] : if __opts__ [ 'test' ] : ret [ 'result' ] = None ret [ 'changes' ] [ 'Inheritance...
def reg_add ( self , reg , value ) : """Add a value to a register . The value can be another : class : ` Register ` , an : class : ` Offset ` , a : class : ` Buffer ` , an integer or ` ` None ` ` . Arguments : reg ( pwnypack . shellcode . types . Register ) : The register to add the value to . value : The...
if value is None : return [ ] elif isinstance ( value , Register ) : return self . reg_add_reg ( reg , value ) elif isinstance ( value , ( Buffer , six . integer_types ) ) : if isinstance ( reg , Buffer ) : value = sum ( len ( v ) for v in six . iterkeys ( self . data ) ) + value . offset if not...
def _find_conferences ( self , year ) : """Retrieve the conferences and teams for the requested season . Find and retrieve all conferences for a given season and parse all of the teams that participated in the conference during that year . Conference information includes abbreviation and full name for the c...
if not year : year = utils . _find_year_for_season ( 'ncaaf' ) page = self . _pull_conference_page ( year ) if not page : output = ( "Can't pull requested conference page. Ensure the " "following URL exists: %s" % ( CONFERENCES_URL % year ) ) raise ValueError ( output ) conferences = page ( 'table#conferenc...
def rename_retract_ar_transition ( portal ) : """Renames retract _ ar transition to invalidate"""
logger . info ( "Renaming 'retract_ar' transition to 'invalidate'" ) wf_tool = api . get_tool ( "portal_workflow" ) workflow = wf_tool . getWorkflowById ( "bika_ar_workflow" ) if "invalidate" not in workflow . transitions : workflow . transitions . addTransition ( "invalidate" ) transition = workflow . transitions ...
def set_audiorenderer ( self , renderer ) : """Sets the SoundRenderer object . This should take care of processing the audioframes set in audioqueue . Parameters renderer : soundrenderers . SoundRenderer A subclass of soundrenderers . SoundRenderer that takes care of the audio rendering . Raises Runti...
if not hasattr ( self , 'audioqueue' ) or self . audioqueue is None : raise RuntimeError ( "No video has been loaded, or no audiostream " "was detected." ) if not isinstance ( renderer , SoundRenderer ) : raise TypeError ( "Invalid renderer object. Not a subclass of " "SoundRenderer" ) self . soundrenderer = re...
def copy ( self , deep = True ) : """Make a copy of this SparseDataFrame"""
result = super ( ) . copy ( deep = deep ) result . _default_fill_value = self . _default_fill_value result . _default_kind = self . _default_kind return result
def gen_random_name ( family_name = None , gender = None , length = None ) : """指定姓氏 、 性别 、 长度 , 返回随机人名 , 也可不指定生成随机人名 : param : * family _ name : ( string ) 姓 * gender : ( string ) 性别 " 01 " 男性 , " 00 " 女性 , 默认 None : 随机 * length : ( int ) 大于等于 2 小于等于 10 的整数 , 默认 None : 随机 2 或者 3 : return : * full _ nam...
family_word = ( "赵钱孙李周吴郑王冯陈褚卫蒋沈韩杨朱秦尤许何吕施张孔曹严华金魏陶姜戚谢邹喻柏水窦章云苏潘葛" "奚范彭郎鲁韦昌马苗凤花方俞任袁柳酆鲍史唐费廉岑薛雷贺倪汤滕殷罗毕郝邬安常乐于时傅皮卞齐康" "伍余元卜顾孟平黄和穆萧尹姚邵湛汪祁毛禹狄米贝明臧计伏成戴谈宋茅庞熊纪舒屈项祝董梁杜阮蓝闵" "席季麻强贾路娄危江童颜郭梅盛林刁钟徐邱骆高夏蔡田樊胡凌霍虞万支柯咎管卢莫经房裘缪干解应宗" "宣丁贲邓郁单杭洪包诸左石崔吉钮龚程嵇邢滑裴陆荣翁荀羊於惠甄魏加封芮羿储靳汲邴糜松井段富巫" "乌焦巴弓牧隗山谷车侯宓蓬全郗班仰秋仲伊宫宁仇栾暴甘钭厉戎祖武符刘姜詹束龙叶幸司韶郜黎蓟薄" "印宿白怀蒲台从鄂索咸籍赖卓蔺屠蒙池乔阴郁胥...
def write_file ( path : str , contents , mode : str = 'w' , retry_count : int = 3 , offset : int = 0 ) -> typing . Tuple [ bool , typing . Union [ None , Exception ] ] : """Writes the specified contents to a file , with retry attempts if the write operation fails . This is useful to prevent OS related write colli...
error = None for i in range ( retry_count ) : error = attempt_file_write ( path , contents , mode , offset ) if error is None : return True , None time . sleep ( 0.2 ) return False , error
def bvlpdu_contents ( self , use_dict = None , as_class = dict ) : """Return the contents of an object as a dict ."""
broadcast_distribution_table = [ ] for bdte in self . bvlciBDT : broadcast_distribution_table . append ( str ( bdte ) ) return key_value_contents ( use_dict = use_dict , as_class = as_class , key_values = ( ( 'function' , 'ReadBroadcastDistributionTableAck' ) , ( 'bdt' , broadcast_distribution_table ) , ) )
def add_review ( self , review ) : """Add a release object if it does not already exist"""
for r in self . reviews : if r . id == review . id : return self . reviews . append ( review )
def plot ( self , figure_list ) : '''When each subscript is called , uses its standard plotting Args : figure _ list : list of figures passed from the guit'''
# TODO : be smarter about how we plot ScriptIterator if self . _current_subscript_stage is not None : if self . _current_subscript_stage [ 'current_subscript' ] is not None : self . _current_subscript_stage [ 'current_subscript' ] . plot ( figure_list ) if ( self . is_running is False ) and not ( self . dat...
def bots_get ( self , bot ) : """Fetch and fill Bot object : param bot : empty bot object with name to search : type bot : Bot : rtype : Bot : return : filled bot object"""
data = self . client . bots . __getattr__ ( bot . name ) . __call__ ( ) return Bot ( data )
def get_all ( self , ** kwargs ) : """Get all keys currently stored in etcd . : param keys _ only : if True , retrieve only the keys , not the values : returns : sequence of ( value , metadata ) tuples"""
range_response = self . get_all_response ( ** kwargs ) for kv in range_response . kvs : yield ( kv . value , KVMetadata ( kv , range_response . header ) )
def start ( self ) -> None : """Start the internal control loop . Potentially blocking , depending on the value of ` _ run _ control _ loop ` set by the initializer ."""
self . _setup ( ) if self . _run_control_loop : asyncio . set_event_loop ( asyncio . new_event_loop ( ) ) self . _heartbeat_reciever . start ( ) self . _logger . info ( ' Start Loop' ) return self . loop . start ( ) else : self . _logger . debug ( ' run_control_loop == False' )
def make_timebar ( progress = 0 , duration = 0 ) : """Makes a new time bar string Args : progress : How far through the current song we are ( in seconds ) duration : The duration of the current song ( in seconds ) Returns : timebar ( str ) : The time bar string"""
duration_string = api_music . duration_to_string ( duration ) if duration <= 0 : return "---" time_counts = int ( round ( ( progress / duration ) * TIMEBAR_LENGTH ) ) if time_counts > TIMEBAR_LENGTH : time_counts = TIMEBAR_LENGTH if duration > 0 : bar = "│" + ( TIMEBAR_PCHAR * time_counts ) + ( TIMEBAR_ECHA...
def _init_norm ( self , weights ) : """Set the norm of the weight vector ."""
with tf . variable_scope ( "init_norm" ) : flat = tf . reshape ( weights , [ - 1 , self . layer_depth ] ) return tf . reshape ( tf . norm ( flat , axis = 0 ) , ( self . layer_depth , ) )
def remove_cpds ( self , * cpds ) : """Removes the cpds that are provided in the argument . Parameters * cpds : list , set , tuple ( array - like ) List of CPDs which are to be associated with the model . Each CPD should be an instance of ` TabularCPD ` . Examples > > > from pgmpy . models import Dynami...
for cpd in cpds : if isinstance ( cpd , ( tuple , list ) ) : cpd = self . get_cpds ( cpd ) self . cpds . remove ( cpd )
def add_basic_block ( self , basic_block ) : """Adds the given basic block in the function"""
assert ( isinstance ( basic_block , BasicBlock ) ) self . basic_block_list . append ( basic_block )
def _from_string ( cls , serialized ) : """Requests CourseLocator to deserialize its part and then adds the local deserialization of block"""
# Allow access to _ from _ string protected method course_key = CourseLocator . _from_string ( serialized ) # pylint : disable = protected - access parsed_parts = cls . parse_url ( serialized ) block_id = parsed_parts . get ( 'block_id' , None ) if block_id is None : raise InvalidKeyError ( cls , serialized ) retur...
def update_branding ( self , branding_id , params ) : """Update a existing branding @ branding _ id : Id of the branding to update @ params : Same params as method create _ branding , see above @ return : A dict with updated branding data"""
connection = Connection ( self . token ) connection . add_header ( 'Content-Type' , 'application/json' ) connection . set_url ( self . production , self . BRANDINGS_ID_URL % branding_id ) connection . add_params ( params ) return connection . patch_request ( )
async def find_deleted ( self , seq_set : SequenceSet , selected : SelectedMailbox ) -> Sequence [ int ] : """Return all the active message UIDs that have the ` ` \\ Deleted ` ` flag . Args : seq _ set : The sequence set of the possible messages . selected : The selected mailbox session ."""
session_flags = selected . session_flags return [ msg . uid async for _ , msg in self . find ( seq_set , selected ) if Deleted in msg . get_flags ( session_flags ) ]
def stop ( self ) : """Stops the service ."""
if self . log_file != PIPE and not ( self . log_file == DEVNULL and _HAS_NATIVE_DEVNULL ) : try : self . log_file . close ( ) except Exception : pass if self . process is None : return try : self . send_remote_shutdown_command ( ) except TypeError : pass try : if self . process :...
def add_item ( self , path , name , icon = None , url = None , order = None , permission = None , active_regex = None ) : """Add new menu item to menu : param path : Path of menu : param name : Display name : param icon : CSS icon : param url : link to page : param order : Sort order : param permission ...
if self . root_item is None : self . root_item = MenuItem ( 'ROOT' , 'ROOT' ) root_item = self . root_item current_path = '' for node in path . split ( '/' ) [ : - 1 ] : if not node : continue current_path = '/' + '{}/{}' . format ( current_path , node ) . strip ( '/' ) new_root = root_item . ch...
def login ( self , username , password ) : """Login to the TS3 Server @ param username : Username @ type username : str @ param password : Password @ type password : str"""
d = self . send_command ( 'login' , keys = { 'client_login_name' : username , 'client_login_password' : password } ) if d == 0 : self . _log . info ( 'Login Successful' ) return True return False
def _get_user ( self , user : Union [ User , str ] ) -> User : """Creates an User from an user _ id , if none , or fetch a cached User As all users are supposed to be in discovery room , its members dict is used for caching"""
user_id : str = getattr ( user , 'user_id' , user ) discovery_room = self . _global_rooms . get ( make_room_alias ( self . network_id , DISCOVERY_DEFAULT_ROOM ) , ) if discovery_room and user_id in discovery_room . _members : duser = discovery_room . _members [ user_id ] # if handed a User instance with display...
def _exec_loop ( self , a , bd_all , xyz , mask , n_withdrifts , spec_drift_grids ) : """Solves the kriging system by looping over all specified points . Less memory - intensive , but involves a Python - level loop ."""
npt = bd_all . shape [ 0 ] n = self . X_ADJUSTED . shape [ 0 ] kvalues = np . zeros ( npt ) sigmasq = np . zeros ( npt ) a_inv = scipy . linalg . inv ( a ) for j in np . nonzero ( ~ mask ) [ 0 ] : # Note that this is the same thing as range ( npt ) if mask is not defined , bd = bd_all [ j ] # otherwise it takes...
def bytes2human ( n : Union [ int , float ] , format : str = '%(value).1f %(symbol)s' , symbols : str = 'customary' ) -> str : """Converts a number of bytes into a human - readable format . From http : / / code . activestate . com / recipes / 578019 - bytes - to - human - human - to - bytes - converter / . Args...
# noqa n = int ( n ) if n < 0 : raise ValueError ( "n < 0" ) symbols = SYMBOLS [ symbols ] prefix = { } for i , s in enumerate ( symbols [ 1 : ] ) : prefix [ s ] = 1 << ( i + 1 ) * 10 for symbol in reversed ( symbols [ 1 : ] ) : if n >= prefix [ symbol ] : value = float ( n ) / prefix [ symbol ] ...
def canonicalization ( self , method , node ) : """Canonicalizes a node following the method : param method : Method identification : type method : str : param node : object to canonicalize : type node : str : return : Canonicalized node in a String"""
if method not in constants . TransformUsageC14NMethod : raise Exception ( 'Method not allowed: ' + method ) c14n_method = constants . TransformUsageC14NMethod [ method ] return etree . tostring ( node , method = c14n_method [ 'method' ] , with_comments = c14n_method [ 'comments' ] , exclusive = c14n_method [ 'exclu...
def get_slot ( handler_input , slot_name ) : # type : ( HandlerInput , str ) - > Optional [ Slot ] """Return the slot information from intent request . The method retrieves the slot information : py : class : ` ask _ sdk _ model . slot . Slot ` from the input intent request for the given ` ` slot _ name ` ` ....
request = handler_input . request_envelope . request if isinstance ( request , IntentRequest ) : if request . intent . slots is not None : return request . intent . slots . get ( slot_name , None ) else : return None raise TypeError ( "The provided request is not an IntentRequest" )
def add_reverse_arcs ( graph , capac = None ) : """Utility function for flow algorithms that need for every arc ( u , v ) , the existence of an ( v , u ) arc , by default with zero capacity . graph can be in adjacency list , possibly with capacity matrix capac . or graph can be in adjacency dictionary , then ...
for u in range ( len ( graph ) ) : for v in graph [ u ] : if u not in graph [ v ] : if type ( graph [ v ] ) is list : graph [ v ] . append ( u ) if capac : capac [ v ] [ u ] = 0 else : assert type ( graph [ v ] ) is ...
def _take_screenshot ( self , screenshot = False , name_prefix = 'unknown' ) : """This is different from _ save _ screenshot . The return value maybe None or the screenshot path Args : screenshot : bool or PIL image"""
if isinstance ( screenshot , bool ) : if not screenshot : return return self . _save_screenshot ( name_prefix = name_prefix ) if isinstance ( screenshot , Image . Image ) : return self . _save_screenshot ( screen = screenshot , name_prefix = name_prefix ) raise TypeError ( "invalid type for func _ta...
def edges2nodes ( edges ) : """gather the nodes from the edges"""
nodes = [ ] for e1 , e2 in edges : nodes . append ( e1 ) nodes . append ( e2 ) nodedict = dict ( [ ( n , None ) for n in nodes ] ) justnodes = list ( nodedict . keys ( ) ) # justnodes . sort ( ) justnodes = sorted ( justnodes , key = lambda x : str ( x [ 0 ] ) ) return justnodes
def _chooseBestSegmentPerCell ( cls , connections , cells , allMatchingSegments , potentialOverlaps ) : """For each specified cell , choose its matching segment with largest number of active potential synapses . When there ' s a tie , the first segment wins . @ param connections ( SparseMatrixConnections ) @ ...
candidateSegments = connections . filterSegmentsByCell ( allMatchingSegments , cells ) # Narrow it down to one pair per cell . onePerCellFilter = np2 . argmaxMulti ( potentialOverlaps [ candidateSegments ] , connections . mapSegmentsToCells ( candidateSegments ) ) learningSegments = candidateSegments [ onePerCellFilter...
def describe ( self , pid , vendorSpecific = None ) : """Note : If the server returns a status code other than 200 OK , a ServiceFailure will be raised , as this method is based on a HEAD request , which cannot carry exception information ."""
response = self . describeResponse ( pid , vendorSpecific = vendorSpecific ) return self . _read_header_response ( response )
def capture_moves ( self , position ) : """Finds out all possible capture moves : rtype : list"""
try : right_diagonal = self . square_in_front ( self . location . shift_right ( ) ) for move in self . _one_diagonal_capture_square ( right_diagonal , position ) : yield move except IndexError : pass try : left_diagonal = self . square_in_front ( self . location . shift_left ( ) ) for move i...
def read_input_file ( filename , sep = '\t' , noquote = False ) : """Reads a given inputfile ( tab delimited ) and returns a matrix ( list of list ) . arg : filename , the complete path to the inputfile to read"""
output = [ ] stream = None try : stream = open ( filename , 'r' ) for row in stream : row = row . strip ( ) if noquote : row = row . replace ( '"' , '' ) output . append ( row . split ( sep ) ) except IOError as err : # pragma : no cover LOG . info ( "Something wrong happ...
def rotateCD ( self , orient ) : """Rotates WCS CD matrix to new orientation given by ' orient '"""
# Determine where member CRVAL position falls in ref frame # Find out whether this needs to be rotated to align with # reference frame . _delta = self . get_orient ( ) - orient if _delta == 0. : return # Start by building the rotation matrix . . . _rot = fileutil . buildRotMatrix ( _delta ) # . . . then , rotate th...
def get_grist ( value ) : """Returns the grist of a string . If value is a sequence , does it for every value and returns the result as a sequence ."""
assert is_iterable_typed ( value , basestring ) or isinstance ( value , basestring ) def get_grist_one ( name ) : split = __re_grist_and_value . match ( name ) if not split : return '' else : return split . group ( 1 ) if isinstance ( value , str ) : return get_grist_one ( value ) else :...
import math def calculate_standard_deviation ( inputs ) : """Function to determine the standard deviation of a list of numbers . The standard deviation is calculated as the square root of the average of squared deviations from the mean . Examples : > > > calculate _ standard _ deviation ( [ 4 , 2 , 5 , 8 , ...
count_numbers = len ( inputs ) if count_numbers <= 1 : return 0.0 mean = sum ( inputs ) / count_numbers squared_deviations = [ ( x - mean ) ** 2 for x in inputs ] variance = sum ( squared_deviations ) / ( count_numbers - 1 ) return math . sqrt ( variance )
def get ( self , * args , ** kwargs ) : """Get an element from the iterable by an arg or kwarg . Args can be a single positional argument that is an index value to retrieve . If the specified index is out of range , None is returned . Otherwise use kwargs to provide a key / value . The key is expected to be...
if self : if args : index = args [ 0 ] if index <= len ( self ) - 1 : return self [ args [ 0 ] ] return None elif kwargs : key , value = kwargs . popitem ( ) for item in self . items : if getattr ( item , key , None ) == value : ret...
def save ( filepath , makedirs = True , title = u'IPyVolume Widget' , all_states = False , offline = False , scripts_path = 'js' , drop_defaults = False , template_options = ( ( "extra_script_head" , "" ) , ( "body_pre" , "" ) , ( "body_post" , "" ) ) , devmode = False , offline_cors = False , ) : """Save the curre...
ipyvolume . embed . embed_html ( filepath , current . container , makedirs = makedirs , title = title , all_states = all_states , offline = offline , scripts_path = scripts_path , drop_defaults = drop_defaults , template_options = template_options , devmode = devmode , offline_cors = offline_cors , )
def set_face_values ( self , front_face_value , side_face_value , top_face_value ) : """stub"""
if front_face_value is None or side_face_value is None or top_face_value is None : raise NullArgument ( ) self . add_integer_value ( value = int ( front_face_value ) , label = 'frontFaceValue' ) self . add_integer_value ( value = int ( side_face_value ) , label = 'sideFaceValue' ) self . add_integer_value ( value =...
def _process_json ( data ) : """return a list of GradPetition objects ."""
requests = [ ] for item in data : petition = GradPetition ( ) petition . description = item . get ( 'description' ) petition . submit_date = parse_datetime ( item . get ( 'submitDate' ) ) petition . decision_date = parse_datetime ( item . get ( 'decisionDate' ) ) if item . get ( 'deptRecommend' ) an...
def get_requirements ( * args ) : """Get requirements from pip requirement files ."""
requirements = set ( ) with open ( get_absolute_path ( * args ) ) as handle : for line in handle : # Strip comments . line = re . sub ( r'^#.*|\s#.*' , '' , line ) # Ignore empty lines if line and not line . isspace ( ) : requirements . add ( re . sub ( r'\s+' , '' , line ) ) ret...
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'normalized_text' ) and self . normalized_text is not None : _dict [ 'normalized_text' ] = self . normalized_text if hasattr ( self , 'start_time' ) and self . start_time is not None : _dict [ 'start_time' ] = self . start_time if hasattr ( self , 'end_time' ) and self . end_time...
def idx_sequence ( self ) : """Indices of sentences when enumerating data set from batches . Useful when retrieving the correct order of sentences Returns list List of ids ranging from 0 to # sent - 1"""
return [ x [ 1 ] for x in sorted ( zip ( self . _record , list ( range ( len ( self . _record ) ) ) ) ) ]
def _measure ( self , weighted ) : """_ BaseMeasure subclass representing primary measure for this cube . If the cube response includes a means measure , the return value is means . Otherwise it is counts , with the choice between weighted or unweighted determined by * weighted * . Note that weighted counts...
return ( self . _measures . means if self . _measures . means is not None else self . _measures . weighted_counts if weighted else self . _measures . unweighted_counts )
def script_exists ( self , digest , * digests ) : """Check existence of scripts in the script cache ."""
return self . execute ( b'SCRIPT' , b'EXISTS' , digest , * digests )
def getLCDType ( self ) : """Returns LCD type as a string , either monochrome or rgb"""
command = '$GE' settings = self . sendCommand ( command ) flags = int ( settings [ 2 ] , 16 ) if flags & 0x0100 : lcdtype = 'monochrome' else : lcdtype = 'rgb' return lcdtype
def p_preprocessor_line_line ( p ) : """preproc _ line : _ LINE INTEGER"""
p . lexer . lineno = int ( p [ 2 ] ) + p . lexer . lineno - p . lineno ( 2 )
def upsert ( cls , name , ** fields ) : """Insert or update an instance"""
instance = cls . get ( name ) if instance : instance . _set_fields ( fields ) else : instance = cls ( name = name , ** fields ) instance = failsafe_add ( cls . query . session , instance , name = name ) return instance
def setup_multiifo_interval_coinc_inj ( workflow , hdfbank , full_data_trig_files , inj_trig_files , stat_files , background_file , veto_file , veto_name , out_dir , pivot_ifo , fixed_ifo , tags = None ) : """This function sets up exact match multiifo coincidence for injections"""
if tags is None : tags = [ ] make_analysis_dir ( out_dir ) logging . info ( 'Setting up coincidence for injections' ) if len ( hdfbank ) != 1 : raise ValueError ( 'Must use exactly 1 bank file for this coincidence ' 'method, I got %i !' % len ( hdfbank ) ) hdfbank = hdfbank [ 0 ] # Wall time knob and memory kno...
def _randomized_hands ( ) : ''': return : 4 hands , obtained by shuffling the 28 dominoes used in this variation of the game , and distributing them evenly'''
all_dominoes = [ dominoes . Domino ( i , j ) for i in range ( 7 ) for j in range ( i , 7 ) ] random . shuffle ( all_dominoes ) return [ dominoes . Hand ( all_dominoes [ 0 : 7 ] ) , dominoes . Hand ( all_dominoes [ 7 : 14 ] ) , dominoes . Hand ( all_dominoes [ 14 : 21 ] ) , dominoes . Hand ( all_dominoes [ 21 : 28 ] ) ]
def get_completions ( self , candidates ) : """Given an iterable collection of block _ keys in the course , returns a mapping of the block _ keys to the present completion values of their associated blocks . If a completion is not found for a given block in the current course , 0.0 is returned . The service...
queryset = BlockCompletion . user_course_completion_queryset ( self . _user , self . _course_key ) . filter ( block_key__in = candidates ) completions = BlockCompletion . completion_by_block_key ( queryset ) candidates_with_runs = [ candidate . replace ( course_key = self . _course_key ) for candidate in candidates ] f...
def set_n ( self , value ) : '''setter'''
if isinstance ( value , int ) : self . __n = value else : raise TypeError ( "The type of n must be int." )
def get_mapping ( session , table , candidates , generator , key_map ) : """Generate map of keys and values for the candidate from the generator . : param session : The database session . : param table : The table we will be inserting into ( i . e . Feature or Label ) . : param candidates : The candidates to ...
for cand in candidates : # Grab the old values currently in the DB try : temp = session . query ( table ) . filter ( table . candidate_id == cand . id ) . one ( ) cand_map = dict ( zip ( temp . keys , temp . values ) ) except NoResultFound : cand_map = { } map_args = { "candidate_id"...
def check_key ( self , key , key_extra_len = 0 ) : """Checks sanity of key . Fails if : Key length is > SERVER _ MAX _ KEY _ LENGTH ( Raises MemcachedKeyLength ) . Contains control characters ( Raises MemcachedKeyCharacterError ) . Is not a string ( Raises MemcachedStringEncodingError ) Is an unicode string...
if isinstance ( key , tuple ) : key = key [ 1 ] if not key : raise Client . MemcachedKeyNoneError ( "Key is None" ) if isinstance ( key , unicode ) : raise Client . MemcachedStringEncodingError ( "Keys must be str()'s, not unicode. Convert your unicode " "strings using mystring.encode(charset)!" ) if not i...
def write ( url , content , ** args ) : """Put the object / collection into a file URL ."""
with HTTPResource ( url , ** args ) as resource : resource . write ( content )
def construct_headline ( need_data , app ) : """Constructs the node - structure for the headline / title container : param need _ data : need _ info container : return : node"""
# need title calculation title_type = '{}: ' . format ( need_data [ "type_name" ] ) title_headline = need_data [ "title" ] title_id = "{}" . format ( need_data [ "id" ] ) title_spacer = " " # need title node_type = nodes . inline ( title_type , title_type , classes = [ "needs-type" ] ) node_title = nodes . inline ( tit...
def arrayCast ( source , dtype ) : """Casts a NumPy array to the specified datatype , storing the copy in memory if there is sufficient available space or else using a memory - mapped temporary file to provide the underlying buffer ."""
# Determine the number of bytes required to store the array requiredBytes = _requiredSize ( source . shape , dtype ) # Determine if there is sufficient available memory vmem = psutil . virtual_memory ( ) if vmem . available > requiredBytes : return source . astype ( dtype , subok = False ) else : dest = arrayFa...
def add_service_group ( self , lb_id , allocation = 100 , port = 80 , routing_type = 2 , routing_method = 10 ) : """Adds a new service group to the load balancer . : param int loadbal _ id : The id of the loadbal where the service resides : param int allocation : percent of connections to allocate toward the ...
mask = 'virtualServers[serviceGroups[services[groupReferences]]]' load_balancer = self . lb_svc . getObject ( id = lb_id , mask = mask ) service_template = { 'port' : port , 'allocation' : allocation , 'serviceGroups' : [ { 'routingTypeId' : routing_type , 'routingMethodId' : routing_method } ] } load_balancer [ 'virtu...
def complete ( self ) : """Mark the task complete . > > > from pytodoist import todoist > > > user = todoist . login ( ' john . doe @ gmail . com ' , ' password ' ) > > > project = user . get _ project ( ' PyTodoist ' ) > > > task = project . add _ task ( ' Install PyTodoist ' ) > > > task . complete ( )"...
args = { 'id' : self . id } _perform_command ( self . project . owner , 'item_close' , args )
def get_balance ( self ) : """Retrieves the balance for the configured account"""
self . br . open ( self . MOBILE_WEB_URL % { 'accountno' : self . account } ) try : # Search for the existence of the Register link - indicating a new account self . br . find_link ( text = 'Register' ) raise InvalidAccountException except mechanize . LinkNotFoundError : pass self . br . follow_link ( text ...
def main ( ) : """Purge a single fastly url"""
parser = OptionParser ( description = "Purge a single url from fastly." ) parser . add_option ( "-k" , "--key" , dest = "apikey" , default = "" , help = "fastly api key" ) parser . add_option ( "-H" , "--host" , dest = "host" , help = "host to purge from" ) parser . add_option ( "-p" , "--path" , dest = "path" , help =...
def make_schema_from ( value , env ) : """Make a Schema object from the given spec . The input and output types of this function are super unclear , and are held together by ponies , wishes , duct tape , and a load of tests . See the comments for horrific entertainment ."""
# So this thing may not need to evaluate anything [ 0] if isinstance ( value , framework . Thunk ) : value = framework . eval ( value , env ) # We ' re a bit messy . In general , this has evaluated to a Schema object , but not necessarily : # for tuples and lists , we still need to treat the objects as specs . if i...
def check_url ( url ) : """Check whether the given URL is dead or alive . Returns a dict with four keys : " url " : The URL that was checked ( string ) " alive " : Whether the URL was working , True or False " status " : The HTTP status code of the response from the URL , e . g . 200 , 401 , 500 ( int ) ...
result = { "url" : url } try : response = requests . get ( url ) result [ "status" ] = response . status_code result [ "reason" ] = response . reason response . raise_for_status ( ) # Raise if status _ code is not OK . result [ "alive" ] = True except AttributeError as err : if err . message...
def clean_super_features ( self ) : """Removes any null & non - integer values from the super feature list"""
if self . super_features : self . super_features = [ int ( sf ) for sf in self . super_features if sf is not None and is_valid_digit ( sf ) ]
def delete_translations_for_item_and_its_children ( self , item , languages = None ) : """deletes the translations task of an item and its children used when a model is not enabled anymore : param item : : param languages : : return :"""
self . log ( '--- Deleting translations ---' ) if not self . master : self . set_master ( item ) object_name = '{} - {}' . format ( item . _meta . app_label . lower ( ) , item . _meta . verbose_name ) object_class = item . __class__ . __name__ object_pk = item . pk filter_by = { 'object_class' : object_class , 'obj...
def remove ( self , indices ) : """Remove the fragments corresponding to the given list of indices . : param indices : the list of indices to be removed : type indices : list of int : raises ValueError : if one of the indices is not valid"""
if not self . _is_valid_index ( indices ) : self . log_exc ( u"The given list of indices is not valid" , None , True , ValueError ) new_fragments = [ ] sorted_indices = sorted ( indices ) i = 0 j = 0 while ( i < len ( self ) ) and ( j < len ( sorted_indices ) ) : if i != sorted_indices [ j ] : new_fragm...
def unset_config_value ( self , name , quiet = False ) : """unset a configuration value Parameters name : the name of the value to unset ( remove key in dictionary ) quiet : disable verbose output if True ( default is False )"""
config_data = self . _read_config_file ( ) if name in config_data : del config_data [ name ] self . _write_config_file ( config_data ) if not quiet : self . print_config_value ( name , separator = ' is now set to: ' )
def setup_proxies_or_exit ( config : Dict [ str , Any ] , tokennetwork_registry_contract_address : str , secret_registry_contract_address : str , endpoint_registry_contract_address : str , user_deposit_contract_address : str , service_registry_contract_address : str , blockchain_service : BlockChainService , contracts ...
node_network_id = config [ 'chain_id' ] environment_type = config [ 'environment_type' ] contract_addresses_given = ( tokennetwork_registry_contract_address is not None and secret_registry_contract_address is not None and endpoint_registry_contract_address is not None ) if not contract_addresses_given and not bool ( co...
def _copy_scratch_to_state ( args : Dict [ str , Any ] ) : """Copes scratch shards to state shards ."""
np . copyto ( _state_shard ( args ) , _scratch_shard ( args ) )