signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def launch_instance ( instance_name , command , existing_ip = None , cpu = 1 , mem = 4 , code_dir = None , setup_command = None ) : """Launch a GCE instance ."""
# Create instance ip = existing_ip or create_instance ( instance_name , cpu = cpu , mem = mem ) tf . logging . info ( "Waiting for SSH %s" , instance_name ) ready = wait_for_ssh ( ip ) if not ready : raise ValueError ( "Instance %s never ready for SSH" % instance_name ) # Copy code if code_dir : shell_run_with_...
def take ( self , num ) : """Take the first num elements of the RDD . It works by first scanning one partition , and use the results from that partition to estimate the number of additional partitions needed to satisfy the limit . Translated from the Scala implementation in RDD # take ( ) . . . note : : t...
items = [ ] totalParts = self . getNumPartitions ( ) partsScanned = 0 while len ( items ) < num and partsScanned < totalParts : # The number of partitions to try in this iteration . # It is ok for this number to be greater than totalParts because # we actually cap it at totalParts in runJob . numPartsToTry = 1 ...
def resolveSystem ( self , sysID ) : """Try to lookup the catalog resource for a system ID"""
ret = libxml2mod . xmlACatalogResolveSystem ( self . _o , sysID ) return ret
def task_verify ( self , task ) : '''return False if any of ' taskid ' , ' project ' , ' url ' is not in task dict or project in not in task _ queue'''
for each in ( 'taskid' , 'project' , 'url' , ) : if each not in task or not task [ each ] : logger . error ( '%s not in task: %.200r' , each , task ) return False if task [ 'project' ] not in self . projects : logger . error ( 'unknown project: %s' , task [ 'project' ] ) return False project...
def _surface_escape ( code , char ) : """Return * code * with * char * escaped as an HTML entity . The main use of this is to escape pipes ( ` ` | ` ` ) or equal signs ( ` ` = ` ` ) in parameter names or values so they are not mistaken for new parameters ."""
replacement = str ( HTMLEntity ( value = ord ( char ) ) ) for node in code . filter_text ( recursive = False ) : if char in node : code . replace ( node , node . replace ( char , replacement ) , False )
def get_function_help ( function : str , bel_spec : BELSpec ) : """Get function _ help given function name This will get the function summary template ( argument summary in signature ) and the argument help listing ."""
function_long = bel_spec [ "functions" ] [ "to_long" ] . get ( function ) function_help = [ ] if function_long : for signature in bel_spec [ "functions" ] [ "signatures" ] [ function_long ] [ "signatures" ] : function_help . append ( { "function_summary" : signature [ "argument_summary" ] , "argument_help" ...
def remove ( self , item ) : """Remove an attribute value to our object instance . : param str item : Application attribute name : raises : AttributeError"""
if item not in self . __dict__ [ self . ATTRIBUTES ] . keys ( ) : raise AttributeError ( '%s does not exist' % item ) delattr ( self , item )
def is_outlier ( df , item_id , segment_id , price ) : """Verify if a item is an outlier compared to the other occurrences of the same item , based on his price . Args : item _ id : idPlanilhaItens segment _ id : idSegmento price : VlUnitarioAprovado"""
if ( segment_id , item_id ) not in df . index : return False mean = df . loc [ ( segment_id , item_id ) ] [ 'mean' ] std = df . loc [ ( segment_id , item_id ) ] [ 'std' ] return gaussian_outlier . is_outlier ( x = price , mean = mean , standard_deviation = std )
def _process_gxd_allele_pair_view ( self , limit ) : """This assumes that the genotype and alleles have already been added to the id hashmap . We use the Genotype methods to add all the parts we need . Triples added : < genotype _ id > has _ part < vslc > < vslc > has _ part < allele1 > < vslc > has _ p...
if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) geno = Genotype ( graph ) line_counter = 0 raw = '/' . join ( ( self . rawdir , 'gxd_allelepair_view' ) ) LOG . info ( "processing allele pairs (VSLCs) for genotypes" ) geno_hash = { } with open ( raw , 'r' ) as f...
def create_pgm_dict ( lambdaFile : str , asts : List , file_name : str , mode_mapper_dict : dict , save_file = False , ) -> Dict : """Create a Python dict representing the PGM , with additional metadata for JSON output ."""
lambdaStrings = [ "import math\n\n" ] state = PGMState ( lambdaStrings ) generator = GrFNGenerator ( ) generator . mode_mapper = mode_mapper_dict pgm = generator . genPgm ( asts , state , { } , "" ) [ 0 ] if pgm . get ( "start" ) : pgm [ "start" ] = pgm [ "start" ] [ 0 ] else : pgm [ "start" ] = generator . fun...
def run ( self , data , store , signal , context , ** kwargs ) : """The main run method of the Python task . Args : data ( : class : ` . MultiTaskData ` ) : The data object that has been passed from the predecessor task . store ( : class : ` . DataStoreDocument ` ) : The persistent data store object that al...
params = self . params . eval ( data , store , exclude = [ 'command' ] ) capture_stdout = self . _callback_stdout is not None or params . capture_stdout capture_stderr = self . _callback_stderr is not None or params . capture_stderr stdout_file = TemporaryFile ( ) if params . capture_stdout else None stderr_file = Temp...
def get_signed_area ( self ) : """Return area of a simple ( ie . non - self - intersecting ) polygon . If verts wind anti - clockwise , this returns a negative number . Assume y - axis points up ."""
accum = 0.0 for i in range ( len ( self . verts ) ) : j = ( i + 1 ) % len ( self . verts ) accum += ( self . verts [ j ] [ 0 ] * self . verts [ i ] [ 1 ] - self . verts [ i ] [ 0 ] * self . verts [ j ] [ 1 ] ) return accum / 2
def dyld_image_suffix_search ( iterator , env = None ) : """For a potential path iterator , add DYLD _ IMAGE _ SUFFIX semantics"""
suffix = dyld_image_suffix ( env ) if suffix is None : return iterator def _inject ( iterator = iterator , suffix = suffix ) : for path in iterator : if path . endswith ( '.dylib' ) : yield path [ : - len ( '.dylib' ) ] + suffix + '.dylib' else : yield path + suffix ...
def to_internal_value ( self , data ) : """Dicts of native values < - Dicts of primitive datatypes ."""
if html . is_html_input ( data ) : data = html . parse_html_dict ( data ) if not isinstance ( data , dict ) : self . fail ( 'not_a_dict' , input_type = type ( data ) . __name__ ) return { six . text_type ( key ) : self . child . run_validation ( value ) for key , value in data . items ( ) }
def wiki_revert ( self , wiki_page_id , version_id ) : """Revert page to a previeous version ( Requires login ) ( UNTESTED ) . Parameters : wiki _ page _ id ( int ) : Where page _ id is the wiki page id . version _ id ( int ) :"""
return self . _get ( 'wiki_pages/{0}/revert.json' . format ( wiki_page_id ) , { 'version_id' : version_id } , method = 'PUT' , auth = True )
def set_scrollbars ( self ) : """Set to always have vertical scrollbar . Have horizontal scrollbar unless grid has very few rows . Older versions of wxPython will choke on this , in which case nothing happens ."""
try : if len ( self . row_labels ) < 5 : show_horizontal = wx . SHOW_SB_NEVER else : show_horizontal = wx . SHOW_SB_DEFAULT self . ShowScrollbars ( show_horizontal , wx . SHOW_SB_DEFAULT ) except AttributeError : pass
def create_and_wait_for_completion ( self , sql_query ) : """Creates a new batch SQL query and waits for its completion or failure Batch SQL jobs are asynchronous , once created this method automatically queries the job status until it ' s one of ' done ' , ' failed ' , ' canceled ' , ' unknown ' : param sq...
header = { 'content-type' : 'application/json' } data = self . send ( self . api_url , http_method = "POST" , json_body = { "query" : sql_query } , http_header = header ) warnings . warn ( 'Batch SQL job created with job_id: {job_id}' . format ( job_id = data [ 'job_id' ] ) ) while data and data [ 'status' ] in BATCH_J...
def execute ( self , operation , parameters = None , configuration = None ) : """Synchronously execute a SQL query . Blocks until results are available . Parameters operation : str The SQL query to execute . parameters : str , optional Parameters to be bound to variables in the SQL query , if any . Im...
# PEP 249 self . execute_async ( operation , parameters = parameters , configuration = configuration ) log . debug ( 'Waiting for query to finish' ) self . _wait_to_finish ( ) # make execute synchronous log . debug ( 'Query finished' )
def ISWAP ( q1 , q2 ) : """Produces an ISWAP gate : : ISWAP = [ [ 1 , 0 , 0 , 0 ] , [0 , 0 , 1j , 0 ] , [0 , 1j , 0 , 0 ] , [0 , 0 , 0 , 1 ] ] This gate swaps the state of two qubits , applying a - i phase to q1 when it is in the 1 state and a - i phase to q2 when it is in the 0 state . : param q1 : Q...
return Gate ( name = "ISWAP" , params = [ ] , qubits = [ unpack_qubit ( q ) for q in ( q1 , q2 ) ] )
def parse_instruction ( string , location , tokens ) : """Parse an x86 instruction ."""
prefix_str = tokens . get ( "prefix" , None ) mnemonic_str = tokens . get ( "mnemonic" ) operands = [ op for op in tokens . get ( "operands" , [ ] ) ] infer_operands_size ( operands ) # Quick hack : Capstone returns rep instead of repe for cmps and scas # instructions . if prefix_str == "rep" and ( mnemonic_str . start...
def urlopen ( link ) : """Return urllib2 urlopen"""
try : return urllib2 . urlopen ( link ) except urllib2 . URLError : pass except ValueError : return "" except KeyboardInterrupt : print ( "" ) raise SystemExit ( )
def reset ( self , route = None ) : '''Reset all routes ( force plugins to be re - applied ) and clear all caches . If an ID or route object is given , only that specific route is affected .'''
if route is None : routes = self . routes elif isinstance ( route , Route ) : routes = [ route ] else : routes = [ self . routes [ route ] ] for route in routes : route . reset ( ) if DEBUG : for route in routes : route . prepare ( ) self . hooks . trigger ( 'app_reset' )
def coredump_configured ( name , enabled , dump_ip , host_vnic = 'vmk0' , dump_port = 6500 ) : '''Ensures a host ' s core dump configuration . name Name of the state . enabled Sets whether or not ESXi core dump collection should be enabled . This is a boolean value set to ` ` True ` ` or ` ` False ` ` to ...
ret = { 'name' : name , 'result' : False , 'changes' : { } , 'comment' : '' } esxi_cmd = 'esxi.cmd' enabled_msg = 'ESXi requires that the core dump must be enabled ' 'before any other parameters may be set.' host = __pillar__ [ 'proxy' ] [ 'host' ] current_config = __salt__ [ esxi_cmd ] ( 'get_coredump_network_config' ...
def _deriv_growth ( z , ** cosmo ) : """Returns derivative of the linear growth factor at z for a given cosmology * * cosmo"""
inv_h = ( cosmo [ 'omega_M_0' ] * ( 1 + z ) ** 3 + cosmo [ 'omega_lambda_0' ] ) ** ( - 0.5 ) fz = ( 1 + z ) * inv_h ** 3 deriv_g = growthfactor ( z , norm = True , ** cosmo ) * ( inv_h ** 2 ) * 1.5 * cosmo [ 'omega_M_0' ] * ( 1 + z ) ** 2 - fz * growthfactor ( z , norm = True , ** cosmo ) / _int_growth ( z , ** cosmo )...
def generateSequences ( n = 2048 , w = 40 , sequenceLength = 5 , sequenceCount = 2 , sharedRange = None , seed = 42 ) : """Generate high order sequences using SequenceMachine"""
# Lots of room for noise sdrs patternAlphabetSize = 10 * ( sequenceLength * sequenceCount ) patternMachine = PatternMachine ( n , w , patternAlphabetSize , seed ) sequenceMachine = SequenceMachine ( patternMachine , seed ) numbers = sequenceMachine . generateNumbers ( sequenceCount , sequenceLength , sharedRange = shar...
def get_energy ( self ) : """Returns the consumed energy since the start of the statistics in Wh . Attention : Returns None if the value can ' t be queried or is unknown ."""
value = self . box . homeautoswitch ( "getswitchenergy" , self . actor_id ) return int ( value ) if value . isdigit ( ) else None
def FSkip ( params , ctxt , scope , stream , coord ) : """Returns 0 if successful or - 1 if the address is out of range"""
if len ( params ) != 1 : raise errors . InvalidArguments ( coord , "{} args" . format ( len ( params ) ) , "FSkip accepts only one argument" ) skip_amt = PYVAL ( params [ 0 ] ) pos = skip_amt + stream . tell ( ) return FSeek ( [ pos ] , ctxt , scope , stream , coord )
def doDirectPayment ( self , params ) : """Call PayPal DoDirectPayment method ."""
defaults = { "method" : "DoDirectPayment" , "paymentaction" : "Sale" } required = [ "creditcardtype" , "acct" , "expdate" , "cvv2" , "ipaddress" , "firstname" , "lastname" , "street" , "city" , "state" , "countrycode" , "zip" , "amt" , ] nvp_obj = self . _fetch ( params , required , defaults ) if nvp_obj . flag : r...
def file_saved_in_other_editorstack ( self , original_filename , filename ) : """File was just saved in another editorstack , let ' s synchronize ! This avoids file being automatically reloaded . The original filename is passed instead of an index in case the tabs on the editor stacks were moved and are now i...
index = self . has_filename ( original_filename ) if index is None : return finfo = self . data [ index ] finfo . newly_created = False finfo . filename = to_text_string ( filename ) finfo . lastmodified = QFileInfo ( finfo . filename ) . lastModified ( )
def __format_replace_metrics ( self , file , metrics ) : """Formats the given replace metrics and returns the matching rich html text . : param file : File . : type file : unicode : param metrics : Replace metrics to format . : type metrics : unicode : return : Rich text . : rtype : unicode"""
color = "rgb({0}, {1}, {2})" span_format = "<span style=\"color: {0};\">{{0}}</span>" . format ( color . format ( self . __default_line_color . red ( ) , self . __default_line_color . green ( ) , self . __default_line_color . blue ( ) ) ) dir_name , base_name = ( os . path . dirname ( file ) , os . path . basename ( fi...
def read_files ( path , verbose = True ) : """Read multiple ` ` CTfile ` ` formatted files . : param str path : Path to ` ` CTfile ` ` . : return : Subclass of : class : ` ~ ctfile . ctfile . CTfile ` . : rtype : : class : ` ~ ctfile . ctfile . CTfile `"""
for filehandle in filehandles ( path , verbose = verbose ) : yield CTfile . load ( filehandle )
def job_get_log ( object_id , input_params = { } , always_retry = False , ** kwargs ) : """Invokes the / job - xxxx / getLog API method . For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Applets - and - Entry - Points # API - method % 3A - % 2Fjob - xxxx % 2FgetLog"""
return DXHTTPRequest ( '/%s/getLog' % object_id , input_params , always_retry = always_retry , ** kwargs )
def render_css ( self , fn = None , text = None , margin = '' , indent = '\t' ) : """output css using the Sass processor"""
fn = fn or os . path . splitext ( self . fn ) [ 0 ] + '.css' if not os . path . exists ( os . path . dirname ( fn ) ) : os . makedirs ( os . path . dirname ( fn ) ) curdir = os . path . abspath ( os . curdir ) os . chdir ( os . path . dirname ( fn ) ) # needed in order for scss to relative @ import text = text or s...
def parse_host_port ( host_port ) : """Takes a string argument specifying host or host : port . Returns a ( hostname , port ) or ( ip _ address , port ) tuple . If no port is given , the second ( port ) element of the returned tuple will be None . host : port argument , for example , is accepted in the forms ...
host , port = None , None # default _s_ = host_port [ : ] if _s_ [ 0 ] == "[" : if "]" in host_port : host , _s_ = _s_ . lstrip ( "[" ) . rsplit ( "]" , 1 ) host = ipaddress . IPv6Address ( host ) . compressed if _s_ [ 0 ] == ":" : port = int ( _s_ . lstrip ( ":" ) ) else...
def close ( self ) : """Called by the main gui to close the containers . Called also when the container widget is closed Closed by clicking the window : goes through self . close _ slot Closed programmatically : use this method directly"""
if ( self . closed ) : return print ( self . pre , "close" ) for child in self . children : child . close ( ) self . openglthread = None self . gpu_handler = None self . closed = True self . window . unSetPropagate ( ) # we don ' t want the window to send the close signal . . which would call this * again * ( t...
def _import_api ( ) : '''Download https : / / < url > / pve - docs / api - viewer / apidoc . js Extract content of pveapi var ( json formated ) Load this json content into global variable " api "'''
global api full_url = 'https://{0}:{1}/pve-docs/api-viewer/apidoc.js' . format ( url , port ) returned_data = requests . get ( full_url , verify = verify_ssl ) re_filter = re . compile ( '(?<=pveapi =)(.*)(?=^;)' , re . DOTALL | re . MULTILINE ) api_json = re_filter . findall ( returned_data . text ) [ 0 ] api = salt ....
def hold ( name = None , pkgs = None , ** kwargs ) : '''Add a package lock . Specify packages to lock by exact name . root operate on a different root directory . CLI Example : . . code - block : : bash salt ' * ' pkg . add _ lock < package name > salt ' * ' pkg . add _ lock < package1 > , < package2 > ...
ret = { } root = kwargs . get ( 'root' ) if ( not name and not pkgs ) or ( name and pkgs ) : raise CommandExecutionError ( 'Name or packages must be specified.' ) elif name : pkgs = [ name ] locks = list_locks ( root = root ) added = [ ] try : pkgs = list ( __salt__ [ 'pkg_resource.parse_targets' ] ( pkgs )...
def __pop_top_frame ( self ) : """Pops the top frame off the frame stack ."""
popped = self . __stack . pop ( ) if self . __stack : self . __stack [ - 1 ] . process_subframe ( popped )
def handleOneNodeMsg ( self , wrappedMsg ) : """Validate and process one message from a node . : param wrappedMsg : Tuple of message and the name of the node that sent the message"""
try : vmsg = self . validateNodeMsg ( wrappedMsg ) if vmsg : logger . trace ( "{} msg validated {}" . format ( self , wrappedMsg ) , extra = { "tags" : [ "node-msg-validation" ] } ) self . unpackNodeMsg ( * vmsg ) else : logger . debug ( "{} invalidated msg {}" . format ( self , wrap...
def get_formatted_as_type ( self , value , default = None , out_type = str ) : """Return formatted value for input value , returns as out _ type . Caveat emptor : if out _ type is bool and value a string , return will be True if str is ' True ' . It will be False for all other cases . Args : value : the v...
if value is None : value = default if isinstance ( value , SpecialTagDirective ) : result = value . get_value ( self ) return types . cast_to_type ( result , out_type ) if isinstance ( value , str ) : result = self . get_formatted_string ( value ) result_type = type ( result ) if out_type is res...
def translate_path ( self , dep_file , dep_rule ) : """Translate dep _ file from dep _ rule into this rule ' s output path ."""
dst_base = dep_file . split ( os . path . join ( dep_rule . address . repo , dep_rule . address . path ) , 1 ) [ - 1 ] if self . params [ 'strip_prefix' ] : dst_base = dep_file . split ( self . params [ 'strip_prefix' ] , 1 ) [ - 1 ] return os . path . join ( self . address . repo , self . address . path , self . p...
def isdefined ( obj , force_import = False , namespace = None ) : """Return True if object is defined in namespace If namespace is None - - > namespace = locals ( )"""
if namespace is None : namespace = locals ( ) attr_list = obj . split ( '.' ) base = attr_list . pop ( 0 ) if len ( base ) == 0 : return False if base not in builtins . __dict__ and base not in namespace : if force_import : try : module = __import__ ( base , globals ( ) , namespace ) ...
def create_events ( self , kwargs_list ) : """Create events in bulk to save on queries . Each element in the kwargs list should be a dict with the same set of arguments you would normally pass to create _ event : param kwargs _ list : list of kwargs dicts : return : list of Event"""
# Build map of uuid to event info uuid_map = { kwargs . get ( 'uuid' , '' ) : { 'actors' : kwargs . pop ( 'actors' , [ ] ) , 'ignore_duplicates' : kwargs . pop ( 'ignore_duplicates' , False ) , 'event_kwargs' : kwargs } for kwargs in kwargs_list } # Check for uuids uuid_set = set ( Event . objects . filter ( uuid__in =...
def converts_to_proto ( value , msg , raise_err = False ) : """Boolean response if a dictionary can convert into the proto ' s schema : param value : < dict > : param msg : < proto object > : param raise _ err : < bool > ( default false ) raise for troubleshooting : return : < bool > whether the dict can co...
result = True try : dict_to_protobuf . dict_to_protobuf ( value , msg ) except TypeError as type_error : if raise_err : raise type_error result = False return result
def partitions ( self ) : """: class : ` ~ zhmcclient . PartitionManager ` : Access to the : term : ` Partitions < Partition > ` in this CPC ."""
# We do here some lazy loading . if not self . _partitions : self . _partitions = PartitionManager ( self ) return self . _partitions
def created ( self , data , schema = None , envelope = None ) : """Gets a 201 response with the specified data . : param data : The content value . : param schema : The schema to serialize the data . : param envelope : The key used to envelope the data . : return : A Flask response object ."""
data = marshal ( data , schema , envelope ) return self . __make_response ( ( data , 201 ) )
def parse ( self , limit = None ) : """Override Source . parse ( ) Args : : param limit ( int , optional ) limit the number of rows processed Returns : : return None"""
if limit is not None : LOG . info ( "Only parsing first %d rows" , limit ) rgd_file = '/' . join ( ( self . rawdir , self . files [ 'rat_gene2mammalian_phenotype' ] [ 'file' ] ) ) # ontobio gafparser implemented here p = GafParser ( ) assocs = p . parse ( open ( rgd_file , "r" ) ) for i , assoc in enumerate ( assoc...
def _get_const_info ( const_index , const_list ) : """Helper to get optional details about const references Returns the dereferenced constant and its repr if the constant list is defined . Otherwise returns the constant index and its repr ( ) ."""
argval = const_index if const_list is not None : argval = const_list [ const_index ] # float values nan and inf are not directly representable in Python at least # before 3.5 and even there it is via a library constant . # So we will canonicalize their representation as float ( ' nan ' ) and float ( ' inf ' ) if is...
def requirements ( ) : """Build the requirements list for this project"""
requirements_list = [ ] with open ( 'requirements.txt' ) as requirements : for install in requirements : requirements_list . append ( install . strip ( ) ) return requirements_list
def list_vmss_skus ( access_token , subscription_id , resource_group , vmss_name ) : '''List the VM skus available for a VM Scale Set . Args : access _ token ( str ) : A valid Azure authentication token . subscription _ id ( str ) : Azure subscription id . resource _ group ( str ) : Azure resource group nam...
endpoint = '' . join ( [ get_rm_endpoint ( ) , '/subscriptions/' , subscription_id , '/resourceGroups/' , resource_group , '/providers/Microsoft.Compute/virtualMachineScaleSets/' , vmss_name , '/skus' , '?api-version=' , COMP_API ] ) return do_get_next ( endpoint , access_token )
def check_model ( self ) : """Check the model for various errors . This method checks for the following errors - * Checks if the cardinalities of all the variables are consistent across all the factors . * Factors are defined for all the random variables . Returns check : boolean True if all the checks ...
cardinalities = self . get_cardinality ( ) for factor in self . factors : for variable , cardinality in zip ( factor . scope ( ) , factor . cardinality ) : if cardinalities [ variable ] != cardinality : raise ValueError ( 'Cardinality of variable {var} not matching among factors' . format ( var ...
def read_node_label_matrix ( file_path , separator , numbering = "matlab" ) : """Reads node - label pairs in csv format and returns a list of tuples and a node - label matrix . Inputs : - file _ path : The path where the node - label matrix is stored . - separator : The delimiter among values ( e . g . " , " , ...
# Open file file_row_generator = get_file_row_generator ( file_path , separator ) file_row = next ( file_row_generator ) number_of_rows = file_row [ 1 ] number_of_categories = int ( file_row [ 3 ] ) # Initialize lists for row and column sparse matrix arguments row = list ( ) col = list ( ) append_row = row . append app...
def copyfileobj ( fsrc , fdst , length = 16 * 1024 ) : """copy data from file - like object fsrc to file - like object fdst"""
while 1 : buf = fsrc . read ( length ) if not buf : break fdst . write ( buf )
def simxGetDialogInput ( clientID , dialogHandle , operationMode ) : '''Please have a look at the function description / documentation in the V - REP user manual'''
inputText = ct . POINTER ( ct . c_char ) ( ) ret = c_GetDialogInput ( clientID , dialogHandle , ct . byref ( inputText ) , operationMode ) a = bytearray ( ) if ret == 0 : i = 0 while inputText [ i ] != b'\0' : if sys . version_info [ 0 ] == 3 : a . append ( int . from_bytes ( inputText [ i ]...
def flat_map ( self , flatmap_fn ) : """Applies a flatmap operator to the stream . Attributes : flatmap _ fn ( function ) : The user - defined logic of the flatmap ( e . g . split ( ) ) ."""
op = Operator ( _generate_uuid ( ) , OpType . FlatMap , "FlatMap" , flatmap_fn , num_instances = self . env . config . parallelism ) return self . __register ( op )
def msg_timeout ( self , msg_timeout_ms ) : """msg _ timeout ( nsqd 0.2.28 + ) configure the server - side message timeout for messages delivered to this client ."""
assert issubclass ( msg_timeout_ms . __class__ , int ) return self . __push ( 'msg_timeout' , msg_timeout_ms )
def convert_rtc ( cls , timestamp ) : """Convert a number of seconds since 1/1/2000 to UTC time ."""
if timestamp & ( 1 << 31 ) : timestamp &= ~ ( 1 << 31 ) delta = datetime . timedelta ( seconds = timestamp ) return cls . _Y2KReference + delta
def do_ls ( self , params ) : """\x1b [1mNAME \x1b [0m ls - Lists the znodes for the given < path > \x1b [1mSYNOPSIS \x1b [0m ls < path > [ watch ] [ sep ] \x1b [1mOPTIONS \x1b [0m * watch : set a ( child ) watch on the path ( default : false ) * sep : separator to be used ( default : ' \\ n ' ) \x1b ...
watcher = lambda evt : self . show_output ( str ( evt ) ) kwargs = { "watch" : watcher } if params . watch else { } znodes = self . _zk . get_children ( params . path , ** kwargs ) self . show_output ( params . sep . join ( sorted ( znodes ) ) )
def eval_set ( self , evals , iteration = 0 , feval = None ) : # pylint : disable = invalid - name """Evaluate a set of data . Parameters evals : list of tuples ( DMatrix , string ) List of items to be evaluated . iteration : int Current iteration . feval : function Custom evaluation function . Retu...
if feval is None : for d in evals : if not isinstance ( d [ 0 ] , DMatrix ) : raise TypeError ( 'expected DMatrix, got {}' . format ( type ( d [ 0 ] ) . __name__ ) ) if not isinstance ( d [ 1 ] , STRING_TYPES ) : raise TypeError ( 'expected string, got {}' . format ( type ( d...
def set_highest_numeric_score ( self , score ) : """Sets the highest numeric score . arg : score ( decimal ) : the highest numeric score raise : InvalidArgument - ` ` score ` ` is invalid raise : NoAccess - ` ` score ` ` cannot be modified * compliance : mandatory - - This method must be implemented . *"""
# Implemented from template for osid . grading . GradeSystemForm . set _ lowest _ numeric _ score if self . get_highest_numeric_score_metadata ( ) . is_read_only ( ) : raise errors . NoAccess ( ) try : score = float ( score ) except ValueError : raise errors . InvalidArgument ( ) if not self . _is_valid_dec...
def get_volume ( self , controller , zone ) : """Gets the volume level which needs to be doubled to get it to the range of 0 . . 100 - it is located on a 2 byte offset"""
volume_level = self . get_zone_info ( controller , zone , 2 ) if volume_level is not None : volume_level *= 2 return volume_level
def _users_from_environ ( env_prefix = '' ) : """Environment value via ` user : password | user2 : password2 `"""
auth_string = os . environ . get ( env_prefix + 'WSGI_AUTH_CREDENTIALS' ) if not auth_string : return { } result = { } for credentials in auth_string . split ( '|' ) : username , password = credentials . split ( ':' , 1 ) result [ username ] = password return result
def check_returncode ( p , out ) : """Raise exception according to unrar exit code ."""
code = p . returncode if code == 0 : return # map return code to exception class , codes from rar . txt errmap = [ None , RarWarning , RarFatalError , RarCRCError , RarLockedArchiveError , # 1 . . 4 RarWriteError , RarOpenError , RarUserError , RarMemoryError , # 5 . . 8 RarCreateError , RarNoFilesError , RarWrongP...
def togglePopup ( self ) : """Toggles whether or not the popup is visible ."""
if not self . _popupWidget . isVisible ( ) : self . showPopup ( ) elif self . _popupWidget . currentMode ( ) != self . _popupWidget . Mode . Dialog : self . _popupWidget . close ( )
def _add_length_constrain ( token_lst : List [ Dict ] , lengths : List ) -> List [ Dict ] : """Add length constrain for some token type , create cross production Args : token _ lst : List [ Dict ] lengths : List Returns : List [ Dict ]"""
result = [ ] for a_token in token_lst : for length in lengths : if type ( length ) == str and length and length . isdigit ( ) : a_token [ attrs . LENGTH ] = int ( length ) result . append ( copy . deepcopy ( a_token ) ) elif type ( length ) == int : a_token [ attr...
def from_dict ( event_dict ) : """Create a SnippetEvent object from a dictionary . Args : event _ dict : a dictionary representing an event . Returns : A SnippetEvent object ."""
return SnippetEvent ( callback_id = event_dict [ 'callbackId' ] , name = event_dict [ 'name' ] , creation_time = event_dict [ 'time' ] , data = event_dict [ 'data' ] )
def vsh ( cmd , * args , ** kw ) : """Execute a command installed into the active virtualenv ."""
args = '" "' . join ( i . replace ( '"' , r'\"' ) for i in args ) easy . sh ( '"%s" "%s"' % ( venv_bin ( cmd ) , args ) )
def topic_coupling ( model , threshold = None , ** kwargs ) : """Two papers are coupled if they both contain a shared topic above a ` ` threshold ` ` . Parameters model : : class : ` . LDAModel ` threshold : float Default : ` ` 3 . / model . Z ` ` kwargs : kwargs Passed on to : func : ` . coupling ` \...
if not threshold : threshold = 3. / model . Z select = lambda f , v , c , dc : v > threshold graph = coupling ( model . corpus , 'topics' , filter = select , ** kwargs ) graph . name = '' return graph
def resources ( self ) : """Returns a list of all : class : ` ~ plexapi . myplex . MyPlexResource ` objects connected to the server ."""
data = self . query ( MyPlexResource . key ) return [ MyPlexResource ( self , elem ) for elem in data ]
def get_restore_path ( filename ) : """get _ restore _ path : returns path to directory for restoration points Args : filename ( str ) : Name of file to store Returns : string path to file"""
path = os . path . join ( RESTORE_DIRECTORY , FILE_STORE_LOCATION ) if not os . path . exists ( path ) : os . makedirs ( path ) return os . path . join ( path , filename + '.pickle' )
def is_prev_free ( self ) : """Returns a concrete state of the flag indicating whether the previous chunk is free or not . Issues a warning if that flag is symbolic and has multiple solutions , and then assumes that the previous chunk is free . : returns : True if the previous chunk is free ; False otherwise"""
flag = self . state . memory . load ( self . base + self . _chunk_size_t_size , self . _chunk_size_t_size ) & CHUNK_P_MASK def sym_flag_handler ( flag ) : l . warning ( "A chunk's P flag is symbolic; assuming it is not set" ) return self . state . solver . min_int ( flag ) flag = concretize ( flag , self . stat...
def allow_headers ( self , domain , headers , secure = True ) : """Allows ` ` domain ` ` to push data via the HTTP headers named in ` ` headers ` ` . As with ` ` allow _ domain ` ` , ` ` domain ` ` may be either a full domain name or a wildcard . Again , use of wildcards is discouraged for security reasons ...
if self . site_control == SITE_CONTROL_NONE : raise TypeError ( METAPOLICY_ERROR . format ( "allow headers from a domain" ) ) self . header_domains [ domain ] = { 'headers' : headers , 'secure' : secure }
def not_found ( cls , errors = None ) : """Shortcut API for HTTP 404 ` Not found ` response . Args : errors ( list ) : Response key / value data . Returns : WSResponse Instance ."""
if cls . expose_status : # pragma : no cover cls . response . content_type = 'application/json' cls . response . _status_line = '404 Not Found' return cls ( 404 , None , errors ) . to_json
def _declareTimeoutExceeded ( self , ev_data : RestartLogData ) : """This function is called when time for restart is up"""
logger . info ( "Timeout exceeded for {}" . format ( ev_data . when ) ) last = self . _actionLog . last_event if ( last and last . ev_type == RestartLog . Events . failed and last . data == ev_data ) : return None self . _action_failed ( ev_data , reason = "exceeded restart timeout" ) self . _unscheduleAction ( ) s...
def access_list ( ** kwargs ) : """Shows services for which there are ACL specified ."""
ctx = Context ( ** kwargs ) ctx . execute_action ( 'access:list' , ** { 'unicorn' : ctx . repo . create_secure_service ( 'unicorn' ) , } )
def p_object_ty ( self , p ) : """object _ ty : OBJECT ' ( ' ID ' ) ' | OBJECT ' ( ' ID ' , ' obj _ fields ' ) '"""
field_types = { } if len ( p ) == 5 else p [ 5 ] p [ 0 ] = Object ( p [ 3 ] , ** field_types )
def dump_database ( self ) : """Create dumpfile from postgres database , and return filename ."""
db_file = self . create_file_name ( self . databases [ 'source' ] [ 'name' ] ) self . print_message ( "Dumping postgres database '%s' to file '%s'" % ( self . databases [ 'source' ] [ 'name' ] , db_file ) ) self . export_pgpassword ( 'source' ) args = [ "pg_dump" , "-Fc" , "--no-acl" , "--no-owner" , "--dbname=%s" % se...
def emit ( self , content , request = None , emitter = None ) : """Serialize response . : return response : Instance of django . http . Response"""
# Get emitter for request emitter = emitter or self . determine_emitter ( request ) emitter = emitter ( self , request = request , response = content ) # Serialize the response content response = emitter . emit ( ) if not isinstance ( response , HttpResponse ) : raise AssertionError ( "Emitter must return HttpRespo...
def set ( self , reference , document_data , merge = False ) : """Add a " change " to replace a document . See : meth : ` ~ . firestore _ v1beta1 . document . DocumentReference . set ` for more information on how ` ` option ` ` determines how the change is applied . Args : reference ( ~ . firestore _ v1...
if merge is not False : write_pbs = _helpers . pbs_for_set_with_merge ( reference . _document_path , document_data , merge ) else : write_pbs = _helpers . pbs_for_set_no_merge ( reference . _document_path , document_data ) self . _add_write_pbs ( write_pbs )
def save ( self ) : """: return : save this team on Ariane server ( create or update )"""
LOGGER . debug ( "Team.save" ) post_payload = { } consolidated_osi_id = [ ] consolidated_app_id = [ ] if self . id is not None : post_payload [ 'teamID' ] = self . id if self . name is not None : post_payload [ 'teamName' ] = self . name if self . description is not None : post_payload [ 'teamDescription' ]...
def get_value ( self , var , cast = None , default = environ . Env . NOTSET , # noqa : C901 parse_default = False , raw = False ) : """Return value for given environment variable . : param var : Name of variable . : param cast : Type to cast return value as . : param default : If var not present in environ , ...
if raw : env_var = var else : env_var = f'{self.prefix}{var}' # logger . debug ( f " get ' { env _ var } ' casted as ' { cast } ' with default ' { default } ' " ) if var in self . scheme : var_info = self . scheme [ var ] try : has_default = len ( var_info ) == 2 except TypeError : h...
def maybe_fix_ssl_version ( ca_name , cacert_path = None , ca_filename = None ) : '''Check that the X509 version is correct ( was incorrectly set in previous salt versions ) . This will fix the version if needed . ca _ name ca authority name cacert _ path absolute path to ca certificates root directory ...
set_ca_path ( cacert_path ) if not ca_filename : ca_filename = '{0}_ca_cert' . format ( ca_name ) certp = '{0}/{1}/{2}.crt' . format ( cert_base_path ( ) , ca_name , ca_filename ) ca_keyp = '{0}/{1}/{2}.key' . format ( cert_base_path ( ) , ca_name , ca_filename ) with salt . utils . files . fopen ( certp ) as fic :...
def get_cpds ( self , node = None , time_slice = 0 ) : """Returns the CPDs that have been associated with the network . Parameters node : tuple ( node _ name , time _ slice ) The node should be in the following form ( node _ name , time _ slice ) . Here , node _ name is the node that is inserted while the t...
# TODO : fix bugs in this if node : if node not in super ( DynamicBayesianNetwork , self ) . nodes ( ) : raise ValueError ( 'Node not present in the model.' ) else : for cpd in self . cpds : if cpd . variable == node : return cpd else : return [ cpd for cpd in sel...
def decrypt ( self , document_id , encrypted_content , account ) : """Decrypt a previously encrypted content using the secret store keys identified by document _ id . Note that decryption requires permission already granted to the consumer account . : param document _ id : hex str id of document to use to ret...
return self . _secret_store ( account ) . decrypt_document ( document_id , encrypted_content )
def _parse_location ( self , entry ) : """Return the * * first * * location as ` geojson . Point ` ."""
locations = _deep_value_list ( entry , 'tif:Geolocalisations' ) coords = [ ] for location in locations : coords = _deep_value ( location , 'tif:DetailGeolocalisation' , 'tif:Zone' , 'tif:Points' , 'tif:DetailPoint' , 'tif:Coordonnees' , 'tif:DetailCoordonnees' ) if 'tif:Latitude' not in coords : continu...
def get_connection_distance ( relationship , obj1 , obj2 , limit = 2 ) : """Calculates the distance between the two given objects for the given relationship . See ` connections . models . Relationship ` for more info . { % get _ connection _ distance ' relationship _ name ' obj1 obj2 as distance % } { % get _...
return get_relationship ( relationship ) . distance_between ( obj1 , obj2 , limit )
def apply_new_scoped_variable_type ( self , path , new_variable_type_str ) : """Applies the new data type of the scoped variable defined by path : param str path : The path identifying the edited variable : param str new _ variable _ type _ str : New data type as str"""
data_port_id = self . list_store [ path ] [ self . ID_STORAGE_ID ] try : if self . model . state . scoped_variables [ data_port_id ] . data_type . __name__ != new_variable_type_str : self . model . state . scoped_variables [ data_port_id ] . change_data_type ( new_variable_type_str ) except ValueError as e ...
def insert_many ( self , table , columns , values , limit = MAX_ROWS_PER_QUERY , execute = True ) : """Insert multiple rows into a table . If only one row is found , self . insert method will be used ."""
# Make values a list of lists if it is a flat list if not isinstance ( values [ 0 ] , ( list , set , tuple ) ) : values = [ ] for v in values : if v is not None and len ( v ) > 0 : values . append ( [ v ] ) else : values . append ( [ None ] ) # Concatenate statement cols ...
def get_vcl ( self , service_id , version_number , name , include_content = True ) : """Get the uploaded VCL for a particular service and version ."""
content = self . _fetch ( "/service/%s/version/%d/vcl/%s?include_content=%d" % ( service_id , version_number , name , int ( include_content ) ) ) return FastlyVCL ( self , content )
def _remove_duplicate_points ( points , groups ) : '''Removes the duplicate points from the beginning of a section , if they are present in points - groups representation . Returns : points , groups with unique points .'''
group_initial_ids = groups [ : , GPFIRST ] to_be_reduced = np . zeros ( len ( group_initial_ids ) ) to_be_removed = [ ] for ig , g in enumerate ( groups ) : iid , typ , pid = g [ GPFIRST ] , g [ GTYPE ] , g [ GPID ] # Remove first point from sections that are # not the root section , a soma , or a child of ...
def update_file ( finfo , sample_info , config ) : """Update the file to an iRODS repository ."""
ffinal = filesystem . update_file ( finfo , sample_info , config , pass_uptodate = True ) _upload_dir_icommands_cli ( config . get ( "dir" ) , config . get ( "folder" ) , config )
def __tdfs ( j , k , head , next , post , stack ) : """Depth - first search and postorder of a tree rooted at node j ."""
top = 0 stack [ 0 ] = j while ( top >= 0 ) : p = stack [ top ] i = head [ p ] if i == - 1 : top -= 1 post [ k ] = p k += 1 else : head [ p ] = next [ i ] top += 1 stack [ top ] = i return k
def _fit ( self , y , exogenous = None , ** fit_args ) : """Internal fit"""
# This wrapper is used for fitting either an ARIMA or a SARIMAX def _fit_wrapper ( ) : # these might change depending on which one method = self . method # If it ' s in kwargs , we ' ll use it trend = self . trend # if not seasonal : if not self . _is_seasonal ( ) : if method is None : ...
def remove_files ( ) : """Removes any pre - existing tracks that were not just downloaded"""
logger . info ( "Removing local track files that were not downloaded..." ) files = [ f for f in os . listdir ( '.' ) if os . path . isfile ( f ) ] for f in files : if f not in fileToKeep : os . remove ( f )
def sync_with_handlers ( self , handlers = ( ) ) : '''Sync the stored log records to the provided log handlers .'''
if not handlers : return while self . __messages : record = self . __messages . pop ( 0 ) for handler in handlers : if handler . level > record . levelno : # If the handler ' s level is higher than the log record one , # it should not handle the log record continue handle...
def async_refresh ( self ) : """Calling this method will send the status line to i3bar immediately without waiting for timeout ( 1s by default ) ."""
self . refresh_cond . acquire ( ) self . refresh_cond . notify ( ) self . refresh_cond . release ( )
def initialize ( self , gyro_rate , slices = None , skip_estimation = False ) : """Prepare calibrator for calibration This method does three things : 1 . Create slices from the video stream , if not already provided 2 . Estimate time offset 3 . Estimate rotation between camera and gyroscope Parameters g...
self . params [ 'user' ] [ 'gyro_rate' ] = gyro_rate for p in ( 'gbias_x' , 'gbias_y' , 'gbias_z' ) : self . params [ 'initialized' ] [ p ] = 0.0 if slices is not None : self . slices = slices if self . slices is None : self . slices = videoslice . Slice . from_stream_randomly ( self . video ) logger . ...
def summarize ( objects ) : """Summarize an objects list . Return a list of lists , whereas each row consists of : : [ str ( type ) , number of objects of this type , total size of these objects ] . No guarantee regarding the order is given ."""
count = { } total_size = { } for o in objects : otype = _repr ( o ) if otype in count : count [ otype ] += 1 total_size [ otype ] += _getsizeof ( o ) else : count [ otype ] = 1 total_size [ otype ] = _getsizeof ( o ) rows = [ ] for otype in count : rows . append ( [ otype...
def mkdir_p ( * args , ** kwargs ) : """Like ` mkdir ` , but does not raise an exception if the directory already exists ."""
try : return os . mkdir ( * args , ** kwargs ) except OSError as exc : if exc . errno != errno . EEXIST : raise
def dict_to_unicode ( raw_dict ) : """Ensure all keys and values in a dict are unicode . The passed dict is assumed to have lists for all values ."""
decoded = { } for key , value in raw_dict . items ( ) : decoded [ to_unicode ( key ) ] = map ( to_unicode , value ) return decoded