signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def notify_txn_invalid ( self , txn_id , message = None , extended_data = None ) : """Adds a batch id to the invalid cache along with the id of the transaction that was rejected and any error message or extended data . Removes that batch id from the pending set . The cache is only temporary , and the batch in...
invalid_txn_info = { 'id' : txn_id } if message is not None : invalid_txn_info [ 'message' ] = message if extended_data is not None : invalid_txn_info [ 'extended_data' ] = extended_data with self . _lock : for batch_id , txn_ids in self . _batch_info . items ( ) : if txn_id in txn_ids : ...
def import_medusa_data ( mat_filename , config_file ) : """Import measurement data ( a . mat file ) of the FZJ EIT160 system . This data format is identified as ' FZJ - EZ - 2017 ' . Parameters mat _ filename : string filename to the . mat data file . Note that only MNU0 single - potentials are supported ...
df_emd , df_md = _read_mat_mnu0 ( mat_filename ) # ' configs ' can be a numpy array or a filename if not isinstance ( config_file , np . ndarray ) : configs = np . loadtxt ( config_file ) . astype ( int ) else : configs = config_file # construct four - point measurements via superposition print ( 'constructing ...
def remote_run ( cmd , instance_name , detach = False , retries = 1 ) : """Run command on GCS instance , optionally detached ."""
if detach : cmd = SCREEN . format ( command = cmd ) args = SSH . format ( instance_name = instance_name ) . split ( ) args . append ( cmd ) for i in range ( retries + 1 ) : try : if i > 0 : tf . logging . info ( "Retry %d for %s" , i , args ) return sp . check_call ( args ) excep...
def is_openmp_supported ( ) : """Determine whether the build compiler has OpenMP support ."""
log_threshold = log . set_threshold ( log . FATAL ) ret = check_openmp_support ( ) log . set_threshold ( log_threshold ) return ret
def _scaleTo8bit ( self , img ) : '''The pattern comparator need images to be 8 bit - > find the range of the signal and scale the image'''
r = scaleSignalCutParams ( img , 0.02 ) # , nSigma = 3) self . signal_ranges . append ( r ) return toUIntArray ( img , dtype = np . uint8 , range = r )
def value_loss ( value_net_apply , value_net_params , observations , rewards , reward_mask , gamma = 0.99 ) : """Computes the value loss . Args : value _ net _ apply : value net apply function with signature ( params , ndarray of shape ( B , T + 1 ) + OBS ) - > ndarray ( B , T + 1 , 1) value _ net _ params ...
B , T = rewards . shape # pylint : disable = invalid - name assert ( B , T + 1 ) == observations . shape [ : 2 ] # NOTE : observations is ( B , T + 1 ) + OBS , value _ prediction is ( B , T + 1 , 1) value_prediction = value_net_apply ( observations , value_net_params ) assert ( B , T + 1 , 1 ) == value_prediction . sha...
def venv_metadata_extension ( extraction_fce ) : """Extracts specific metadata from virtualenv object , merges them with data from given extraction method ."""
def inner ( self ) : data = extraction_fce ( self ) if virtualenv is None or not self . venv : logger . debug ( "Skipping virtualenv metadata extraction." ) return data temp_dir = tempfile . mkdtemp ( ) try : extractor = virtualenv . VirtualEnv ( self . name , temp_dir , self . n...
def read ( self , vals ) : """Read values . Args : vals ( list ) : list of strings representing values"""
i = 0 if len ( vals [ i ] ) == 0 : self . typical_or_extreme_period_name = None else : self . typical_or_extreme_period_name = vals [ i ] i += 1 if len ( vals [ i ] ) == 0 : self . typical_or_extreme_period_type = None else : self . typical_or_extreme_period_type = vals [ i ] i += 1 if len ( vals [ i ] ...
def p_if_statement_1 ( self , p ) : """if _ statement : IF LPAREN expr RPAREN statement"""
p [ 0 ] = self . asttypes . If ( predicate = p [ 3 ] , consequent = p [ 5 ] ) p [ 0 ] . setpos ( p )
def _histogram_summary ( self , tf_name , value , step = None ) : """Args : tf _ name ( str ) : name of tensorflow variable value ( tuple or list ) : either a tuple of bin _ edges and bincounts or a list of values to summarize in a histogram . References : https : / / github . com / yunjey / pytorch - tut...
if isinstance ( value , tuple ) : bin_edges , bincounts = value assert len ( bin_edges ) == len ( bincounts ) + 1 , ( 'must have one more edge than count' ) hist = summary_pb2 . HistogramProto ( ) hist . min = float ( min ( bin_edges ) ) hist . max = float ( max ( bin_edges ) ) else : values = n...
def round_sig ( x , sig ) : """Round the number to the specified number of significant figures"""
return round ( x , sig - int ( floor ( log10 ( abs ( x ) ) ) ) - 1 )
def add_boot_info_table ( self , boot_info_table ) : # type : ( eltorito . EltoritoBootInfoTable ) - > None '''A method to add a boot info table to this Inode . Parameters : boot _ info _ table - The Boot Info Table object to add to this Inode . Returns : Nothing .'''
if not self . _initialized : raise pycdlibexception . PyCdlibInternalError ( 'Inode is not yet initialized' ) self . boot_info_table = boot_info_table
def verbosity_level ( self , value ) : """Setter for * * self . _ _ verbosity _ level * * attribute . : param value : Attribute value . : type value : int"""
if value is not None : assert type ( value ) is int , "'{0}' attribute: '{1}' type is not 'int'!" . format ( "verbosity_level" , value ) assert value >= 0 and value <= 4 , "'{0}' attribute: Value need to be exactly beetween 0 and 4!" . format ( "verbosity_level" ) self . __verbosity_level = value
def disaggregate_temperature ( self , method = 'sine_min_max' , min_max_time = 'fix' , mod_nighttime = False ) : """Disaggregate air temperature . Parameters method : str , optional Disaggregation method . ` ` sine _ min _ max ` ` Hourly temperatures follow a sine function preserving daily minimum and m...
self . data_disagg . temp = melodist . disaggregate_temperature ( self . data_daily , method = method , min_max_time = min_max_time , max_delta = self . statistics . temp . max_delta , mean_course = self . statistics . temp . mean_course , sun_times = self . sun_times , mod_nighttime = mod_nighttime )
def send_and_wait ( self , path , message , timeout = 0 , responder = None ) : """Send a message and block until a response is received . Return response message"""
message . on ( "response" , lambda x , event_origin , source : None , once = True ) if timeout > 0 : ts = time . time ( ) else : ts = 0 sent = False while not message . response_received : if not sent : self . send ( path , message ) sent = True if ts : if time . time ( ) - ts > ...
def p_program_line_label ( p ) : """label _ line : LABEL statements | LABEL co _ statements"""
lbl = make_label ( p [ 1 ] , p . lineno ( 1 ) ) p [ 0 ] = make_block ( lbl , p [ 2 ] ) if len ( p ) == 3 else lbl
def check_rst ( code , ignore ) : """Yield errors in nested RST code ."""
filename = '<string>' for result in check ( code , filename = filename , ignore = ignore ) : yield result
def iter_configurations ( kafka_topology_base_path = None ) : """Cluster topology iterator . Iterate over all the topologies available in config ."""
if not kafka_topology_base_path : config_dirs = get_conf_dirs ( ) else : config_dirs = [ kafka_topology_base_path ] types = set ( ) for config_dir in config_dirs : new_types = [ x for x in map ( lambda x : os . path . basename ( x ) [ : - 5 ] , glob . glob ( '{0}/*.yaml' . format ( config_dir ) ) , ) if x n...
def sorted_files_from_bucket ( bucket , keys = None ) : """Return files from bucket sorted by given keys . : param bucket : : class : ` ~ invenio _ files _ rest . models . Bucket ` containing the files . : param keys : Keys order to be used . : returns : Sorted list of bucket items ."""
keys = keys or [ ] total = len ( keys ) sortby = dict ( zip ( keys , range ( total ) ) ) values = ObjectVersion . get_by_bucket ( bucket ) . all ( ) return sorted ( values , key = lambda x : sortby . get ( x . key , total ) )
def add_answer_for_student ( student_item , vote , rationale ) : """Add an answer for a student to the backend Args : student _ item ( dict ) : The location of the problem this submission is associated with , as defined by a course , student , and item . vote ( int ) : the option that student voted for ra...
answers = get_answers_for_student ( student_item ) answers . add_answer ( vote , rationale ) sub_api . create_submission ( student_item , { ANSWER_LIST_KEY : answers . get_answers_as_list ( ) } )
def pop ( self ) : """Removes the last traversal path node from this traversal path ."""
node = self . nodes . pop ( ) self . __keys . remove ( node . key )
async def get_password_tty ( device , options ) : """Get the password to unlock a device from terminal ."""
# TODO : make this a TRUE async text = _ ( 'Enter password for {0.device_presentation}: ' , device ) try : return getpass . getpass ( text ) except EOFError : print ( "" ) return None
def _read_stdin ( ) : """Generator for reading from standard input in nonblocking mode . Other ways of reading from ` ` stdin ` ` in python waits , until the buffer is big enough , or until EOF character is sent . This functions yields immediately after each line ."""
line = sys . stdin . readline ( ) while line : yield line line = sys . stdin . readline ( )
def _get_oplog_timestamp ( self , newest_entry ) : """Return the timestamp of the latest or earliest entry in the oplog ."""
sort_order = pymongo . DESCENDING if newest_entry else pymongo . ASCENDING curr = ( self . oplog . find ( { "op" : { "$ne" : "n" } } ) . sort ( "$natural" , sort_order ) . limit ( - 1 ) ) try : ts = next ( curr ) [ "ts" ] except StopIteration : LOG . debug ( "OplogThread: oplog is empty." ) return None LOG ...
def decode_field ( self , field , value ) : """Decode a JSON value to a python value . Args : field : A ProtoRPC field instance . value : A serialized JSON value . Returns : A Python value compatible with field ."""
# Override BytesField handling . Client libraries typically use a url - safe # encoding . b64decode doesn ' t handle these gracefully . urlsafe _ b64decode # handles both cases safely . Also add padding if the padding is incorrect . if isinstance ( field , messages . BytesField ) : try : # Need to call str ( value ...
def edge_length_sum ( self , terminal = True , internal = True ) : '''Compute the sum of all selected edge lengths in this ` ` Tree ` ` Args : ` ` terminal ` ` ( ` ` bool ` ` ) : ` ` True ` ` to include terminal branches , otherwise ` ` False ` ` ` ` internal ` ` ( ` ` bool ` ` ) : ` ` True ` ` to include int...
if not isinstance ( terminal , bool ) : raise TypeError ( "leaves must be a bool" ) if not isinstance ( internal , bool ) : raise TypeError ( "internal must be a bool" ) return sum ( node . edge_length for node in self . traverse_preorder ( ) if node . edge_length is not None and ( ( terminal and node . is_leaf...
def setup_psd_workflow ( workflow , science_segs , datafind_outs , output_dir = None , tags = None ) : '''Setup static psd section of CBC workflow . At present this only supports pregenerated psd files , in the future these could be created within the workflow . Parameters workflow : pycbc . workflow . core ....
if tags is None : tags = [ ] logging . info ( "Entering static psd module." ) make_analysis_dir ( output_dir ) cp = workflow . cp # Parse for options in ini file . try : psdMethod = cp . get_opt_tags ( "workflow-psd" , "psd-method" , tags ) except : # Predefined PSD sare optional , just return an empty list if ...
def save ( self , * objs , condition = None , atomic = False ) : """Save one or more objects . : param objs : objects to save . : param condition : only perform each save if this condition holds . : param bool atomic : only perform each save if the local and DynamoDB versions of the object match . : raises ...
objs = set ( objs ) validate_not_abstract ( * objs ) for obj in objs : self . session . save_item ( { "TableName" : self . _compute_table_name ( obj . __class__ ) , "Key" : dump_key ( self , obj ) , ** render ( self , obj = obj , atomic = atomic , condition = condition , update = True ) } ) object_saved . send ...
def discard_local_changes ( cwd , path = '.' , user = None , password = None , ignore_retcode = False , output_encoding = None ) : '''. . versionadded : : 2019.2.0 Runs a ` ` git checkout - - < path > ` ` from the directory specified by ` ` cwd ` ` . cwd The path to the git checkout path path relative to ...
cwd = _expand_path ( cwd , user ) command = [ 'git' , 'checkout' , '--' , path ] # Checkout message goes to stderr return _git_run ( command , cwd = cwd , user = user , password = password , ignore_retcode = ignore_retcode , redirect_stderr = True , output_encoding = output_encoding ) [ 'stdout' ]
def gen_row_lines ( self , row , style , inner_widths , height ) : r"""Combine cells in row and group them into lines with vertical borders . Caller is expected to pass yielded lines to ' ' . join ( ) to combine them into a printable line . Caller must append newline character to the end of joined line . In :...
cells_in_row = list ( ) # Resize row if it doesn ' t have enough cells . if len ( row ) != len ( inner_widths ) : row = row + [ '' ] * ( len ( inner_widths ) - len ( row ) ) # Pad and align each cell . Split each cell into lines to support multi - line cells . for i , cell in enumerate ( row ) : align = ( self ...
def Field ( self , field , Value = None ) : '''Add field to bitmap'''
if Value == None : try : return self . __Bitmap [ field ] except KeyError : return None elif Value == 1 or Value == 0 : self . __Bitmap [ field ] = Value else : raise ValueError
def coarsen ( self , windows , func , boundary = 'exact' , side = 'left' ) : """Apply"""
windows = { k : v for k , v in windows . items ( ) if k in self . dims } if not windows : return self . copy ( ) reshaped , axes = self . _coarsen_reshape ( windows , boundary , side ) if isinstance ( func , str ) : name = func func = getattr ( duck_array_ops , name , None ) if func is None : ra...
def create_target_group ( name , protocol , port , vpc_id , region = None , key = None , keyid = None , profile = None , health_check_protocol = 'HTTP' , health_check_port = 'traffic-port' , health_check_path = '/' , health_check_interval_seconds = 30 , health_check_timeout_seconds = 5 , healthy_threshold_count = 5 , u...
ret = { 'name' : name , 'result' : None , 'comment' : '' , 'changes' : { } } if __salt__ [ 'boto_elbv2.target_group_exists' ] ( name , region , key , keyid , profile ) : ret [ 'result' ] = True ret [ 'comment' ] = 'Target Group {0} already exists' . format ( name ) return ret if __opts__ [ 'test' ] : re...
def execute_django ( self , soql , args = ( ) ) : """Fixed execute for queries coming from Django query compilers"""
response = None sqltype = soql . split ( None , 1 ) [ 0 ] . upper ( ) if isinstance ( self . query , subqueries . InsertQuery ) : response = self . execute_insert ( self . query ) elif isinstance ( self . query , subqueries . UpdateQuery ) : response = self . execute_update ( self . query ) elif isinstance ( se...
def fetch_datatype ( self , bucket , key , r = None , pr = None , basic_quorum = None , notfound_ok = None , timeout = None , include_context = None ) : """Fetches a Riak Datatype ."""
raise NotImplementedError
def max_pairs ( shape ) : """[ DEPRECATED ] Compute the maximum number of record pairs possible ."""
if not isinstance ( shape , ( tuple , list ) ) : x = get_length ( shape ) n = int ( x * ( x - 1 ) / 2 ) elif ( isinstance ( shape , ( tuple , list ) ) and len ( shape ) == 1 ) : x = get_length ( shape [ 0 ] ) n = int ( x * ( x - 1 ) / 2 ) else : n = numpy . prod ( [ get_length ( xi ) for xi in shape...
def clear ( ) : """Clear all data on the local server . Useful for debugging purposed ."""
utils . check_for_local_server ( ) click . confirm ( "Are you sure you want to do this? It will delete all of your data" , abort = True ) server = Server ( config [ "local_server" ] [ "url" ] ) for db_name in all_dbs : del server [ db_name ]
def set ( self , key , value , expire = 0 , noreply = None ) : """The memcached " set " command . Args : key : str , see class docs for details . value : str , see class docs for details . expire : optional int , number of seconds until the item is expired from the cache , or zero for no expiry ( the defa...
if noreply is None : noreply = self . default_noreply return self . _store_cmd ( b'set' , { key : value } , expire , noreply ) [ key ]
def ot_find_studies ( arg_dict , exact = True , verbose = False , oti_wrapper = None ) : """Uses a peyotl wrapper around an Open Tree web service to get a list of studies including values ` value ` for a given property to be searched on ` porperty ` . The oti _ wrapper can be None ( in which case the default wr...
if oti_wrapper is None : from peyotl . sugar import oti oti_wrapper = oti return oti_wrapper . find_studies ( arg_dict , exact = exact , verbose = verbose , wrap_response = True )
def pair ( self ) : """Returns a callable and an iterable respectively . Those can be used to both transmit a message and / or iterate over incoming messages , that were sent by a pair socket . Note that the iterable returns as many parts as sent by a pair . Also , the sender function has a ` ` print ` ` like...
sock = self . __sock ( zmq . PAIR ) return self . __send_function ( sock ) , self . __recv_generator ( sock )
def expand_expression ( self , pattern , hosts , services , hostgroups , servicegroups , running = False ) : # pylint : disable = too - many - locals """Expand a host or service expression into a dependency node tree using ( host | service ) group membership , regex , or labels as item selector . : param patter...
error = None node = DependencyNode ( ) node . operand = '&' elts = [ e . strip ( ) for e in pattern . split ( ',' ) ] # If host _ name is empty , use the host _ name the business rule is bound to if not elts [ 0 ] : elts [ 0 ] = self . bound_item . host_name filters = [ ] # Looks for hosts / services using appropri...
def register ( cls , function = None , name = None ) : """Registers a new math function * function * with * name * and returns an : py : class : ` Operation ` instance . A math function expects a : py : class : ` Number ` as its first argument , followed by optional ( keyword ) arguments . When * name * is * No...
def register ( function ) : op = Operation ( function , name = name ) @ functools . wraps ( function ) def wrapper ( num , * args , ** kwargs ) : if op . derivative is None : raise Exception ( "cannot run operation '{}', no derivative registered" . format ( op . name ) ) # ensure...
def _extract_assignment_text ( self , element_id ) : """Extract assignment text ( instructions ) . @ param element _ id : Element id to extract assignment instructions from . @ type element _ id : str @ return : List of assignment text ( instructions ) . @ rtype : [ str ]"""
dom = get_page ( self . _session , OPENCOURSE_PROGRAMMING_ASSIGNMENTS_URL , json = True , course_id = self . _course_id , element_id = element_id ) return [ element [ 'submissionLearnerSchema' ] [ 'definition' ] [ 'assignmentInstructions' ] [ 'definition' ] [ 'value' ] for element in dom [ 'elements' ] ]
def register ( self , widget , basename , ** parameters ) : """Register a widget , URL basename and any optional URL parameters . Parameters are passed as keyword arguments , i . e . > > > router . register ( MyWidget , ' mywidget ' , my _ parameter = " [ A - Z0-9 ] + " ) This would be the equivalent of manua...
self . registry . append ( ( widget , basename , parameters ) )
def coherence_spectrogram ( self , other , stride , fftlength = None , overlap = None , window = 'hann' , nproc = 1 ) : """Calculate the coherence spectrogram between this ` TimeSeries ` and other . Parameters other : ` TimeSeries ` the second ` TimeSeries ` in this CSD calculation stride : ` float ` nu...
from . . spectrogram . coherence import from_timeseries return from_timeseries ( self , other , stride , fftlength = fftlength , overlap = overlap , window = window , nproc = nproc )
def generate_local_port ( ) : """https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / lib / socket . c # L63."""
global _PREVIOUS_LOCAL_PORT if _PREVIOUS_LOCAL_PORT is None : try : with contextlib . closing ( socket . socket ( getattr ( socket , 'AF_NETLINK' , - 1 ) , socket . SOCK_RAW ) ) as s : s . bind ( ( 0 , 0 ) ) _PREVIOUS_LOCAL_PORT = int ( s . getsockname ( ) [ 0 ] ) except OSError ...
def kernel_command_line ( self , kernel_command_line ) : """Sets the kernel command line for this QEMU VM . : param kernel _ command _ line : QEMU kernel command line"""
log . info ( 'QEMU VM "{name}" [{id}] has set the QEMU kernel command line to {kernel_command_line}' . format ( name = self . _name , id = self . _id , kernel_command_line = kernel_command_line ) ) self . _kernel_command_line = kernel_command_line
def template_chooser_clicked ( self ) : """Slot activated when report file tool button is clicked . . . versionadded : 4.3.0"""
path = self . template_path . text ( ) if not path : path = setting ( 'lastCustomTemplate' , '' , str ) if path : directory = dirname ( path ) else : directory = '' # noinspection PyCallByClass , PyTypeChecker file_name = QFileDialog . getOpenFileName ( self , tr ( 'Select report' ) , directory , tr ( 'QGIS...
def request_data ( cls , time , site_id , derived = False ) : """Retreive IGRA version 2 data for one station . Parameters site _ id : str 11 - character IGRA2 station identifier . time : datetime The date and time of the desired observation . If list of two times is given , dataframes for all dates wit...
igra2 = cls ( ) # Set parameters for data query if derived : igra2 . ftpsite = igra2 . ftpsite + 'derived/derived-por/' igra2 . suffix = igra2 . suffix + '-drvd.txt' else : igra2 . ftpsite = igra2 . ftpsite + 'data/data-por/' igra2 . suffix = igra2 . suffix + '-data.txt' if type ( time ) == datetime . d...
async def on_raw_401 ( self , message ) : """No such nick / channel ."""
nickname = message . params [ 1 ] # Remove nickname from whois requests if it involves one of ours . if nickname in self . _pending [ 'whois' ] : future = self . _pending [ 'whois' ] . pop ( nickname ) future . set_result ( None ) del self . _whois_info [ nickname ]
def generate_vectored_io_stripe_metadata ( local_path , metadata ) : # type : ( blobxfer . models . upload . LocalPath , dict ) - > dict """Generate vectored io stripe metadata dict : param blobxfer . models . upload . LocalPath local _ path : local path : param dict metadata : existing metadata dict : rtype ...
md = { _JSON_KEY_VECTORED_IO : { _JSON_KEY_VECTORED_IO_MODE : _JSON_KEY_VECTORED_IO_STRIPE , _JSON_KEY_VECTORED_IO_STRIPE : { _JSON_KEY_VECTORED_IO_STRIPE_TOTAL_SIZE : local_path . total_size , _JSON_KEY_VECTORED_IO_STRIPE_OFFSET_START : local_path . view . fd_start , _JSON_KEY_VECTORED_IO_STRIPE_TOTAL_SLICES : local_p...
def is_subdomain ( self , other ) : """Is self a subdomain of other ? The notion of subdomain includes equality . @ rtype : bool"""
( nr , o , nl ) = self . fullcompare ( other ) if nr == NAMERELN_SUBDOMAIN or nr == NAMERELN_EQUAL : return True return False
def _transform ( self , df ) : """Private transform method of a Transformer . This serves as batch - prediction method for our purposes ."""
output_col = self . getOutputCol ( ) label_col = self . getLabelCol ( ) new_schema = copy . deepcopy ( df . schema ) new_schema . add ( StructField ( output_col , StringType ( ) , True ) ) rdd = df . rdd . coalesce ( 1 ) features = np . asarray ( rdd . map ( lambda x : from_vector ( x . features ) ) . collect ( ) ) # N...
def _parse_date_default_value ( property_name , default_value_string ) : """Parse and return the default value for a date property ."""
# OrientDB doesn ' t use ISO - 8601 datetime format , so we have to parse it manually # and then turn it into a python datetime object . strptime ( ) will raise an exception # if the provided value cannot be parsed correctly . parsed_value = time . strptime ( default_value_string , ORIENTDB_DATE_FORMAT ) return datetim...
def samples ( self ) : """Access the samples : returns : twilio . rest . autopilot . v1 . assistant . task . sample . SampleList : rtype : twilio . rest . autopilot . v1 . assistant . task . sample . SampleList"""
if self . _samples is None : self . _samples = SampleList ( self . _version , assistant_sid = self . _solution [ 'assistant_sid' ] , task_sid = self . _solution [ 'sid' ] , ) return self . _samples
def earth_rates ( ATTITUDE ) : '''return angular velocities in earth frame'''
from math import sin , cos , tan , fabs p = ATTITUDE . rollspeed q = ATTITUDE . pitchspeed r = ATTITUDE . yawspeed phi = ATTITUDE . roll theta = ATTITUDE . pitch psi = ATTITUDE . yaw phiDot = p + tan ( theta ) * ( q * sin ( phi ) + r * cos ( phi ) ) thetaDot = q * cos ( phi ) - r * sin ( phi ) if fabs ( cos ( theta ) )...
def transform_content ( tags , content_transformer ) : """Transform content in all ` tags ` using result of ` content _ transformer ( tag ) ` call . Args : tags ( obj / list ) : HTMLElement instance , or list of HTMLElement instances . content _ transformer ( function ) : Function which is called as ` `...
if type ( tags ) not in [ tuple , list ] : tags = [ tags ] for tag in tags : new_child = dhtmlparser . HTMLElement ( content_transformer ( tag ) ) # don ' t forget to add parent if the list is double - linked if hasattr ( tag , "parent" ) : new_child . parent = tag tag . childs = [ new_child...
def runInParallel ( * fns ) : """Runs multiple processes in parallel . : type : fns : def"""
proc = [ ] for fn in fns : p = Process ( target = fn ) p . start ( ) proc . append ( p ) for p in proc : p . join ( )
def get_files ( file_tokens , cwd = None ) : """Given a list of parser file tokens , return a list of input objects for them ."""
if not file_tokens : return [ ] token = file_tokens . pop ( ) try : filename = token . filename except AttributeError : filename = '' if cwd : input = Input ( token . alias , filename , cwd = cwd ) else : input = Input ( token . alias , filename ) return [ input ] + get_files ( file_tokens )
def upgrade_nrml ( directory , dry_run , multipoint ) : """Upgrade all the NRML files contained in the given directory to the latest NRML version . Works by walking all subdirectories . WARNING : there is no downgrade !"""
for cwd , dirs , files in os . walk ( directory ) : for f in files : path = os . path . join ( cwd , f ) if f . endswith ( '.xml' ) : ip = iterparse ( path , events = ( 'start' , ) ) next ( ip ) # read node zero try : fulltag = next ( i...
def find_annotations ( data , retriever = None ) : """Find annotation configuration files for vcfanno , using pre - installed inputs . Creates absolute paths for user specified inputs and finds locally installed defaults . Default annotations : - gemini for variant pipelines - somatic for variant tumor pi...
conf_files = dd . get_vcfanno ( data ) if not isinstance ( conf_files , ( list , tuple ) ) : conf_files = [ conf_files ] for c in _default_conf_files ( data , retriever ) : if c not in conf_files : conf_files . append ( c ) conf_checkers = { "gemini" : annotate_gemini , "somatic" : _annotate_somatic } o...
def get_property_example ( cls , property_ , nested = None , ** kw ) : """Get example for property : param dict property _ : : param set nested : : return : example value"""
paths = kw . get ( 'paths' , [ ] ) name = kw . get ( 'name' , '' ) result = None if name and paths : paths = list ( map ( lambda path : '.' . join ( ( path , name ) ) , paths ) ) result , path = cls . _get_custom_example ( paths ) if result is not None and property_ [ 'type' ] in PRIMITIVE_TYPES : c...
def vignettingEq ( xxx_todo_changeme , f = 100 , alpha = 0 , Xi = 0 , tau = 0 , cx = 50 , cy = 50 ) : '''Vignetting equation using the KARL - WEISS - MODEL see http : / / research . microsoft . com / en - us / people / stevelin / vignetting . pdf f - focal length alpha - coefficient in the geometric vignettin...
( x , y ) = xxx_todo_changeme dist = ( ( x - cx ) ** 2 + ( y - cy ) ** 2 ) ** 0.5 A = old_div ( 1.0 , ( 1 + ( old_div ( dist , f ) ) ** 2 ) ** 2 ) G = ( 1 - alpha * dist ) T = np . cos ( tau ) * ( 1 + ( old_div ( np . tan ( tau ) , f ) ) * ( x * np . sin ( Xi ) - y * np . cos ( Xi ) ) ) ** 3 return A * G * T
def hs_join ( ls_hsi , hso ) : """[ Many - to - one ] Synchronizes ( joins ) a list of input handshake interfaces : output is ready when ALL inputs are ready ls _ hsi - ( i ) list of input handshake tuples ( ready , valid ) hso - ( o ) an output handshake tuple ( ready , valid )"""
N = len ( ls_hsi ) ls_hsi_rdy , ls_hsi_vld = zip ( * ls_hsi ) ls_hsi_rdy , ls_hsi_vld = list ( ls_hsi_rdy ) , list ( ls_hsi_vld ) hso_rdy , hso_vld = hso @ always_comb def _hsjoin ( ) : all_vld = True for i in range ( N ) : all_vld = all_vld and ls_hsi_vld [ i ] hso_vld . next = all_vld for i in...
async def configure_reporting ( self , attribute , min_interval , max_interval , reportable_change ) : """Configure reporting ."""
result = await super ( ) . configure_reporting ( PowerConfigurationCluster . BATTERY_VOLTAGE_ATTR , self . FREQUENCY , self . FREQUENCY , self . MINIMUM_CHANGE ) return result
def folderitem ( self , obj , item , index ) : """Service triggered each time an item is iterated in folderitems . The use of this service prevents the extra - loops in child objects . : obj : the instance of the class to be foldered : item : dict containing the properties of the object to be used by the te...
# We are using the existing logic from the auditview logview = api . get_view ( "auditlog" , context = obj , request = self . request ) # get the last snapshot snapshot = get_last_snapshot ( obj ) # get the metadata of the last snapshot metadata = get_snapshot_metadata ( snapshot ) title = obj . Title ( ) url = obj . a...
def update_permissions ( self , grp_name , resource , permissions ) : """Update permissions for the group associated with the given resource . Args : grp _ name ( string ) : Name of group . resource ( intern . resource . boss . Resource ) : Identifies which data model object to operate on permissions ( li...
self . project_service . set_auth ( self . _token_project ) self . project_service . update_permissions ( grp_name , resource , permissions )
def sem ( inlist ) : """Returns the estimated standard error of the mean ( sx - bar ) of the values in the passed list . sem = stdev / sqrt ( n ) Usage : lsem ( inlist )"""
sd = stdev ( inlist ) n = len ( inlist ) return sd / math . sqrt ( n )
def connect ( self ) : """connect"""
_logger . debug ( "Start connecting to broker" ) while True : try : self . client . connect ( self . broker_host , self . broker_port , self . broker_keepalive ) break except Exception : _logger . debug ( "Connect failed. wait %s sec" % self . connect_delay ) sleep ( self . conne...
def add_fast_step ( self , fastsim ) : """Add the fastsim context to the trace ."""
for wire_name in self . trace : self . trace [ wire_name ] . append ( fastsim . context [ wire_name ] )
def symmetric_difference_update ( self , that ) : """Update the set , keeping only elements found in either * self * or * that * , but not in both ."""
_set = self . _set _list = self . _list _set . symmetric_difference_update ( that ) _list . clear ( ) _list . update ( _set ) return self
def split_extension ( path ) : """A extension splitter that checks for compound extensions such as ' file . nii . gz ' Parameters filename : str A filename to split into base and extension Returns base : str The base part of the string , i . e . ' file ' of ' file . nii . gz ' ext : str The extens...
for double_ext in double_exts : if path . endswith ( double_ext ) : return path [ : - len ( double_ext ) ] , double_ext dirname = os . path . dirname ( path ) filename = os . path . basename ( path ) parts = filename . split ( '.' ) if len ( parts ) == 1 : base = filename ext = None else : ext =...
def retrieve_table_records ( self , table , query_column , field_list , ids_to_retrieve ) : """Responsys . retrieveTableRecords call Accepts : InteractObject table string query _ column possible values : ' RIID ' | ' EMAIL _ ADDRESS ' | ' CUSTOMER _ ID ' | ' MOBILE _ NUMBER ' list field _ list list ids ...
table = table . get_soap_object ( self . client ) return RecordData . from_soap_type ( self . call ( 'retrieveTableRecords' , table , query_column , field_list , ids_to_retrieve ) )
def from_JSON ( oauth_json , type = "service" ) : '''At the time of writing , keys include : client _ secret , client _ email , redirect _ uris ( list ) , client _ x509 _ cert _ url , client _ id , javascript _ origins ( list ) auth _ provider _ x509 _ cert _ url , auth _ uri , token _ uri .'''
assert ( type == "service" or type == "web" ) return NestedBunch ( json . loads ( oauth_json ) [ type ] )
def decode_unicode ( data , replace_boo = True ) : # dictionary which direct maps unicode values to its letters dictionary = { '0030' : '0' , '0031' : '1' , '0032' : '2' , '0033' : '3' , '0034' : '4' , '0035' : '5' , '0036' : '6' , '0037' : '7' , '0038' : '8' , '0039' : '9' , '0024' : '$' , '0040' : '@' , '00A2' : ...
for unicode_str in ndata : uni = unicode_str [ 2 : ] if unicode_str not in data : unicode_str = '\U000' + unicode_str [ 2 : ] # converting to standard representation for c in uppers : if c in unicode_str : unicode_str = unicode_str . replace ( c , c . lower ( ...
def sam_parse_reply ( line ) : """parse a reply line into a dict"""
parts = line . split ( ' ' ) opts = { k : v for ( k , v ) in split_kv ( parts [ 2 : ] ) } return SAMReply ( parts [ 0 ] , opts )
def QA_indicator_SKDJ ( DataFrame , N = 9 , M = 3 ) : """1 . 指标 > 80 时 , 回档机率大 ; 指标 < 20 时 , 反弹机率大 ; 2 . K在20左右向上交叉D时 , 视为买进信号参考 ; 3 . K在80左右向下交叉D时 , 视为卖出信号参考 ; 4 . SKDJ波动于50左右的任何讯号 , 其作用不大 。"""
CLOSE = DataFrame [ 'close' ] LOWV = LLV ( DataFrame [ 'low' ] , N ) HIGHV = HHV ( DataFrame [ 'high' ] , N ) RSV = EMA ( ( CLOSE - LOWV ) / ( HIGHV - LOWV ) * 100 , M ) K = EMA ( RSV , M ) D = MA ( K , M ) DICT = { 'RSV' : RSV , 'SKDJ_K' : K , 'SKDJ_D' : D } return pd . DataFrame ( DICT )
def _scobit_utility_transform ( systematic_utilities , alt_IDs , rows_to_alts , shape_params , intercept_params , intercept_ref_pos = None , * args , ** kwargs ) : """Parameters systematic _ utilities : 1D ndarray . All elements should be ints , floats , or longs . Should contain the systematic utilities of e...
# Figure out what indices are to be filled in if intercept_ref_pos is not None and intercept_params is not None : needed_idxs = range ( intercept_params . shape [ 0 ] + 1 ) needed_idxs . remove ( intercept_ref_pos ) if len ( intercept_params . shape ) > 1 and intercept_params . shape [ 1 ] > 1 : # Get an ar...
def tracker ( ) : """start a tracker to register running models"""
application = mmi . tracker . app ( ) application . listen ( 22222 ) logger . info ( 'serving at port 22222' ) tornado . ioloop . IOLoop . instance ( ) . start ( )
def cook_layout ( layout , ajax ) : """Return main _ template compatible layout"""
# Fix XHTML layouts with CR [ + LF ] line endings layout = re . sub ( '\r' , '\n' , re . sub ( '\r\n' , '\n' , layout ) ) # Parse layout if isinstance ( layout , six . text_type ) : result = getHTMLSerializer ( [ layout . encode ( 'utf-8' ) ] , encoding = 'utf-8' ) else : result = getHTMLSerializer ( [ layout ]...
def get_common_session_key ( self , premaster_secret ) : """K = H ( S ) . Special implementation for Apple TV ."""
k_1 = self . hash ( premaster_secret , b'\x00\x00\x00\x00' , as_bytes = True ) k_2 = self . hash ( premaster_secret , b'\x00\x00\x00\x01' , as_bytes = True ) return k_1 + k_2
def _parse_relation ( self , tag ) : """Parses the chunk tag , role and relation id from the token relation tag . - VP = > VP , [ ] , [ ] - VP - 1 = > VP , [ 1 ] , [ None ] - ADJP - PRD = > ADJP , [ None ] , [ PRD ] - NP - SBJ - 1 = > NP , [ 1 ] , [ SBJ ] - NP - OBJ - 1 * NP - OBJ - 2 = > NP , [ 1,2 ] , [...
chunk , relation , role = None , [ ] , [ ] if ";" in tag : # NP - SBJ ; NP - OBJ - 1 = > 1 relates to both SBJ and OBJ . id = tag . split ( "*" ) [ 0 ] [ - 2 : ] id = id if id . startswith ( "-" ) else "" tag = tag . replace ( ";" , id + "*" ) if "*" in tag : tag = tag . split ( "*" ) else : tag = [...
def _compare_suffix ( self , other ) : """Return false if suffixes are mutually exclusive"""
# If suffix is omitted , assume a match if not self . suffix or not other . suffix : return True # Check if more than one unique suffix suffix_set = set ( self . suffix_list + other . suffix_list ) unique_suffixes = suffix_set & UNIQUE_SUFFIXES for key in EQUIVALENT_SUFFIXES : if key in unique_suffixes : ...
def _maybe_replace_path ( self , match ) : """Regex replacement method that will sub paths when needed"""
path = match . group ( 0 ) if self . _should_replace ( path ) : return self . _replace_path ( path ) else : return path
def add ( self , name , arcname = None , recursive = True , exclude = None , filter = None ) : """Add the file ` name ' to the archive . ` name ' may be any type of file ( directory , fifo , symbolic link , etc . ) . If given , ` arcname ' specifies an alternative name for the file in the archive . Directorie...
self . _check ( "aw" ) if arcname is None : arcname = name # Exclude pathnames . if exclude is not None : import warnings warnings . warn ( "use the filter argument instead" , DeprecationWarning , 2 ) if exclude ( name ) : self . _dbg ( 2 , "tarfile: Excluded %r" % name ) return # Skip i...
def add_tags ( self , tags , afterwards = None , remove_rest = False ) : """add ` tags ` to all messages in this thread . . note : : This only adds the requested operation to this objects : class : ` DBManager ' s < alot . db . DBManager > ` write queue . You need to call : meth : ` DBManager . flush < alot...
def myafterwards ( ) : if remove_rest : self . _tags = set ( tags ) else : self . _tags = self . _tags . union ( tags ) if callable ( afterwards ) : afterwards ( ) self . _dbman . tag ( 'thread:' + self . _id , tags , afterwards = myafterwards , remove_rest = remove_rest )
def get_all_published_ships_basic ( db_connection ) : """Gets a list of all published ships and their basic information . : return : Each result has a tuple of ( typeID , typeName , groupID , groupName , categoryID , and categoryName ) . : rtype : list"""
if not hasattr ( get_all_published_ships_basic , '_results' ) : sql = 'CALL get_all_published_ships_basic();' results = execute_sql ( sql , db_connection ) get_all_published_ships_basic . _results = results return get_all_published_ships_basic . _results
def _delete_extraneous_files ( self ) : # type : ( Uploader ) - > None """Delete extraneous files on the remote : param Uploader self : this"""
if not self . _spec . options . delete_extraneous_destination : return # list blobs for all destinations checked = set ( ) deleted = 0 for sa , container , vpath , dpath in self . _get_destination_paths ( ) : key = ';' . join ( ( sa . name , sa . endpoint , str ( dpath ) ) ) if key in checked : cont...
def _populate ( self , json ) : """A helper method that , given a JSON object representing this object , assigns values based on the properties dict and the attributes of its Properties ."""
if not json : return # hide the raw JSON away in case someone needs it self . _set ( '_raw_json' , json ) for key in json : if key in ( k for k in type ( self ) . properties . keys ( ) if not type ( self ) . properties [ k ] . identifier ) : if type ( self ) . properties [ key ] . relationship and not j...
def get_xauth_access_token ( self , username , password ) : """Get an access token from an username and password combination . In order to get this working you need to create an app at http : / / twitter . com / apps , after that send a mail to api @ twitter . com and request activation of xAuth for it ."""
try : url = self . _get_oauth_url ( 'access_token' ) oauth = OAuth1 ( self . consumer_key , client_secret = self . consumer_secret ) r = requests . post ( url = url , auth = oauth , headers = { 'x_auth_mode' : 'client_auth' , 'x_auth_username' : username , 'x_auth_password' : password } ) credentials = ...
def _to_unicode_scalar_value ( s ) : """Helper function for converting a character or surrogate pair into a Unicode scalar value e . g . " \ud800 \udc00 " - > 0x10000 The algorithm can be found in older versions of the Unicode Standard . https : / / unicode . org / versions / Unicode3.0.0 / ch03 . pdf , Secti...
if len ( s ) == 1 : return ord ( s ) elif len ( s ) == 2 : return ( ord ( s [ 0 ] ) - 0xD800 ) * 0x0400 + ( ord ( s [ 1 ] ) - 0xDC00 ) + 0x10000 else : raise ValueError
def do_plot ( args ) : """Create plots of mcmc output"""
import ugali . utils . plotting import pylab as plt config , name , label , coord = args filenames = make_filenames ( config , label ) srcfile = filenames [ 'srcfile' ] samfile = filenames [ 'samfile' ] memfile = filenames [ 'memfile' ] if not exists ( srcfile ) : logger . warning ( "Couldn't find %s; skipping..." ...
def get_following ( self ) : """: calls : ` GET / user / following < http : / / developer . github . com / v3 / users / followers > ` _ : rtype : : class : ` github . PaginatedList . PaginatedList ` of : class : ` github . NamedUser . NamedUser `"""
return github . PaginatedList . PaginatedList ( github . NamedUser . NamedUser , self . _requester , "/user/following" , None )
def unique_ ( self , col ) : """Returns unique values in a column"""
try : df = self . df . drop_duplicates ( subset = [ col ] , inplace = False ) return list ( df [ col ] ) except Exception as e : self . err ( e , "Can not select unique data" )
def from_chord_shorthand ( self , shorthand ) : """Empty the container and add the notes in the shorthand . See mingus . core . chords . from _ shorthand for an up to date list of recognized format . Example : > > > NoteContainer ( ) . from _ chord _ shorthand ( ' Am ' ) [ ' A - 4 ' , ' C - 5 ' , ' E - 5 ...
self . empty ( ) self . add_notes ( chords . from_shorthand ( shorthand ) ) return self
def get_layers ( self , class_ : Type [ L ] , became : bool = True ) -> List [ L ] : """Returns the list of layers of a given class . If no layers are present then the list will be empty . : param class _ : class of the expected layers : param became : Allow transformed layers in results"""
out = self . _index . get ( class_ , [ ] ) if became : out += self . _transformed . get ( class_ , [ ] ) return out
def start_task ( self , method , * args , ** kwargs ) : """Start a task in a separate thread Args : method : the method to start in a separate thread args : Accept args / kwargs arguments"""
thread = threading . Thread ( target = method , args = args , kwargs = kwargs ) thread . is_daemon = False thread . start ( ) self . threads . append ( thread )
def reader ( stream ) : """Read Items from a stream containing lines of JSON ."""
for line in stream : item = Item ( ) item . json = line yield item
def browse ( self , path = None ) : """Returns a list of directories matching the path given . Args : path ( str ) : glob pattern . Returns : List [ str ]"""
params = None if path : assert isinstance ( path , string_types ) params = { 'current' : path } return self . get ( 'browse' , params = params )
def get_collection_measures ( self ) : """Helper function for calculating measurements derived from clusters / chains / collections"""
if not self . quiet : print print "Computing duration-independent" , self . current_collection_type , "measures..." self . compute_collection_measures ( ) # include length = 1 clusters self . compute_collection_measures ( no_singletons = True ) # no length = 1 clusters self . compute_pairwise_similarity_score (...