signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def to_signed ( cls , type_ ) : """Return signed type or equivalent"""
if type_ in cls . unsigned : return { TYPE . ubyte : TYPE . byte_ , TYPE . uinteger : TYPE . integer , TYPE . ulong : TYPE . long_ } [ type_ ] if type_ in cls . decimals or type_ in cls . signed : return type_ return cls . unknown
def get_token ( username , password , server ) : """Retrieve token of TonicDNS API . Arguments : usename : TonicDNS API username password : TonicDNS API password server : TonicDNS API server"""
method = 'PUT' uri = 'https://' + server + '/authenticate' token = '' authinfo = { "username" : username , "password" : password , "local_user" : username } token = tonicdns_client ( uri , method , token , data = authinfo ) return token
def generate ( basename , xml ) : '''generate complete MAVLink CSharp implemenation'''
structsfilename = basename + '.generated.cs' msgs = [ ] enums = [ ] filelist = [ ] for x in xml : msgs . extend ( x . message ) enums . extend ( x . enum ) filelist . append ( os . path . basename ( x . filename ) ) for m in msgs : m . order_map = [ 0 ] * len ( m . fieldnames ) for i in range ( 0 , ...
def make_regression ( n_samples = 100 , n_features = 100 , n_informative = 10 , n_targets = 1 , bias = 0.0 , effective_rank = None , tail_strength = 0.5 , noise = 0.0 , shuffle = True , coef = False , random_state = None , chunks = None , ) : """Generate a random regression problem . The input set can either be w...
chunks = da . core . normalize_chunks ( chunks , ( n_samples , n_features ) ) _check_axis_partitioning ( chunks , n_features ) rng = sklearn . utils . check_random_state ( random_state ) return_coef = coef is True if chunks [ 1 ] [ 0 ] != n_features : raise ValueError ( "Can only generate arrays partitioned along t...
def hash ( self ) : ''': rtype : int : return : hash of the container'''
hashed = super ( ForEach , self ) . hash ( ) return khash ( hashed + self . _mutated_field . hash ( ) )
def last_in_date_group ( df , data_query_cutoff_times , assets , reindex = True , have_sids = True , extra_groupers = None ) : """Determine the last piece of information known on each date in the date index for each group . Input df MUST be sorted such that the correct last item is chosen from each group . Pa...
idx = [ data_query_cutoff_times [ data_query_cutoff_times . searchsorted ( df [ TS_FIELD_NAME ] . values , ) ] ] if have_sids : idx += [ SID_FIELD_NAME ] if extra_groupers is None : extra_groupers = [ ] idx += extra_groupers last_in_group = df . drop ( TS_FIELD_NAME , axis = 1 ) . groupby ( idx , sort = False ,...
def create ( cls , path ) : """Create a new repository"""
cmd = [ HG , 'init' , path ] subprocess . check_call ( cmd ) return cls ( path )
def main ( ) : '''Main routine .'''
# validate command line arguments arg_parser = argparse . ArgumentParser ( ) arg_parser . add_argument ( '--name' , '-n' , required = True , action = 'store' , help = 'Name of vmss' ) arg_parser . add_argument ( '--capacity' , '-c' , required = True , action = 'store' , help = 'Number of VMs' ) arg_parser . add_argumen...
def _run_exitfuncs ( ) : """run any registered exit functions _ exithandlers is traversed in reverse order so functions are executed last in , first out ."""
while _exithandlers : func , targs , kargs = _exithandlers . pop ( ) func ( * targs , ** kargs )
def open_url ( self , url , sleep_after_open = 2 ) : """Access a URL through ZAP ."""
self . zap . urlopen ( url ) # Give the sites tree a chance to get updated time . sleep ( sleep_after_open )
def replace_csi_driver ( self , name , body , ** kwargs ) : """replace the specified CSIDriver This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . replace _ csi _ driver ( name , body , async _ req = True ) > > ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . replace_csi_driver_with_http_info ( name , body , ** kwargs ) else : ( data ) = self . replace_csi_driver_with_http_info ( name , body , ** kwargs ) return data
def verify_user ( self ) : """start verify finger mode ( after capture ) : return : bool"""
command = const . CMD_STARTVERIFY cmd_response = self . __send_command ( command ) if cmd_response . get ( 'status' ) : return True else : raise ZKErrorResponse ( "Cant Verify" )
def get_open_spaces ( board ) : """Given a representation of the board , returns a list of open spaces ."""
open_spaces = [ ] for i in range ( 3 ) : for j in range ( 3 ) : if board [ i ] [ j ] == 0 : open_spaces . append ( encode_pos ( i , j ) ) return open_spaces
def validate_slashes ( param , value , minimum = 2 , maximum = None , form = None ) : """Ensure that parameter has slashes and minimum parts ."""
try : value = value . split ( "/" ) except ValueError : value = None if value : if len ( value ) < minimum : value = None elif maximum and len ( value ) > maximum : value = None if not value : form = form or "/" . join ( "VALUE" for _ in range ( minimum ) ) raise click . BadParam...
def fetch ( self , is_dl_forced = False ) : '''connection details for DISCO'''
cxn = { } cxn [ 'host' ] = 'nif-db.crbs.ucsd.edu' cxn [ 'database' ] = 'disco_crawler' cxn [ 'port' ] = '5432' cxn [ 'user' ] = config . get_config ( ) [ 'user' ] [ 'disco' ] cxn [ 'password' ] = config . get_config ( ) [ 'keys' ] [ cxn [ 'user' ] ] self . dataset . setFileAccessUrl ( 'jdbc:postgresql://' + cxn [ 'host...
async def runCmdLoop ( self ) : '''Run commands from a user in an interactive fashion until fini ( ) or EOFError is raised .'''
while not self . isfini : # FIXME completion self . cmdtask = None try : line = await self . prompt ( ) if not line : continue line = line . strip ( ) if not line : continue coro = self . runCmdLine ( line ) self . cmdtask = self . schedCor...
def relocate ( source , destination , move = False ) : """Adjust the virtual environment settings and optional move it . Args : source ( str ) : Path to the existing virtual environment . destination ( str ) : Desired path of the virtual environment . move ( bool ) : Whether or not to actually move the file...
venv = api . VirtualEnvironment ( source ) if not move : venv . relocate ( destination ) return None venv . move ( destination ) return None
def close ( self ) : """Close the node process ."""
if self . _closed : return False log . info ( "{module}: '{name}' [{id}]: is closing" . format ( module = self . manager . module_name , name = self . name , id = self . id ) ) if self . _console : self . _manager . port_manager . release_tcp_port ( self . _console , self . _project ) self . _console = None...
def add_keyword ( self , word , or_operator = False ) : """Adds a given string or list to the current keyword list : param word : String or list of at least 2 character long keyword ( s ) : param or _ operator : Boolean . Concatenates all elements of parameter word with ` ` OR ` ` . Is ignored is word is not a ...
if isinstance ( word , str if py3k else basestring ) and len ( word ) >= 2 : self . searchterms . append ( word if " " not in word else '"%s"' % word ) elif isinstance ( word , ( tuple , list ) ) : word = [ ( i if " " not in i else '"%s"' % i ) for i in word ] self . searchterms += [ " OR " . join ( word ) ...
def RRlist2bitmap ( lst ) : """Encode a list of integers representing Resource Records to a bitmap field used in the NSEC Resource Record ."""
# RFC 4034 , 4.1.2 . The Type Bit Maps Field import math bitmap = b"" lst = [ abs ( x ) for x in sorted ( set ( lst ) ) if x <= 65535 ] # number of window blocks max_window_blocks = int ( math . ceil ( lst [ - 1 ] / 256. ) ) min_window_blocks = int ( math . floor ( lst [ 0 ] / 256. ) ) if min_window_blocks == max_windo...
def aggregation_summary ( aggregate_hazard , aggregation ) : """Compute the summary from the aggregate hazard to the analysis layer . Source layer : | haz _ id | haz _ class | aggr _ id | aggr _ name | total _ feature | Target layer : | aggr _ id | aggr _ name | Output layer : | aggr _ id | aggr _ name ...
source_fields = aggregate_hazard . keywords [ 'inasafe_fields' ] target_fields = aggregation . keywords [ 'inasafe_fields' ] target_compulsory_fields = [ aggregation_id_field , aggregation_name_field , ] check_inputs ( target_compulsory_fields , target_fields ) # Missing exposure _ count _ field source_compulsory_field...
def replication_factor ( self , cluster = 'main' ) : """Return the replication factor for a cluster as an integer ."""
if not self . config . has_section ( cluster ) : raise SystemExit ( "Cluster '%s' not defined in %s" % ( cluster , self . config_file ) ) return int ( self . config . get ( cluster , 'replication_factor' ) )
def _normalize_status ( status ) : """Try to normalize the HAProxy status as one of the statuses defined in ` ALL _ STATUSES ` , if it can ' t be matched return the status as - is in a tag - friendly format ex : ' UP 1/2 ' - > ' up ' ' no check ' - > ' no _ check '"""
formatted_status = status . lower ( ) . replace ( " " , "_" ) for normalized_status in Services . ALL_STATUSES : if formatted_status . startswith ( normalized_status ) : return normalized_status return formatted_status
def _merge_map ( key , values , partial ) : """A map function used in merge phase . Stores ( key , values ) into KeyValues proto and yields its serialization . Args : key : values key . values : values themselves . partial : True if more values for this key will follow . False otherwise . Yields : The...
proto = kv_pb . KeyValues ( ) proto . set_key ( key ) proto . value_list ( ) . extend ( values ) yield proto . Encode ( )
def interesting ( self , args = None ) : """Gets interesting photos . flickr : ( credsfile ) , interesting"""
kwargs = { 'extras' : ',' . join ( args ) if args else 'last_update,geo,owner_name,url_sq' } return self . _paged_api_call ( self . flickr . interestingness_getList , kwargs )
def _add_scanvec ( self , mutinfo ) : """Internal method used to specify a scan vector . : param mutinfo : A tuple in the form of ` ( vbucket id , vbucket uuid , mutation sequence ) `"""
vb , uuid , seq , bktname = mutinfo self . _sv . setdefault ( bktname , { } ) [ vb ] = ( seq , str ( uuid ) )
def create_table ( cls ) : """create _ table Manually create a temporary table for model in test data base . : return :"""
schema_editor = getattr ( connection , 'schema_editor' , None ) if schema_editor : with schema_editor ( ) as schema_editor : schema_editor . create_model ( cls ) else : raw_sql , _ = connection . creation . sql_create_model ( cls , no_style ( ) , [ ] ) cls . delete_table ( ) cursor = connection ...
def encode_coin_link ( copper , silver = 0 , gold = 0 ) : """Encode a chat link for an amount of coins ."""
return encode_chat_link ( gw2api . TYPE_COIN , copper = copper , silver = silver , gold = gold )
def p_simple_list1 ( p ) : '''simple _ list1 : simple _ list1 AND _ AND newline _ list simple _ list1 | simple _ list1 OR _ OR newline _ list simple _ list1 | simple _ list1 AMPERSAND simple _ list1 | simple _ list1 SEMICOLON simple _ list1 | pipeline _ command'''
if len ( p ) == 2 : p [ 0 ] = [ p [ 1 ] ] else : p [ 0 ] = p [ 1 ] p [ 0 ] . append ( ast . node ( kind = 'operator' , op = p [ 2 ] , pos = p . lexspan ( 2 ) ) ) p [ 0 ] . extend ( p [ len ( p ) - 1 ] )
def email ( self , domains : Union [ tuple , list ] = None ) -> str : """Generate a random email . : param domains : List of custom domains for emails . : type domains : list or tuple : return : Email address . : Example : foretime10 @ live . com"""
if not domains : domains = EMAIL_DOMAINS domain = self . random . choice ( domains ) name = self . username ( template = 'ld' ) return '{name}{domain}' . format ( name = name , domain = domain , )
def __fix_args ( kwargs ) : """Set all named arguments shortcuts and flags ."""
kwargs . setdefault ( 'fixed_strings' , kwargs . get ( 'F' ) ) kwargs . setdefault ( 'basic_regexp' , kwargs . get ( 'G' ) ) kwargs . setdefault ( 'extended_regexp' , kwargs . get ( 'E' ) ) kwargs . setdefault ( 'ignore_case' , kwargs . get ( 'i' ) ) kwargs . setdefault ( 'invert' , kwargs . get ( 'v' ) ) kwargs . setd...
def _buildItemOrNone ( self , elem , cls = None , initpath = None ) : """Calls : func : ` ~ plexapi . base . PlexObject . _ buildItem ( ) ` but returns None if elem is an unknown type ."""
try : return self . _buildItem ( elem , cls , initpath ) except UnknownType : return None
def form_invalid ( self , form ) : """Processes an invalid form submittal . : param form : the form instance . : rtype : django . http . HttpResponse ."""
meta = getattr ( self . model , '_meta' ) # noinspection PyUnresolvedReferences messages . error ( self . request , _ ( u'The {0} could not be saved due to errors.' ) . format ( meta . verbose_name . lower ( ) ) ) return super ( BaseEditView , self ) . form_invalid ( form )
def perimeter ( self ) : """The total perimeter of the source segment , approximated lines through the centers of the border pixels using a 4 - connectivity . If any masked pixels make holes within the source segment , then the perimeter around the inner hole ( e . g . an annulus ) will also contribute to t...
if self . _is_completely_masked : return np . nan * u . pix # unit for table else : from skimage . measure import perimeter return perimeter ( ~ self . _total_mask , neighbourhood = 4 ) * u . pix
def applyStyleRules ( self ) : """Conditionally disabled / enables form fields based on the current section in the radio group"""
for button , widget in zip ( self . radioButtons , self . widgets ) : if isinstance ( widget , CheckBox ) : widget . hideInput ( ) if not button . GetValue ( ) : # not checked widget . widget . Disable ( ) else : widget . widget . Enable ( )
def _options_error ( cls , opt , objtype , backend , valid_options ) : """Generates an error message for an invalid option suggesting similar options through fuzzy matching ."""
current_backend = Store . current_backend loaded_backends = Store . loaded_backends ( ) kws = Keywords ( values = valid_options ) matches = sorted ( kws . fuzzy_match ( opt ) ) if backend is not None : if matches : raise ValueError ( 'Unexpected option %r for %s type ' 'when using the %r extension. Similar ...
def filter_query ( self , query , filter_info , model ) : """Filter query according to jsonapi 1.0 : param Query query : sqlalchemy query to sort : param filter _ info : filter information : type filter _ info : dict or None : param DeclarativeMeta model : an sqlalchemy model : return Query : the sorted q...
if filter_info : filters = create_filters ( model , filter_info , self . resource ) query = query . filter ( * filters ) return query
def type_check_cmd ( self , args , range = None ) : """Sets the flag to begin buffering typecheck notes & clears any stale notes before requesting a typecheck from the server"""
self . log . debug ( 'type_check_cmd: in' ) self . start_typechecking ( ) self . type_check ( "" ) self . editor . message ( 'typechecking' )
def is_connected ( T , directed = True ) : r"""Check connectivity of the transition matrix . Return true , if the input matrix is completely connected , effectively checking if the number of connected components equals one . Parameters T : scipy . sparse matrix Transition matrix directed : bool , option...
nc = connected_components ( T , directed = directed , connection = 'strong' , return_labels = False ) return nc == 1
def list_questions ( self ) : """[ deprecated ] 建議使用方法 ` get _ question ( ) `"""
# 取得新 API 的結果 data = self . get_question ( ) # 實作相容的結構 result = { } for number in data : # 繳交期限 deadline = data [ number ] [ 'deadline' ] # 是否已經過期限 expired = '期限已到' if data [ number ] [ 'expired' ] else '期限未到' # 是否繳交 status = '已繳' if data [ number ] [ 'status' ] else '未繳' # 程式語言種類 language =...
def writefits ( self , fname , clobber = True , trimzero = True , binned = True , hkeys = None ) : """Like : meth : ` pysynphot . spectrum . SourceSpectrum . writefits ` but with ` ` binned = True ` ` as default ."""
spectrum . CompositeSourceSpectrum . writefits ( self , fname , clobber = clobber , trimzero = trimzero , binned = binned , hkeys = hkeys )
def metaclass ( self ) : """Get a metaclass configured to use this registry ."""
if '_metaclass' not in self . __dict__ : self . _metaclass = type ( 'PermissionsMeta' , ( PermissionsMeta , ) , { 'registry' : self } ) return self . _metaclass
async def get_checkpoint_async ( self , partition_id ) : """Get the checkpoint data associated with the given partition . Could return null if no checkpoint has been created for that partition . : param partition _ id : The partition ID . : type partition _ id : str : return : Given partition checkpoint inf...
lease = await self . get_lease_async ( partition_id ) checkpoint = None if lease : if lease . offset : checkpoint = Checkpoint ( partition_id , lease . offset , lease . sequence_number ) return checkpoint
def updateItemData ( self , item , index ) : """Updates the item information from the tree . : param item | < XGanttWidgetItem > index | < int >"""
from projexui . widgets . xganttwidget . xganttwidgetitem import XGanttWidgetItem if not isinstance ( item , XGanttWidgetItem ) : return value = unwrapVariant ( item . data ( index , Qt . EditRole ) ) if type ( value ) == QDateTime : value = value . date ( ) item . setData ( index , Qt . EditRole , wrapVari...
def ev_to_image_number ( offset_us , source_to_detector_m , time_resolution_us , t_start_us , array ) : # delay values is normal 2.99 us with NONE actual MCP delay settings """convert energy ( eV ) to image numbers ( # ) Parameters : numpy array of energy in eV offset _ us : float . Delay of detector in us ...
time_tot_us = np . sqrt ( 81.787 / ( array * 1000 ) ) * source_to_detector_m * 100 / 0.3956 time_record_us = ( time_tot_us + offset_us ) image_number = ( time_record_us - t_start_us ) / time_resolution_us return image_number
def get_overs_summary ( self , match_key ) : """Calling Overs Summary API Arg : match _ key : key of the match Return : json data"""
overs_summary_url = self . api_path + "match/" + match_key + "/overs_summary/" response = self . get_response ( overs_summary_url ) return response
def _identify ( self , dataframe ) : """Returns a list of indexes containing only the points that pass the filter . Parameters dataframe : DataFrame"""
path = Path ( self . vert ) idx = path . contains_points ( dataframe . filter ( self . channels ) ) if self . region == 'out' : idx = ~ idx return idx
def adjust_weight ( self , stock_code , weight ) : """雪球组合调仓 , weight 为调整后的仓位比例 : param stock _ code : str 股票代码 : param weight : float 调整之后的持仓百分比 , 0 - 100 之间的浮点数"""
stock = self . _search_stock_info ( stock_code ) if stock is None : raise exceptions . TradeError ( u"没有查询要操作的股票信息" ) if stock [ "flag" ] != 1 : raise exceptions . TradeError ( u"未上市、停牌、涨跌停、退市的股票无法操作。" ) # 仓位比例向下取两位数 weight = round ( weight , 2 ) # 获取原有仓位信息 position_list = self . _get_position ( ) # 调整后的持仓 for ...
def VRRPNewMaster_originator_switch_info_switchIdentifier ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) VRRPNewMaster = ET . SubElement ( config , "VRRPNewMaster" , xmlns = "http://brocade.com/ns/brocade-notification-stream" ) originator_switch_info = ET . SubElement ( VRRPNewMaster , "originator-switch-info" ) switchIdentifier = ET . SubElement ( originator_switch_info , "switchIdentif...
def create ( self , active = False ) : """Creates a Partner and returns its handle , which is the reference that you have to use every time you refer to that Partner . : param active : 0 : returns : a pointer to the partner object"""
self . library . Par_Create . restype = snap7 . snap7types . S7Object self . pointer = snap7 . snap7types . S7Object ( self . library . Par_Create ( int ( active ) ) )
def MetaGraph ( self ) : """Return the metagraph definition , if there is one . Raises : ValueError : If there is no metagraph for this run . Returns : The ` meta _ graph _ def ` proto ."""
if self . _meta_graph is None : raise ValueError ( 'There is no metagraph in this EventAccumulator' ) meta_graph = meta_graph_pb2 . MetaGraphDef ( ) meta_graph . ParseFromString ( self . _meta_graph ) return meta_graph
def grant ( self , column = None , value = None , ** kwargs ) : """Provides various award , project , and grant personnel information . > > > GICS ( ) . grant ( ' project _ city _ name ' , ' San Francisco ' )"""
return self . _resolve_call ( 'GIC_GRANT' , column , value , ** kwargs )
def create ( self , group_view = False ) : """Update with current tools"""
self . add_handlers ( { '^T' : self . quit , '^Q' : self . quit } ) self . add ( npyscreen . TitleText , name = 'Select which tools to ' + self . action [ 'action' ] + ':' , editable = False ) togglable = [ 'remove' ] if self . action [ 'action_name' ] in togglable : self . cur_view = self . add ( npyscreen . Title...
def _write_header ( self ) : 'Writes the header to the underlying file object .'
header = b'scrypt' + CHR0 + struct . pack ( '>BII' , int ( math . log ( self . N , 2 ) ) , self . r , self . p ) + self . salt # Add the header checksum to the header checksum = hashlib . sha256 ( header ) . digest ( ) [ : 16 ] header += checksum # Add the header stream checksum self . _checksumer = hmac . new ( self ....
def exists_table_upgrades ( self ) : """Return if the upgrades table exists Returns bool True if the table exists False if the table don ' t exists"""
query = """ SELECT EXISTS ( SELECT 1 FROM information_schema.tables WHERE table_schema = '{}' AND table_name = '{}' ); """ . format ( self . upgrades_table [ : self . upgrades_table . index ( '.' ) ] , self . upgrades_table [ self . u...
def dump_db ( db , file , pretty = False , overwrite = False , verbose = True ) : """Dump : class : ` mongomock . database . Database ` to a local file . Only support ` ` * . json ` ` or ` ` * . gz ` ` ( compressed json file ) : param db : instance of : class : ` mongomock . database . Database ` . : param fi...
db_data = _dump ( db ) json . dump ( db_data , file , pretty = pretty , overwrite = overwrite , verbose = verbose , )
def parse_data ( self , response ) : """Convert the weird list format used for datapoints to a more usable dictionnary one : param response : dictionnary from API json response : type response : dict : returns : list of datapoints . . note : : Datapoint content : * time : UTC timestamp , unit : second...
parsed = [ ] try : items = response [ 'sensors' ] for datapoint in response [ 'datapoints' ] : line = { } for index , data in enumerate ( datapoint ) : line [ items [ index ] ] = data parsed . append ( line ) return parsed except ( KeyError , IndexError , TypeError ) : ...
def create ( model_config , batch_size , vectors = None ) : """Create an IMDB dataset"""
path = model_config . data_dir ( 'imdb' ) text_field = data . Field ( lower = True , tokenize = 'spacy' , batch_first = True ) label_field = data . LabelField ( is_target = True ) train_source , test_source = IMDBCached . splits ( root = path , text_field = text_field , label_field = label_field ) text_field . build_vo...
def send ( self , sender , ** named ) : """Send signal from sender to all connected receivers * only if * the signal ' s contents has changed . If any receiver raises an error , the error propagates back through send , terminating the dispatch loop , so it is quite possible to not have all receivers called ...
responses = [ ] if not self . receivers : return responses sender_id = _make_id ( sender ) if sender_id not in self . sender_status : self . sender_status [ sender_id ] = { } if self . sender_status [ sender_id ] == named : return responses self . sender_status [ sender_id ] = named for receiver in self . _...
def build ( installation : 'BugZoo' , container : Container ) -> 'CoverageExtractor' : """Constructs a CoverageExtractor for a given container using the coverage instructions provided by its accompanying bug description ."""
bug = installation . bugs [ container . bug ] # type : Bug instructions = bug . instructions_coverage if instructions is None : raise exceptions . NoCoverageInstructions name = instructions . __class__ . registered_under_name ( ) extractor_cls = _NAME_TO_EXTRACTOR [ name ] builder = extractor_cls . from_instruction...
def _fixSize ( self ) : """Fix the menu size . Commonly called when the font is changed"""
self . height = 0 for o in self . options : text = o [ 'label' ] font = o [ 'font' ] ren = font . render ( text , 1 , ( 0 , 0 , 0 ) ) if ren . get_width ( ) > self . width : self . width = ren . get_width ( ) self . height += font . get_height ( )
def transform ( self , stims , validation = 'strict' , * args , ** kwargs ) : '''Executes the transformation on the passed stim ( s ) . Args : stims ( str , Stim , list ) : One or more stimuli to process . Must be one of : - A string giving the path to a file that can be read in as a Stim ( e . g . , a . ...
if isinstance ( stims , string_types ) : stims = load_stims ( stims ) # If stims is a CompoundStim and the Transformer is expecting a single # input type , extract all matching stims if isinstance ( stims , CompoundStim ) and not isinstance ( self . _input_type , tuple ) : stims = stims . get_stim ( self . _inp...
def Popen ( * args , ** kwargs ) : """Executes a command using subprocess . Popen and redirects output to AETROS and stdout . Parses stdout as well for stdout API calls . Use read _ line argument to read stdout of command ' s stdout line by line . Use returned process stdin to communicate with the command . ...
read_line = None if 'read_line' in kwargs : read_line = kwargs [ 'read_line' ] del kwargs [ 'read_line' ] p = subprocess . Popen ( * args , ** kwargs ) wait_stdout = None wait_stderr = None if p . stdout : wait_stdout = sys . stdout . attach ( p . stdout , read_line = read_line ) if p . stderr : wait_st...
def vector_to_word ( vector ) : """Convert integer vectors to character vectors ."""
word = "" for vec in vector : word = word + int2char ( vec ) return word
def get_assessment_parts_for_assessment_part ( self , assessment_part_id ) : """Gets an ` ` AssessmentPart ` ` for the given assessment part . arg : assessment _ part _ id ( osid . id . Id ) : an assessment part ` ` Id ` ` return : ( osid . assessment . authoring . AssessmentPartList ) - the returned ` ` Asse...
# NOT IN SPEC - Implemented from # osid . assessment _ authoring . AssessmentPartLookupSession . additional _ methods # NOTE : This implementation currently ignores plenary view collection = JSONClientValidated ( 'assessment_authoring' , collection = 'AssessmentPart' , runtime = self . _runtime ) result = collection . ...
def get_authorize_url ( self , callback_url ) : """Returns the Authorize URL as returned by QB , and specified by OAuth 1.0a . : return URI :"""
self . authorize_url = self . authorize_url [ : self . authorize_url . find ( '?' ) ] if '?' in self . authorize_url else self . authorize_url qb_service = OAuth1Service ( consumer_key = self . consumer_key , consumer_secret = self . consumer_secret , request_token_url = self . request_token_url , access_token_url = se...
def tab ( tab_name , element_list = None , section_list = None ) : """Returns a dictionary representing a new tab to display elements . This can be thought of as a simple container for displaying multiple types of information . Args : tab _ name : The title to display element _ list : The list of elements...
_tab = { 'Type' : 'Tab' , 'Title' : tab_name , } if element_list is not None : if isinstance ( element_list , list ) : _tab [ 'Elements' ] = element_list else : _tab [ 'Elements' ] = [ element_list ] if section_list is not None : if isinstance ( section_list , list ) : _tab [ 'Sectio...
def commit ( self ) : """Insert the specified text in all selected lines , always at the same column position ."""
# Get the number of lines and columns in last line . last_line , last_col = self . qteWidget . getNumLinesAndColumns ( ) # If this is the first ever call to this undo / redo element # then backup the current cursor - and marker position because # both will be required for the redo operation . if self . cursorPos is Non...
def image_absoulte_path ( self , url , image ) : """if the image url does not start with ' http : / / ' it will take the absolute path from the url and fuses them with urljoin"""
if not re . match ( re_http , image ) : topimage = urljoin ( url , image ) return topimage return image
def modify_karma ( self , words ) : """Given a regex object , look through the groups and modify karma as necessary"""
# ' user ' : karma k = defaultdict ( int ) if words : # For loop through all of the group members for word_tuple in words : word = word_tuple [ 0 ] ending = word [ - 1 ] # This will either end with a - or + , if it ' s a - subract 1 # kara , if it ends with a + , add 1 karma ...
def trim_nones_from_right ( xs ) : """Returns the list without all the Nones at the right end . > > > trim _ nones _ from _ right ( [ 1 , 2 , None , 4 , None , 5 , None , None ] ) [1 , 2 , None , 4 , None , 5]"""
# Find the first element that does not contain none . for i , item in enumerate ( reversed ( xs ) ) : if item is not None : break return xs [ : - i ]
def generate_url ( self , suffix ) : """Return URL by combining server details with a path suffix ."""
url_base_path = os . path . dirname ( self . path ) netloc = "{}:{}" . format ( * self . server . server_address ) return urlunparse ( ( "http" , netloc , url_base_path + "/" + suffix , "" , "" , "" ) )
def T6 ( word , rules ) : '''If a VVV - sequence contains a long vowel , insert a syllable boundary between it and the third vowel . E . g . [ kor . ke . aa ] , [ yh . ti . öön ] , [ ruu . an ] , [ mää . yt . te ] .'''
offset = 0 try : WORD , rest = tuple ( word . split ( '.' , 1 ) ) for vvv in long_vowel_sequences ( rest ) : i = vvv . start ( 2 ) vvv = vvv . group ( 2 ) i += ( 2 if phon . is_long ( vvv [ : 2 ] ) else 1 ) + offset rest = rest [ : i ] + '.' + rest [ i : ] offset += 1 exc...
def train_image ( self ) : """Return the Docker image to use for training . The : meth : ` ~ sagemaker . estimator . EstimatorBase . fit ` method , which does the model training , calls this method to find the image to use for model training . Returns : str : The URI of the Docker image ."""
if self . image_name : return self . image_name else : return fw_utils . create_image_uri ( self . sagemaker_session . boto_region_name , self . _image_framework ( ) , self . train_instance_type , self . _image_version ( ) , py_version = PYTHON_VERSION )
def _resolve_argn ( macro , args ) : """Get argument from macro name ie : $ ARG3 $ - > args [ 2] : param macro : macro to parse : type macro : : param args : args given to command line : type args : : return : argument at position N - 1 in args table ( where N is the int parsed ) : rtype : None | str"...
# first , get the number of args _id = None matches = re . search ( r'ARG(?P<id>\d+)' , macro ) if matches is not None : _id = int ( matches . group ( 'id' ) ) - 1 try : return args [ _id ] except IndexError : # Required argument not found , returns an empty string return '' return ''
def _apply_single ( self , string ) : """Apply filter to single string"""
if string is None : return None result = self . regex . sub ( "" , string ) result = self . SPACES_REGEX . sub ( " " , result ) . strip ( ) return result
def cell_source ( cell ) : """Return the source of the current cell , as an array of lines"""
source = cell . source if source == '' : return [ '' ] if source . endswith ( '\n' ) : return source . splitlines ( ) + [ '' ] return source . splitlines ( )
def is_enabled ( self , feature_name ) : """Check for a particular feature by name Parameters feature _ name : str The name of a valid feature as string for example ' CUDA ' Returns Boolean True if it ' s enabled , False if it ' s disabled , RuntimeError if the feature is not known"""
feature_name = feature_name . upper ( ) if feature_name not in self : raise RuntimeError ( "Feature '{}' is unknown, known features are: {}" . format ( feature_name , list ( self . keys ( ) ) ) ) return self [ feature_name ] . enabled
def postcode ( anon , obj , field , val ) : """Generates a random postcode ( not necessarily valid , but it will look like one ) ."""
return anon . faker . postcode ( field = field )
def apply_pre_filters ( instance , html ) : """Perform optimizations in the HTML source code . : type instance : fluent _ contents . models . ContentItem : raise ValidationError : when one of the filters detects a problem ."""
# Allow pre processing . Typical use - case is HTML syntax correction . for post_func in appsettings . PRE_FILTER_FUNCTIONS : html = post_func ( instance , html ) return html
def remove_line ( self , section , line ) : """Remove all instances of a line . Returns : int : the number of lines removed"""
try : s = self . _get_section ( section , create = False ) except KeyError : # No such section , skip . return 0 return s . remove ( line )
def set_backend ( backend_name : str ) : """Sets backend ( local or aws )"""
global _backend , _backend_name _backend_name = backend_name assert not ncluster_globals . task_launched , "Not allowed to change backend after launching a task (this pattern is error-prone)" if backend_name == 'aws' : _backend = aws_backend elif backend_name == 'local' : _backend = local_backend else : ass...
def _set_default_cfg_profile ( self ) : """Set default network config profile . Check whether the default _ cfg _ profile value exist in the current version of DCNM . If not , set it to new default value which is supported by latest version ."""
try : cfgplist = self . config_profile_list ( ) if self . default_cfg_profile not in cfgplist : self . default_cfg_profile = ( 'defaultNetworkUniversalEfProfile' if self . _is_iplus else 'defaultNetworkIpv4EfProfile' ) except dexc . DfaClientRequestFailed : LOG . error ( "Failed to send request to D...
def call_sockeye_average ( model_dir : str , log_fname : str ) : """Call sockeye . average with reasonable defaults . : param model _ dir : Trained model directory . : param log _ fname : Location to write log file ."""
params_best_fname = os . path . join ( model_dir , C . PARAMS_BEST_NAME ) params_best_single_fname = os . path . join ( model_dir , PARAMS_BEST_SINGLE ) params_average_fname = os . path . join ( model_dir , PARAMS_AVERAGE ) command = [ sys . executable , "-m" , "sockeye.average" , "--metric={}" . format ( AVERAGE_METRI...
def read ( cls , filepath , validate = True ) : """Read torrent metainfo from file : param filepath : Path of the torrent file : param bool validate : Whether to run : meth : ` validate ` on the new Torrent object : raises ReadError : if reading from ` filepath ` fails : raises ParseError : if ` filepath ...
try : with open ( filepath , 'rb' ) as fh : return cls . read_stream ( fh ) except ( OSError , error . ReadError ) as e : raise error . ReadError ( e . errno , filepath ) except error . ParseError : raise error . ParseError ( filepath )
def xor_sum_pairs ( array : list , length : int ) -> int : """This Python function calculates the sum of XOR results from all possible pairs in an input list . Args : array : Input list of numbers . length : Length of the input list . Returns : The sum of XOR values from each possible pair in the list . ...
result = 0 for i in range ( 0 , length ) : for j in range ( ( i + 1 ) , length ) : result += ( array [ i ] ^ array [ j ] ) return result
def delete_event_view ( request , id ) : """Delete event page . You may only delete an event if you were the creator or you are an administrator . Confirmation page if not POST . id : event id"""
event = get_object_or_404 ( Event , id = id ) if not request . user . has_admin_permission ( 'events' ) : raise exceptions . PermissionDenied if request . method == "POST" : try : event . delete ( ) messages . success ( request , "Successfully deleted event." ) except Event . DoesNotExist : ...
def learn_response ( self , statement , previous_statement = None ) : """Learn that the statement provided is a valid response ."""
if not previous_statement : previous_statement = statement . in_response_to if not previous_statement : previous_statement = self . get_latest_response ( statement . conversation ) if previous_statement : previous_statement = previous_statement . text previous_statement_text = previous_statement if ...
def make_bf ( name , fields , basetype = c_uint32 , doc = None ) : """Create a new Bitfield class , correctly assigning the anonymous fields from the Union in order to get the desired behavior . Parameters : : name The name of the class . This is similar to the namedtuple recipe , in that you ' ll general...
# We need to hack on the fields array to get our integer sizes correct . unsigned_types = [ c_uint8 , c_uint16 , c_uint32 , c_uint64 ] signed_types = [ c_int8 , c_int16 , c_int32 , c_int64 ] unsigned = next ( t for t in unsigned_types if sizeof ( t ) >= sizeof ( basetype ) ) signed = next ( t for t in signed_types if s...
def ReadByte ( self , do_ord = True ) : """Read a single byte . Args : do _ ord ( bool ) : ( default True ) convert the byte to an ordinal first . Returns : bytes : a single byte if successful . 0 ( int ) if an exception occurred ."""
try : if do_ord : return ord ( self . stream . read ( 1 ) ) return self . stream . read ( 1 ) except Exception as e : logger . error ( "ord expected character but got none" ) return 0
def visit_Module ( self , node ) : """Turn globals assignment to functionDef and visit function defs ."""
module_body = list ( ) symbols = set ( ) # Gather top level assigned variables . for stmt in node . body : if isinstance ( stmt , ( ast . Import , ast . ImportFrom ) ) : for alias in stmt . names : name = alias . asname or alias . name symbols . add ( name ) # no warning ...
def _cache_update_needed ( self , course , taskid ) : """: param course : a Course object : param taskid : a ( valid ) task id : raise InvalidNameException , TaskNotFoundException : return : True if an update of the cache is needed , False else"""
if not id_checker ( taskid ) : raise InvalidNameException ( "Task with invalid name: " + taskid ) task_fs = self . get_task_fs ( course . get_id ( ) , taskid ) if ( course . get_id ( ) , taskid ) not in self . _cache : return True try : last_update , __ , __ = self . _get_last_updates ( course , taskid , ta...
def extract_version ( path ) : """Reads the file at the specified path and returns the version contained in it . This is meant for reading the _ _ init _ _ . py file inside a package , and so it expects a version field like : _ _ version _ _ = ' 1.0.0' : param path : path to the Python file : return : the...
# Regular expression for the version _version_re = re . compile ( r'__version__\s+=\s+(.*)' ) with open ( path + '__init__.py' , 'r' , encoding = 'utf-8' ) as f : version = f . read ( ) if version : version = _version_re . search ( version ) if version : version = version . group ( 1 ) versi...
def rescore ( self , only_if_higher ) : """Calculate a new raw score and save it to the block . If only _ if _ higher is True and the score didn ' t improve , keep the existing score . Raises a TypeError if the block cannot be scored . Raises a ValueError if the user has not yet completed the problem . May ...
_ = self . runtime . service ( self , 'i18n' ) . ugettext if not self . allows_rescore ( ) : raise TypeError ( _ ( 'Problem does not support rescoring: {}' ) . format ( self . location ) ) if not self . has_submitted_answer ( ) : raise ValueError ( _ ( 'Cannot rescore unanswered problem: {}' ) . format ( self ....
def str_to_datetime ( self , format = "%Y-%m-%dT%H:%M:%S%ZP" ) : """Create a new SArray with all the values cast to datetime . The string format is specified by the ' format ' parameter . Parameters format : str The string format of the input SArray . Default format is " % Y - % m - % dT % H : % M : % S % Z...
if ( self . dtype != str ) : raise TypeError ( "str_to_datetime expects SArray of str as input SArray" ) with cython_context ( ) : return SArray ( _proxy = self . __proxy__ . str_to_datetime ( format ) )
def merge_bed_by_name ( bt ) : """Merge intervals in a bed file when the intervals have the same name . Intervals with the same name must be adjacent in the bed file ."""
name_lines = dict ( ) for r in bt : name = r . name name_lines [ name ] = name_lines . get ( name , [ ] ) + [ [ r . chrom , r . start , r . end , r . name , r . strand ] ] new_lines = [ ] for name in name_lines . keys ( ) : new_lines += _merge_interval_list ( name_lines [ name ] ) new_lines = [ '\t' . join ...
def get_volume_pixeldata ( sorted_slices ) : """the slice and intercept calculation can cause the slices to have different dtypes we should get the correct dtype that can cover all of them : type sorted _ slices : list of slices : param sorted _ slices : sliced sored in the correct order to create volume"""
slices = [ ] combined_dtype = None for slice_ in sorted_slices : slice_data = _get_slice_pixeldata ( slice_ ) slice_data = slice_data [ numpy . newaxis , : , : ] slices . append ( slice_data ) if combined_dtype is None : combined_dtype = slice_data . dtype else : combined_dtype = num...
def write_result ( self , url_data ) : """Write url _ data . result ."""
self . write ( self . part ( "result" ) + self . spaces ( "result" ) ) if url_data . valid : color = self . colorvalid self . write ( _ ( "Valid" ) , color = color ) else : color = self . colorinvalid self . write ( _ ( "Error" ) , color = color ) if url_data . result : self . write ( u": " + url_da...
def revoke_user_access ( self , access_id ) : '''Takes an access _ id , probably obtained from the get _ access _ list structure , and revokes that access . No return value , but may raise ValueError .'''
path = "/api/v3/publisher/user/access/revoke" data = { 'api_token' : self . api_token , 'access_id' : access_id , } r = requests . get ( self . base_url + path , data = data ) if r . status_code != 200 : raise ValueError ( path + ":" + r . reason )
def drop_post ( self ) : """Remove . postXXXX postfix from version"""
post_index = self . version . find ( '.post' ) if post_index >= 0 : self . version = self . version [ : post_index ]