signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def unmount_loopbacks ( self ) : """Unmounts all loopback devices as identified by : func : ` find _ loopbacks `"""
# re - index loopback devices self . _index_loopbacks ( ) for dev in self . find_loopbacks ( ) : _util . check_output_ ( [ 'losetup' , '-d' , dev ] )
def by_id ( cls , oid ) : """Find a model object by its ` ` ObjectId ` ` , ` ` oid ` ` can be string or ObjectId"""
if oid : d = cls . collection . find_one ( ObjectId ( oid ) ) if d : return cls ( ** d )
def makeHistory ( self ) : '''Runs a loop of sow - - > cultivate - - > reap - - > mill act _ T times , tracking the evolution of variables X named in track _ vars in attributes named X _ hist . Parameters none Returns none'''
self . reset ( ) # Initialize the state of the market for t in range ( self . act_T ) : self . sow ( ) # Distribute aggregated information / state to agents self . cultivate ( ) # Agents take action self . reap ( ) # Collect individual data from agents self . mill ( ) # Process individua...
def _heapqmergesorted ( key = None , * iterables ) : """Return a single iterator over the given iterables , sorted by the given ` key ` function , assuming the input iterables are already sorted by the same function . ( I . e . , the merge part of a general merge sort . ) Uses : func : ` heapq . merge ` for t...
if key is None : keyed_iterables = iterables for element in heapq . merge ( * keyed_iterables ) : yield element else : keyed_iterables = [ ( _Keyed ( key ( obj ) , obj ) for obj in iterable ) for iterable in iterables ] for element in heapq . merge ( * keyed_iterables ) : yield element ....
def load ( self , data ) : """Load a single row of data and convert it into entities and relations ."""
objs = { } for mapper in self . entities : objs [ mapper . name ] = mapper . load ( self . loader , data ) for mapper in self . relations : objs [ mapper . name ] = mapper . load ( self . loader , data , objs )
def volume_create ( name , size = 100 , snapshot = None , voltype = None , ** kwargs ) : '''Create block storage device'''
conn = get_conn ( ) create_kwargs = { 'name' : name , 'size' : size , 'snapshot' : snapshot , 'voltype' : voltype } create_kwargs [ 'availability_zone' ] = kwargs . get ( 'availability_zone' , None ) return conn . volume_create ( ** create_kwargs )
def read_config_file ( f ) : """Read a config file ."""
if isinstance ( f , basestring ) : f = os . path . expanduser ( f ) try : config = ConfigObj ( f , interpolation = False , encoding = 'utf8' ) except ConfigObjError as e : log ( LOGGER , logging . ERROR , "Unable to parse line {0} of config file " "'{1}'." . format ( e . line_number , f ) ) log ( LOGGER...
def get_axis_variables ( ds ) : '''Returns a list of variables that define an axis of the dataset : param netCDF4 . Dataset ds : An open netCDF4 Dataset'''
axis_variables = [ ] for ncvar in ds . get_variables_by_attributes ( axis = lambda x : x is not None ) : axis_variables . append ( ncvar . name ) return axis_variables
def get_question ( self , assessment_section_id , item_id ) : """Gets the ` ` Question ` ` specified by its ` ` Id ` ` . arg : assessment _ section _ id ( osid . id . Id ) : ` ` Id ` ` of the ` ` AssessmentSection ` ` arg : item _ id ( osid . id . Id ) : ` ` Id ` ` of the ` ` Item ` ` return : ( osid . asse...
return self . get_assessment_section ( assessment_section_id ) . get_question ( question_id = item_id )
def to_dict_list ( df , use_ordered_dict = True ) : """Transform each row to dict , and put them into a list . * * 中文文档 * * 将 ` ` pandas . DataFrame ` ` 转换成一个字典的列表 。 列表的长度与行数相同 , 其中 每一个字典相当于表中的一行 , 相当于一个 ` ` pandas . Series ` ` 对象 。"""
if use_ordered_dict : dict = OrderedDict columns = df . columns data = list ( ) for tp in itertuple ( df ) : data . append ( dict ( zip ( columns , tp ) ) ) return data
def optimize ( self , commit = True , waitFlush = None , waitSearcher = None , maxSegments = None , handler = 'update' ) : """Tells Solr to streamline the number of segments used , essentially a defragmentation operation . Optionally accepts ` ` maxSegments ` ` . Default is ` ` None ` ` . Optionally accepts `...
if maxSegments : msg = '<optimize maxSegments="%d" />' % maxSegments else : msg = '<optimize />' return self . _update ( msg , commit = commit , waitFlush = waitFlush , waitSearcher = waitSearcher , handler = handler )
def _zeep_to_dict ( cls , obj ) : """Convert a zeep object to a dictionary ."""
res = serialize_object ( obj ) res = cls . _get_non_empty_dict ( res ) return res
def escape_vals ( vals , escape_numerics = True ) : """Escapes a list of values to a string , converting to unicode for safety ."""
# Ints formatted as floats to disambiguate with counter mode ints , floats = "%.1f" , "%.10f" escaped = [ ] for v in vals : if isinstance ( v , np . timedelta64 ) : v = "'" + str ( v ) + "'" elif isinstance ( v , np . datetime64 ) : v = "'" + str ( v . astype ( 'datetime64[ns]' ) ) + "'" eli...
def unpack_kraus_matrix ( m ) : """Helper to optionally unpack a JSON compatible representation of a complex Kraus matrix . : param Union [ list , np . array ] m : The representation of a Kraus operator . Either a complex square matrix ( as numpy array or nested lists ) or a JSON - able pair of real matrices ...
m = np . asarray ( m , dtype = complex ) if m . ndim == 3 : m = m [ 0 ] + 1j * m [ 1 ] if not m . ndim == 2 : # pragma no coverage raise ValueError ( "Need 2d array." ) if not m . shape [ 0 ] == m . shape [ 1 ] : # pragma no coverage raise ValueError ( "Need square matrix." ) return m
def _isomorphism_rewrite_to_NECtree ( q_s , qgraph ) : """Neighborhood Equivalence Class tree ( see Turbo _ ISO paper )"""
qadj = qgraph . adj adjsets = lambda x : set ( chain . from_iterable ( qadj [ x ] . values ( ) ) ) t = ( [ q_s ] , [ ] ) # ( NEC _ set , children ) visited = { q_s } vcur , vnext = [ t ] , [ ] while vcur : for ( nec , children ) in vcur : c = defaultdict ( list ) for u in nec : for sig ,...
def plot_wfdb ( record = None , annotation = None , plot_sym = False , time_units = 'samples' , title = None , sig_style = [ '' ] , ann_style = [ 'r*' ] , ecg_grids = [ ] , figsize = None , return_fig = False ) : """Subplot individual channels of a wfdb record and / or annotation . This function implements the ba...
( signal , ann_samp , ann_sym , fs , ylabel , record_name ) = get_wfdb_plot_items ( record = record , annotation = annotation , plot_sym = plot_sym ) return plot_items ( signal = signal , ann_samp = ann_samp , ann_sym = ann_sym , fs = fs , time_units = time_units , ylabel = ylabel , title = ( title or record_name ) , s...
def read_string_data ( file , number_values , endianness ) : """Read string raw data This is stored as an array of offsets followed by the contiguous string data ."""
offsets = [ 0 ] for i in range ( number_values ) : offsets . append ( types . Uint32 . read ( file , endianness ) ) strings = [ ] for i in range ( number_values ) : s = file . read ( offsets [ i + 1 ] - offsets [ i ] ) strings . append ( s . decode ( 'utf-8' ) ) return strings
def login ( self , action , registry , ** kwargs ) : """Logs in to a Docker registry . : param action : Action configuration . : type action : dockermap . map . runner . ActionConfig : param registry : Name of the registry server to login to . : type registry : unicode | str : param kwargs : Additional ke...
log . info ( "Logging into registry %s." , registry ) login_kwargs = { 'registry' : registry } auth_config = action . client_config . auth_configs . get ( registry ) if auth_config : log . debug ( "Registry auth config for %s found." , registry ) login_kwargs . update ( auth_config ) insecure_registry = kwa...
def agg ( self , aggregations ) : """Multiple aggregations optimized . Parameters aggregations : list of str Which aggregations to perform . Returns Series Series with resulting aggregations ."""
check_type ( aggregations , list ) new_index = Index ( np . array ( aggregations , dtype = np . bytes_ ) , np . dtype ( np . bytes_ ) ) return _series_agg ( self , aggregations , new_index )
def iter_chat_members ( self , chat_id : Union [ int , str ] , limit : int = 0 , query : str = "" , filter : str = Filters . ALL ) -> Generator [ "pyrogram.ChatMember" , None , None ] : """Use this method to iterate through the members of a chat sequentially . This convenience method does the same as repeatedly c...
current = 0 yielded = set ( ) queries = [ query ] if query else QUERIES total = limit or ( 1 << 31 ) - 1 limit = min ( 200 , total ) resolved_chat_id = self . resolve_peer ( chat_id ) filter = ( Filters . RECENT if self . get_chat_members_count ( chat_id ) <= 10000 and filter == Filters . ALL else filter ) if filter no...
def apply ( coro , * args , ** kw ) : """Creates a continuation coroutine function with some arguments already applied . Useful as a shorthand when combined with other control flow functions . Any arguments passed to the returned function are added to the arguments originally passed to apply . This is sim...
assert_corofunction ( coro = coro ) @ asyncio . coroutine def wrapper ( * _args , ** _kw ) : # Explicitely ignore wrapper arguments return ( yield from coro ( * args , ** kw ) ) return wrapper
def open ( self , filename = None ) : '''Open a browser tab with the notebook path specified relative to the notebook directory . If no filename is specified , open the root of the notebook server .'''
if filename is None : address = self . address + 'tree' else : notebook_path = self . resource_filename ( filename ) if not notebook_path . isfile ( ) : raise IOError ( 'Notebook path not found: %s' % notebook_path ) else : address = '%snotebooks/%s' % ( self . address , filename ) webbr...
def public_key_sec ( self ) : """Return the public key as sec , or None in case of failure ."""
if self . is_coinbase ( ) : return None opcodes = ScriptTools . opcode_list ( self . script ) if len ( opcodes ) == 2 and opcodes [ 0 ] . startswith ( "[30" ) : # the second opcode is probably the public key as sec sec = h2b ( opcodes [ 1 ] [ 1 : - 1 ] ) return sec return None
def change_subpage ( self , offset = None , max_page_count = None , nom = True ) : """Args : * offset - Integer - The positive / negative change to apply to the page . * max _ page _ count - The maximum number of pages available . * nom - None on Max or Min - If max number of pages reached , return none i...
if offset == None : return if self . slots [ 'subpage' ] == None : self . slots [ 'subpage' ] = 1 if ( self . slots [ 'subpage' ] + offset > max_page_count ) and nom : return None elif ( self . slots [ 'subpage' ] + offset < 1 ) and nom : return None else : self . slots [ 'subpage' ] = norm_page_cnt...
def _reverse_problem_hparams ( p_hparams ) : """Swap input / output modalities , vocab , and space ids ."""
p = p_hparams # Swap modalities . # TODO ( trandustin ) : Note this assumes target modalities have feature name # ' target ' , and each intended feature to swap has feature name ' input ' . # In the future , remove need for this behavior . reversed_modality = { } for feature_name in p . modality : reversed_feature_...
def define_models ( self , ic , leaves = None , N = 1 , index = 0 ) : """N , index are either integers or lists of integers . N : number of model stars per observed star index : index of physical association leaves : either a list of leaves , or a pattern by which the leaves are selected ( via ` select _ le...
self . clear_models ( ) if leaves is None : leaves = self . _get_leaves ( ) elif type ( leaves ) == type ( '' ) : leaves = self . select_leaves ( leaves ) # Sort leaves by distance , to ensure system 0 will be assigned # to the main reference star . if np . isscalar ( N ) : N = ( np . ones ( len ( leaves ) ...
def blacklist_bulk ( self , blacklist ) : """Add blacklist entries to the engine node in bulk . For blacklist to work , you must also create a rule with action " Apply Blacklist " . First create your blacklist entries using : class : ` smc . elements . other . Blacklist ` then provide the blacklist to this me...
self . make_request ( EngineCommandFailed , method = 'create' , resource = 'blacklist' , json = blacklist . entries )
def import_from_hdf5 ( network , path , skip_time = False ) : """Import network data from HDF5 store at ` path ` . Parameters path : string Name of HDF5 store skip _ time : bool , default False Skip reading in time dependent attributes"""
basename = os . path . basename ( path ) with ImporterHDF5 ( path ) as importer : _import_from_importer ( network , importer , basename = basename , skip_time = skip_time )
def get_facet_serializer ( self , * args , ** kwargs ) : """Return the facet serializer instance that should be used for serializing faceted output ."""
assert "objects" in kwargs , "`objects` is a required argument to `get_facet_serializer()`" facet_serializer_class = self . get_facet_serializer_class ( ) kwargs [ "context" ] = self . get_serializer_context ( ) kwargs [ "context" ] . update ( { "objects" : kwargs . pop ( "objects" ) , "facet_query_params_text" : self ...
def can_update_assets ( self ) : """Tests if this user can update ` ` Assets ` ` . A return of true does not guarantee successful authorization . A return of false indicates that it is known updating an ` ` Asset ` ` will result in a ` ` PermissionDenied ` ` . This is intended as a hint to an application th...
url_path = construct_url ( 'authorization' , bank_id = self . _catalog_idstr ) return self . _get_request ( url_path ) [ 'assetHints' ] [ 'canUpdate' ]
def start_root_token_generation ( self , otp = None , pgp_key = None ) : """Initialize a new root generation attempt . Only a single root generation attempt can take place at a time . One ( and only one ) of otp or pgp _ key are required . Supported methods : PUT : / sys / generate - root / attempt . Produc...
params = { } if otp is not None and pgp_key is not None : raise ParamValidationError ( 'one (and only one) of otp or pgp_key arguments are required' ) if otp is not None : params [ 'otp' ] = otp if pgp_key is not None : params [ 'pgp_key' ] = pgp_key api_path = '/v1/sys/generate-root/attempt' response = sel...
def _get_float_remainder ( fvalue , signs = 9 ) : """Get remainder of float , i . e . 2.05 - > ' 05' @ param fvalue : input value @ type fvalue : C { integer types } , C { float } or C { Decimal } @ param signs : maximum number of signs @ type signs : C { integer types } @ return : remainder @ rtype : C...
check_positive ( fvalue ) if isinstance ( fvalue , six . integer_types ) : return "0" if isinstance ( fvalue , Decimal ) and fvalue . as_tuple ( ) [ 2 ] == 0 : # Decimal . as _ tuple ( ) - > ( sign , digit _ tuple , exponent ) # если экспонента " 0 " - - значит дробной части нет return "0" signs = min ( signs ...
def drag_and_drop_by_offset ( self , source , xoffset , yoffset ) : """Holds down the left mouse button on the source element , then moves to the target offset and releases the mouse button . : Args : - source : The element to mouse down . - xoffset : X offset to move to . - yoffset : Y offset to move to ...
self . click_and_hold ( source ) self . move_by_offset ( xoffset , yoffset ) self . release ( ) return self
def update_timestep ( self , modelparams , expparams ) : r"""Returns a set of model parameter vectors that is the update of an input set of model parameter vectors , such that the new models are conditioned on a particular experiment having been performed . By default , this is the trivial function : math :...
return np . tile ( modelparams , ( expparams . shape [ 0 ] , 1 , 1 ) ) . transpose ( ( 1 , 2 , 0 ) )
def stdout ( self ) : """Флаг - - stdout может быть взят из переменной окружения CROSSPM _ STDOUT . Если есть любое значение в CROSSPM _ STDOUT - оно понимается как True : return :"""
# - - stdout stdout = self . _args [ '--stdout' ] if stdout : return True # CROSSPM _ STDOUT stdout_env = os . getenv ( 'CROSSPM_STDOUT' , None ) if stdout_env is not None : return True return False
def GetDateRange ( self ) : """Return the range over which this ServicePeriod is valid . The range includes exception dates that add service outside of ( start _ date , end _ date ) , but doesn ' t shrink the range if exception dates take away service at the edges of the range . Returns : A tuple of " YYY...
start = self . start_date end = self . end_date for date , ( exception_type , _ ) in self . date_exceptions . items ( ) : if exception_type == self . _EXCEPTION_TYPE_REMOVE : continue if not start or ( date < start ) : start = date if not end or ( date > end ) : end = date if start i...
def _getCharWidths ( self , xref , bfname , ext , ordering , limit , idx = 0 ) : """Return list of glyphs and glyph widths of a font ."""
if self . isClosed or self . isEncrypted : raise ValueError ( "operation illegal for closed / encrypted doc" ) return _fitz . Document__getCharWidths ( self , xref , bfname , ext , ordering , limit , idx )
def get_cursor_right_position ( self , count = 1 ) : """Relative position for cursor _ right ."""
if count < 0 : return self . get_cursor_left_position ( - count ) return min ( count , len ( self . current_line_after_cursor ) )
def fetch_next_page ( self ) : """Manually , synchronously fetch the next page . Supplied for manually retrieving pages and inspecting : meth : ` ~ . current _ page ` . It is not necessary to call this when iterating through results ; paging happens implicitly in iteration ."""
if self . response_future . has_more_pages : self . response_future . start_fetching_next_page ( ) result = self . response_future . result ( ) self . _current_rows = result . _current_rows # ResultSet has already _ set _ current _ rows to the appropriate form else : self . _current_rows = [ ]
def write_dataframe ( rows , encoding = ENCODING , dialect = DIALECT , ** kwargs ) : """Dump ` ` rows ` ` to string buffer and load with ` ` pandas . read _ csv ( ) ` ` using ` ` kwargs ` ` ."""
global pandas if pandas is None : # pragma : no cover import pandas with contextlib . closing ( CsvBuffer ( ) ) as fd : write_csv ( fd , rows , encoding , dialect ) fd . seek ( 0 ) df = read_csv ( pandas , fd , encoding , dialect , kwargs ) return df
def add_highlight_area ( self , mask , label = None , col = 0 ) : """add a highlighted area - - outline an arbitrarily shape - - as if drawn from a Lasso event . This takes a mask , which should be a boolean array of the same shape as the image ."""
patch = mask * np . ones ( mask . shape ) * 0.9 cmap = self . conf . cmap [ col ] area = self . axes . contour ( patch , cmap = cmap , levels = [ 0 , 1 ] ) self . conf . highlight_areas . append ( area ) col = None if hasattr ( cmap , '_lut' ) : rgb = [ int ( i * 240 ) ^ 255 for i in cmap . _lut [ 0 ] [ : 3 ] ] ...
def predict_in_frame_coding_effect ( variant , transcript , trimmed_cdna_ref , trimmed_cdna_alt , sequence_from_start_codon , cds_offset ) : """Coding effect of an in - frame nucleotide change Parameters variant : Variant transcript : Transcript trimmed _ cdna _ ref : str Reference nucleotides from the co...
ref_codon_start_offset , ref_codon_end_offset , mutant_codons = get_codons ( variant = variant , trimmed_cdna_ref = trimmed_cdna_ref , trimmed_cdna_alt = trimmed_cdna_alt , sequence_from_start_codon = sequence_from_start_codon , cds_offset = cds_offset ) mutation_affects_start_codon = ( ref_codon_start_offset == 0 ) if...
def save_xml ( self , doc , element ) : '''Save this execution context into an xml . dom . Element object .'''
element . setAttributeNS ( XSI_NS , XSI_NS_S + 'type' , 'rtsExt:execution_context_ext' ) element . setAttributeNS ( RTS_NS , RTS_NS_S + 'id' , self . id ) element . setAttributeNS ( RTS_NS , RTS_NS_S + 'kind' , self . kind ) element . setAttributeNS ( RTS_NS , RTS_NS_S + 'rate' , str ( self . rate ) ) for p in self . p...
def orng_type ( self , table_name , col ) : '''Returns an Orange datatype for a given mysql column . : param table _ name : target table name : param col : column to determine the Orange datatype'''
mysql_type = self . types [ table_name ] [ col ] n_vals = len ( self . db . col_vals [ table_name ] [ col ] ) if mysql_type in OrangeConverter . continuous_types or ( n_vals >= 50 and mysql_type in OrangeConverter . integer_types ) : return 'c' elif mysql_type in OrangeConverter . ordinal_types + OrangeConverter . ...
def _parse_status ( data , cast_type ) : """Parses a STATUS message and returns a CastStatus object . : type data : dict : param cast _ type : Type of Chromecast . : rtype : CastStatus"""
data = data . get ( 'status' , { } ) volume_data = data . get ( 'volume' , { } ) try : app_data = data [ 'applications' ] [ 0 ] except KeyError : app_data = { } is_audio = cast_type in ( CAST_TYPE_AUDIO , CAST_TYPE_GROUP ) status = CastStatus ( data . get ( 'isActiveInput' , None if is_audio else False ) , data...
def bed ( args ) : """% prog bed btabfile Convert btab to bed format ."""
from jcvi . formats . blast import BlastLine p = OptionParser ( bed . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) btabfile , = args btab = Btab ( btabfile ) for b in btab : Bline = BlastLine ( b . blastline ) print ( Bline . bedline )
def package_assets ( example_path ) : """Generates pseudo - packages for the examples directory ."""
examples ( example_path , force = True , root = __file__ ) for root , dirs , files in os . walk ( example_path ) : walker ( root , dirs + files ) setup_args [ 'packages' ] += packages for p , exts in extensions . items ( ) : if exts : setup_args [ 'package_data' ] [ p ] = exts
def jsLocal ( self , time_zone = '' ) : '''a method to report a javascript string from a labDT object : param time _ zone : [ optional ] string with timezone to report in : return : string with date and time info'''
# validate inputs js_format = '%a %b %d %Y %H:%M:%S GMT%z (%Z)' title = 'Timezone input for labDT.jsLocal' get_tz = get_localzone ( ) if time_zone : # if time _ zone . lower ( ) in ( ' utc ' , ' uct ' , ' universal ' , ' zulu ' ) : # raise ValueError ( ' time _ zone cannot be UTC . % s requires a local timezone value ....
def url ( self ) : """Returns the URL for the resource based on the ` ` self ` ` link . This method returns the ` ` href ` ` of the document ' s ` ` self ` ` link if it has one , or ` ` None ` ` if the document lacks a ` ` self ` ` link , or the ` ` href ` ` of the document ' s first ` ` self ` ` link if it h...
if not 'self' in self . links : return None self_link = self . links [ 'self' ] if isinstance ( self_link , list ) : for link in self_link : return link . url ( ) return self_link . url ( )
def show_firmware_version_output_show_firmware_version_node_info_is_active_cp ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) show_firmware_version = ET . Element ( "show_firmware_version" ) config = show_firmware_version output = ET . SubElement ( show_firmware_version , "output" ) show_firmware_version = ET . SubElement ( output , "show-firmware-version" ) node_info = ET . SubElement ( show_firmware_versio...
def _get_unstack_items ( self , unstacker , new_columns ) : """Get the placement , values , and mask for a Block unstack . This is shared between ObjectBlock and ExtensionBlock . They differ in that ObjectBlock passes the values , while ExtensionBlock passes the dummy ndarray of positions to be used by a take...
# shared with ExtensionBlock new_items = unstacker . get_new_columns ( ) new_placement = new_columns . get_indexer ( new_items ) new_values , mask = unstacker . get_new_values ( ) mask = mask . any ( 0 ) return new_placement , new_values , mask
def calc ( args ) : """% prog calc [ prot . fasta ] cds . fasta > out . ks Protein file is optional . If only one file is given , it is assumed to be CDS sequences with correct frame ( frame 0 ) . Results will be written to stdout . Both protein file and nucleotide file are assumed to be Fasta format , with...
from jcvi . formats . fasta import translate p = OptionParser ( calc . __doc__ ) p . add_option ( "--longest" , action = "store_true" , help = "Get longest ORF, only works if no pep file, " "e.g. ESTs [default: %default]" ) p . add_option ( "--msa" , default = "clustalw" , choices = ( "clustalw" , "muscle" ) , help = "...
def export_go ( self , go_template = GO_TEMPLATE , go_indent = GO_INDENTATION , go_package = GO_PACKAGE ) : '''Export the grammar to a Go file which can be used with the goleri module .'''
language = [ ] enums = set ( ) indent = 0 pattern = self . RE_KEYWORDS . pattern . replace ( '`' , '` + "`" + `' ) if not pattern . startswith ( '^' ) : pattern = '^' + pattern for name in self . _order : elem = getattr ( self , name , None ) if not isinstance ( elem , Element ) : continue if no...
def merge_attributes ( attr1 , attr2 ) : """Merges two attribute dictionaries into a single dictionary . Parameters ` attr1 ` , ` attr2 ` : dict Returns dict"""
new_d = copy . deepcopy ( attr1 ) new_d . update ( attr2 ) # all of attr2 key : values just overwrote attr1 , fix it for k , v in new_d . items ( ) : if not isinstance ( v , list ) : new_d [ k ] = [ v ] for k , v in six . iteritems ( attr1 ) : if k in attr2 : if not isinstance ( v , list ) : ...
def _calculate_block_structure ( self , inequalities , equalities , momentinequalities , momentequalities , extramomentmatrix , removeequalities , block_struct = None ) : """Calculates the block _ struct array for the output file ."""
block_struct = [ ] if self . verbose > 0 : print ( "Calculating block structure..." ) block_struct . append ( len ( self . monomial_sets [ 0 ] ) * len ( self . monomial_sets [ 1 ] ) ) if extramomentmatrix is not None : for _ in extramomentmatrix : block_struct . append ( len ( self . monomial_sets [ 0 ]...
def read_filepath ( filepath , encoding = 'utf-8' ) : """Returns the text content of ` filepath `"""
with codecs . open ( filepath , 'r' , encoding = encoding ) as fo : return fo . read ( )
def _assert_safe_casting ( cls , data , subarr ) : """Ensure incoming data can be represented as ints ."""
if not issubclass ( data . dtype . type , np . signedinteger ) : if not np . array_equal ( data , subarr ) : raise TypeError ( 'Unsafe NumPy casting, you must ' 'explicitly cast' )
def simplify_compound_subjects ( sentence_str ) : """Given a sentence doc , return a new sentence doc with compound subjects reduced to their simplest forms . ' The man , the boy , and the girl went to school . ' would reduce to ' They went to school ' ' The man , the boy , or the girls are frauds . ' wou...
sentence_doc = textacy . Doc ( sentence_str , lang = 'en_core_web_lg' ) cs_patterns = [ r'((<DET>?(<NOUN|PROPN>|<PRON>)+<PUNCT>)+<DET>?(<NOUN|PROPN>|<PRON>)+<PUNCT>?<CCONJ><DET>?(<NOUN|PROPN>|<PRON>)+)|' '(<DET>?(<NOUN|PROPN>|<PRON>)<CCONJ><DET>?(<NOUN|PROPN>|<PRON>))' ] for cs_pattern in cs_patterns : compound_sub...
def authn_request ( self , context , entity_id ) : """Do an authorization request on idp with given entity id . This is the start of the authorization . : type context : satosa . context . Context : type entity _ id : str : rtype : satosa . response . Response : param context : The current context : par...
# If IDP blacklisting is enabled and the selected IDP is blacklisted , # stop here if self . idp_blacklist_file : with open ( self . idp_blacklist_file ) as blacklist_file : blacklist_array = json . load ( blacklist_file ) [ 'blacklist' ] if entity_id in blacklist_array : satosa_logging ...
def set_computed_cost_arr ( self , value ) : '''setter'''
if isinstance ( value , np . ndarray ) : self . __computed_cost_arr = value else : raise TypeError ( )
def repair ( self , volume_id_or_uri , timeout = - 1 ) : """Removes extra presentations from a specified volume on the storage system . Args : volume _ id _ or _ uri : Can be either the volume id or the volume uri . timeout : Timeout in seconds . Wait for task completion by default . The timeout does not ...
data = { "type" : "ExtraManagedStorageVolumePaths" , "resourceUri" : self . _client . build_uri ( volume_id_or_uri ) } custom_headers = { 'Accept-Language' : 'en_US' } uri = self . URI + '/repair' return self . _client . create ( data , uri = uri , timeout = timeout , custom_headers = custom_headers )
def expectation_payload ( prep_prog , operator_programs , random_seed ) : """REST payload for : py : func : ` ForestConnection . _ expectation `"""
if operator_programs is None : operator_programs = [ Program ( ) ] if not isinstance ( prep_prog , Program ) : raise TypeError ( "prep_prog variable must be a Quil program object" ) payload = { 'type' : TYPE_EXPECTATION , 'state-preparation' : prep_prog . out ( ) , 'operators' : [ x . out ( ) for x in operator_...
def autoencoder_discrete_cifar ( ) : """Discrete autoencoder model for compressing cifar ."""
hparams = autoencoder_ordered_discrete ( ) hparams . bottleneck_noise = 0.0 hparams . bottleneck_bits = 90 hparams . num_hidden_layers = 2 hparams . hidden_size = 256 hparams . num_residual_layers = 4 hparams . batch_size = 32 hparams . learning_rate_constant = 1.0 return hparams
def generate_username ( self , user_class ) : """Generate a new username for a user"""
m = getattr ( user_class , 'generate_username' , None ) if m : return m ( ) else : max_length = user_class . _meta . get_field ( self . username_field ) . max_length return uuid . uuid4 ( ) . hex [ : max_length ]
def strict_dependencies ( self , dep_context ) : """: param dep _ context : A DependencyContext with configuration for the request . : return : targets that this target " strictly " depends on . This set of dependencies contains only directly declared dependencies , with two exceptions : 1 ) aliases are expan...
strict_deps = self . _cached_strict_dependencies_map . get ( dep_context , None ) if strict_deps is None : default_predicate = self . _closure_dep_predicate ( { self } , ** dep_context . target_closure_kwargs ) # TODO ( # 5977 ) : this branch needs testing ! if not default_predicate : def default_pr...
def watch ( logger_name , level = DEBUG , out = stdout ) : """Quick wrapper for using the Watcher . : param logger _ name : name of logger to watch : param level : minimum log level to show ( default INFO ) : param out : where to send output ( default stdout ) : return : Watcher instance"""
watcher = Watcher ( logger_name ) watcher . watch ( level , out ) return watcher
def concat_urls ( * urls ) : """Concat Urls Args : * args : ( str ) Returns : str : urls starting and ending with / merged with /"""
normalized_urls = filter ( bool , [ url . strip ( '/' ) for url in urls ] ) joined_urls = '/' . join ( normalized_urls ) if not joined_urls : return '/' return '/{}/' . format ( joined_urls )
def matrix ( self , x = ( 0 , 0 ) , y = ( 0 , 0 ) , z = ( 0 , 0 ) ) : """Copy the ` ` pyny . Polygon ` ` along a 3D matrix given by the three tuples x , y , z : : param x : Number of copies and distance between them in this direction . : type x : tuple ( len = 2) : returns : list of ` ` pyny . Polygons ` ...
space = Space ( Place ( Surface ( self ) ) ) space = space . matrix ( x , y , z , inplace = False ) return [ place . surface [ 0 ] for place in space ]
def stop ( self ) : """stops the process triggered by start Setting the shared memory boolean run to false , which should prevent the loop from repeating . Call _ _ cleanup to make sure the process stopped . After that we could trigger start ( ) again ."""
if self . is_alive ( ) : self . _proc . terminate ( ) if self . _proc is not None : self . __cleanup ( ) if self . raise_error : if self . _proc . exitcode == 255 : raise LoopExceptionError ( "the loop function return non zero exticode ({})!\n" . format ( self . _proc . exitcode ) + "see...
def _setup_maya ( ) : """Setup Maya logging , but be * really * defensive about it ."""
# We are having trouble with this in Mark Media . For some reason this # remains importable from a uifutures . host launched from Maya . return try : import maya . utils except ImportError : return # Remove the shell handler ; we have created one ourselves . if hasattr ( maya . utils , 'shellLogHandler' ) : ...
def get_yarn_applications ( self , start_time , end_time , filter_str = "" , limit = 100 , offset = 0 ) : """Returns a list of YARN applications that satisfy the filter @ type start _ time : datetime . datetime . Note that the datetime must either be time zone aware or specified in the server time zone . See ...
params = { 'from' : start_time . isoformat ( ) , 'to' : end_time . isoformat ( ) , 'filter' : filter_str , 'limit' : limit , 'offset' : offset } return self . _get ( "yarnApplications" , ApiYarnApplicationResponse , params = params , api_version = 6 )
def device_selected ( self , index ) : """Handler for selecting a device from the list in the UI"""
device = self . devicelist_model . itemFromIndex ( index ) print ( device . device . addr ) self . btnConnect . setEnabled ( True )
def sanitize_qualifiers ( repos = None , followers = None , language = None ) : '''qualifiers = c repos : + 42 followers : + 1000 language : params = { ' q ' : ' tom repos : > 42 followers : > 1000 ' }'''
qualifiers = '' if repos : qualifiers += 'repos:{0} ' . format ( repos ) qualifiers = re . sub ( r"([+])([=a-zA-Z0-9]+)" , r">\2" , qualifiers ) qualifiers = re . sub ( r"([-])([=a-zA-Z0-9]+)" , r"<\2" , qualifiers ) if followers : qualifiers += 'followers:{0} ' . format ( followers ) qualifiers = r...
def process_task ( self ) : """This function is called when the client has failed to send all of the segments of a segmented request , the application has taken too long to complete the request , or the client failed to ack the segments of a segmented response ."""
if _debug : ServerSSM . _debug ( "process_task" ) if self . state == SEGMENTED_REQUEST : self . segmented_request_timeout ( ) elif self . state == AWAIT_RESPONSE : self . await_response_timeout ( ) elif self . state == SEGMENTED_RESPONSE : self . segmented_response_timeout ( ) elif self . state == COMPL...
def instance_default ( self , obj ) : '''Get the default value that will be used for a specific instance . Args : obj ( HasProps ) : The instance to get the default value for . Returns : object'''
return self . property . themed_default ( obj . __class__ , self . name , obj . themed_values ( ) )
def setattrdeep ( obj , attr , val ) : 'Set dotted attr ( like " a . b . c " ) on obj to val .'
attrs = attr . split ( '.' ) for a in attrs [ : - 1 ] : obj = getattr ( obj , a ) setattr ( obj , attrs [ - 1 ] , val )
def delete_repo ( self , repo_name = None , envs = [ ] , query = '/repositories/' ) : """` repo _ name ` - Name of repository to delete Delete repo in specified environments"""
orphan_query = '/content/orphans/rpm/' juicer . utils . Log . log_debug ( "Delete Repo: %s" , repo_name ) for env in self . args . envs : if not juicer . utils . repo_exists_p ( repo_name , self . connectors [ env ] , env ) : juicer . utils . Log . log_info ( "repo `%s` doesn't exist in %s... skipping!" , (...
def InputCodon ( seq_length , ignore_stop_codons = True , name = None , ** kwargs ) : """Input placeholder for array returned by ` encodeCodon ` Note : The seq _ length is divided by 3 Wrapper for : ` keras . layers . Input ( ( seq _ length / 3 , 61 or 61 ) , name = name , * * kwargs ) `"""
if ignore_stop_codons : vocab = CODONS else : vocab = CODONS + STOP_CODONS assert seq_length % 3 == 0 return Input ( ( seq_length / 3 , len ( vocab ) ) , name = name , ** kwargs )
def after_each_callback ( eng , callback_func , obj ) : """Take action after every WF callback ."""
obj . callback_pos = eng . state . callback_pos obj . extra_data [ "_last_task_name" ] = callback_func . __name__ task_history = get_task_history ( callback_func ) if "_task_history" not in obj . extra_data : obj . extra_data [ "_task_history" ] = [ task_history ] else : obj . extra_data [ "_task_history" ] . a...
def SpinBasisKet ( * numer_denom , hs ) : """Constructor for a : class : ` BasisKet ` for a : class : ` SpinSpace ` For a half - integer spin system : : > > > hs = SpinSpace ( ' s ' , spin = ( 3 , 2 ) ) > > > assert SpinBasisKet ( 1 , 2 , hs = hs ) = = BasisKet ( " + 1/2 " , hs = hs ) For an integer spin sy...
try : spin_numer , spin_denom = hs . spin . as_numer_denom ( ) except AttributeError : raise TypeError ( "hs=%s for SpinBasisKet must be a SpinSpace instance" % hs ) assert spin_denom in ( 1 , 2 ) if spin_denom == 1 : # integer spin if len ( numer_denom ) != 1 : raise TypeError ( "SpinBasisKet requi...
def _throttle_error ( self , msg , * args , ** kwargs ) : """Avoids sending errors repeatedly . Waits at least ` self . server _ error _ interval ` seconds before sending the same error string to the error logging facility . If not enough time has passed , it calls ` log . debug ` instead Receives the same ...
now = time . time ( ) if msg in self . _errors : if ( ( now - self . _errors [ msg ] ) >= self . server_error_interval ) : fn = self . log . error self . _errors [ msg ] = now else : fn = self . log . debug else : self . _errors [ msg ] = now fn = self . log . error return fn ( m...
def _construct_X ( self , omega , weighted = True , ** kwargs ) : """Construct the design matrix for the problem"""
t = kwargs . get ( 't' , self . t ) dy = kwargs . get ( 'dy' , self . dy ) fit_offset = kwargs . get ( 'fit_offset' , self . fit_offset ) if fit_offset : offsets = [ np . ones ( len ( t ) ) ] else : offsets = [ ] cols = sum ( ( [ np . sin ( ( i + 1 ) * omega * t ) , np . cos ( ( i + 1 ) * omega * t ) ] for i in...
async def flush ( self , request : Request , stacks : List [ Stack ] ) : """Add a typing stack after each stack ."""
ns : List [ Stack ] = [ ] for stack in stacks : ns . extend ( self . typify ( stack ) ) if len ( ns ) > 1 and ns [ - 1 ] == Stack ( [ lyr . Typing ( ) ] ) : ns [ - 1 ] . get_layer ( lyr . Typing ) . active = False await self . next ( request , ns )
def removecontains ( args ) : """% prog removecontains 4 - unitigger / best . contains asm . gkpStore Remove contained reads from gkpStore . This will improve assembly contiguity without sacrificing accuracy , when using bogart unitigger ."""
p = OptionParser ( removecontains . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) contains , gkpStore = args s = set ( ) fp = open ( contains ) for row in fp : if row [ 0 ] == '#' : continue iid = int ( row . split ( ) [ 0 ] ) s . ad...
def nb_persons ( self , role = None ) : """Returns the number of persons contained in the entity . If ` ` role ` ` is provided , only the entity member with the given role are taken into account ."""
if role : if role . subroles : role_condition = np . logical_or . reduce ( [ self . members_role == subrole for subrole in role . subroles ] ) else : role_condition = self . members_role == role return self . sum ( role_condition ) else : return np . bincount ( self . members_entity_id )
def register_to_payment ( order_class , ** kwargs ) : """A function for registering unaware order class to ` ` getpaid ` ` . This will generate a ` ` Payment ` ` model class that will store payments with ForeignKey to original order class This also will build a model class for every enabled backend ."""
global Payment global Order class Payment ( PaymentFactory . construct ( order = order_class , ** kwargs ) ) : objects = PaymentManager ( ) class Meta : ordering = ( '-created_on' , ) verbose_name = _ ( "Payment" ) verbose_name_plural = _ ( "Payments" ) Order = order_class # Now build mo...
def get_type ( self ) : """Getting type of measurement keeping backwards compatibility for v2 API output changes ."""
mtype = None if "type" not in self . meta_data : return mtype mtype = self . meta_data [ "type" ] if isinstance ( mtype , dict ) : mtype = self . meta_data . get ( "type" , { } ) . get ( "name" , "" ) . upper ( ) elif isinstance ( mtype , str ) : mtype = mtype return mtype
def is_active ( self ) : """Determines whether this plugin is active . This plugin is only active if TensorBoard sampled any text summaries . Returns : Whether this plugin is active ."""
if not self . _multiplexer : return False if self . _index_cached is not None : # If we already have computed the index , use it to determine whether # the plugin should be active , and if so , return immediately . if any ( self . _index_cached . values ( ) ) : return True if self . _multiplexer . Plugi...
def createCacheRemoveCallback ( cacheRef , key , finalizer ) : """Construct a callable to be used as a weakref callback for cache entries . The callable will invoke the provided finalizer , as well as removing the cache entry if the cache still exists and contains an entry for the given key . @ type cacheRe...
def remove ( reference ) : # Weakref callbacks cannot raise exceptions or DOOM ensues try : finalizer ( ) except : logErrorNoMatterWhat ( ) try : cache = cacheRef ( ) if cache is not None : if key in cache . data : if cache . data [ key ] is refere...
def describe_api_resource ( restApiId , path , region = None , key = None , keyid = None , profile = None ) : '''Given rest api id , and an absolute resource path , returns the resource id for the given path . CLI Example : . . code - block : : bash salt myminion boto _ apigateway . describe _ api _ resourc...
r = describe_api_resources ( restApiId , region = region , key = key , keyid = keyid , profile = profile ) resources = r . get ( 'resources' ) if resources is None : return r for resource in resources : if resource [ 'path' ] == path : return { 'resource' : resource } return { 'resource' : None }
def _backup ( path , filename ) : """Backup a file ."""
target = os . path . join ( path , filename ) if os . path . isfile ( target ) : dt = datetime . now ( ) new_filename = ".{0}.{1}.{2}" . format ( filename , dt . isoformat ( ) , "backup" ) destination = os . path . join ( path , new_filename ) puts ( "- Backing up {0} to {1}" . format ( colored . cyan (...
def azel2radec ( az_deg : float , el_deg : float , lat_deg : float , lon_deg : float , time : datetime , usevallado : bool = False ) -> Tuple [ float , float ] : """viewing angle ( az , el ) to sky coordinates ( ra , dec ) Parameters az _ deg : float or numpy . ndarray of float azimuth [ degrees clockwize fro...
if usevallado or Time is None : # non - AstroPy method , less accurate return vazel2radec ( az_deg , el_deg , lat_deg , lon_deg , time ) obs = EarthLocation ( lat = lat_deg * u . deg , lon = lon_deg * u . deg ) direc = AltAz ( location = obs , obstime = Time ( str2dt ( time ) ) , az = az_deg * u . deg , alt = el_de...
def act ( self , cmd_name , params = None ) : """Run the specified command with its parameters ."""
command = getattr ( self , cmd_name ) if params : command ( params ) else : command ( )
async def load ( self ) : """Load scenes from KLF 200."""
json_response = await self . pyvlx . interface . api_call ( 'scenes' , 'get' ) self . data_import ( json_response )
def remove_links ( text ) : """Helper function to remove the links from the input text Args : text ( str ) : A string Returns : str : the same text , but with any substring that matches the regex for a link removed and replaced with a space Example : > > > from tweet _ parser . getter _ methods . twee...
tco_link_regex = re . compile ( "https?://t.co/[A-z0-9].*" ) generic_link_regex = re . compile ( "(https?://)?(\w*[.]\w+)+([/?=&]+\w+)*" ) remove_tco = re . sub ( tco_link_regex , " " , text ) remove_generic = re . sub ( generic_link_regex , " " , remove_tco ) return remove_generic
def plot_blob ( sampler , blobidx = 0 , label = None , last_step = False , figure = None , ** kwargs ) : """Plot a metadata blob as a fit to spectral data or value distribution Additional ` ` kwargs ` ` are passed to ` plot _ fit ` . Parameters sampler : ` emcee . EnsembleSampler ` Sampler with a stored cha...
modelx , model = _process_blob ( sampler , blobidx , last_step ) if label is None : label = "Model output {0}" . format ( blobidx ) if modelx is None : # Blob is scalar , plot distribution f = plot_distribution ( model , label , figure = figure ) else : f = plot_fit ( sampler , modelidx = blobidx , last_ste...
def get_presig ( self , target , source , env ) : """Return the signature contents of this callable action ."""
try : return self . gc ( target , source , env ) except AttributeError : return self . funccontents
def run_query ( self , collection_name , query ) : """method runs query on a specified collection and return a list of filtered Job records"""
cursor = self . ds . filter ( collection_name , query ) return [ Job . from_json ( document ) for document in cursor ]
def inline ( self ) -> str : """Return inline string format of the Membership instance : return :"""
return "{0}:{1}:{2}:{3}:{4}" . format ( self . issuer , self . signatures [ 0 ] , self . membership_ts , self . identity_ts , self . uid )
def CreatePrecisionHelper ( cls , precision ) : """Creates a precision helper . Args : precision ( str ) : precision of the date and time value , which should be one of the PRECISION _ VALUES in definitions . Returns : class : date time precision helper class . Raises : ValueError : if the precision v...
precision_helper_class = cls . _PRECISION_CLASSES . get ( precision , None ) if not precision_helper_class : raise ValueError ( 'Unsupported precision: {0!s}' . format ( precision ) ) return precision_helper_class