signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_active_geometry ( self ) : """Get the geometry of the currently active window Usage : C { window . get _ active _ geometry ( ) } @ return : a 4 - tuple containing the x - origin , y - origin , width and height of the window ( in pixels ) @ rtype : C { tuple ( int , int , int , int ) }"""
active = self . mediator . interface . get_window_title ( ) result , output = self . _run_wmctrl ( [ "-l" , "-G" ] ) matchingLine = None for line in output . split ( '\n' ) : if active in line [ 34 : ] . split ( ' ' , 1 ) [ - 1 ] : matchingLine = line if matchingLine is not None : output = matchingLine ...
def all ( cls , otp = False , ccid = False , u2f = False ) : """Returns a set of all PIDs , with optional filtering"""
pids = set ( [ cls . YUBIKEY , cls . NEO_OTP , cls . NEO_OTP_CCID , cls . NEO_CCID , cls . NEO_U2F , cls . NEO_OTP_U2F , cls . NEO_U2F_CCID , cls . NEO_OTP_U2F_CCID , cls . NEO_SKY , cls . YK4_OTP , cls . YK4_U2F , cls . YK4_OTP_U2F , cls . YK4_CCID , cls . YK4_OTP_CCID , cls . YK4_U2F_CCID , cls . YK4_OTP_U2F_CCID , c...
def get_items ( self , url , container , container_object , local_object ) : """Get an objects from a container . : param url : : param container :"""
headers , container_uri = self . _return_base_data ( url = url , container = container , container_object = container_object ) return self . _getter ( uri = container_uri , headers = headers , local_object = local_object )
def permute_pathways_across_features ( self ) : """Return a permutation of the network . Requires that the significant pathways file has been specified during CoNetwork initialization ( or set ` self . feature _ pathway _ df ` to the pandas . DataFrame afterwards ) ."""
side_labels = self . feature_pathway_df . side . unique ( ) pathway_features = { } for side in side_labels : pathway_features [ side ] = [ ] feature_grouping = self . feature_pathway_df . groupby ( [ "side" , "feature" ] ) for ( side , feature ) , group in feature_grouping : pathways = group [ "pathway" ] . tol...
def _mem_update_done ( self , mem ) : """Callback from each individual memory ( only 1 - wire ) when reading of header / elements are done"""
if mem . id in self . _ow_mems_left_to_update : self . _ow_mems_left_to_update . remove ( mem . id ) logger . debug ( mem ) if len ( self . _ow_mems_left_to_update ) == 0 : if self . _refresh_callback : self . _refresh_callback ( ) self . _refresh_callback = None
def process_raw_data ( cls , raw_data ) : """Create a new model using raw API response ."""
properties = raw_data . get ( "properties" , { } ) raw_metadata = raw_data . get ( "resourceMetadata" , None ) if raw_metadata is not None : metadata = ResourceMetadata . from_raw_data ( raw_metadata ) raw_data [ "resourceMetadata" ] = metadata raw_state = properties . get ( "configurationState" , None ) if raw...
def get_gyroscope_raw ( self ) : """Gyroscope x y z raw data in radians per second"""
raw = self . _get_raw_data ( 'gyroValid' , 'gyro' ) if raw is not None : self . _last_gyro_raw = raw return deepcopy ( self . _last_gyro_raw )
def minimum ( self ) : """Finds the minimum reaction energy E _ min and corresponding mixing ratio x _ min . Returns : Tuple ( x _ min , E _ min ) ."""
return min ( [ ( x , energy ) for _ , x , energy , _ , _ in self . get_kinks ( ) ] , key = lambda i : i [ 1 ] )
def marvcli_comment_list ( datasets ) : """Lists comments for datasets . Output : setid comment _ id date time author message"""
app = create_app ( ) ids = parse_setids ( datasets , dbids = True ) comments = db . session . query ( Comment ) . options ( db . joinedload ( Comment . dataset ) ) . filter ( Comment . dataset_id . in_ ( ids ) ) for comment in sorted ( comments , key = lambda x : ( x . dataset . _setid , x . id ) ) : print ( commen...
def line ( self , x1 , y1 , x2 , y2 ) : "Draw a line"
self . _out ( sprintf ( '%.2f %.2f m %.2f %.2f l S' , x1 * self . k , ( self . h - y1 ) * self . k , x2 * self . k , ( self . h - y2 ) * self . k ) )
def packet_loss ( self ) : '''packet loss as a percentage'''
if self . mav_count == 0 : return 0 return ( 100.0 * self . mav_loss ) / ( self . mav_count + self . mav_loss )
def resolve_data_objects ( objects , project = None , folder = None , batchsize = 1000 ) : """: param objects : Data object specifications , each with fields " name " ( required ) , " folder " , and " project " : type objects : list of dictionaries : param project : ID of project context ; a data object ' s p...
if not isinstance ( batchsize , int ) or batchsize <= 0 or batchsize > 1000 : raise ValueError ( "batchsize for resolve_data_objects must be a positive integer not exceeding 1000" ) args = { } if project : args . update ( { 'project' : project } ) if folder : args . update ( { 'folder' : folder } ) results ...
def list_minus ( l : List , minus : List ) -> List : """Returns l without what is in minus > > > list _ minus ( [ 1 , 2 , 3 ] , [ 2 ] ) [1 , 3]"""
return [ o for o in l if o not in minus ]
def __push_facvar_sparse ( self , polynomial , block_index , row_offset , i , j ) : """Calculate the sparse vector representation of a polynomial and pushes it to the F structure ."""
width = self . block_struct [ block_index - 1 ] # Preprocess the polynomial for uniform handling later # DO NOT EXPAND THE POLYNOMIAL HERE ! ! ! ! ! # The simplify _ polynomial bypasses the problem . # Simplifying here will trigger a bug in SymPy related to # the powers of daggered variables . # polynomial = polynomial...
def getLogs ( self , CorpNum , ItemCode , MgtKey ) : """전자명세서 문서이력 목록 확인 args CorpNum : 팝빌회원 사업자번호 ItemCode : 명세서 종류 코드 [121 - 거래명세서 ] , [ 122 - 청구서 ] , [ 123 - 견적서 ] , [124 - 발주서 ] , [ 125 - 입금표 ] , [ 126 - 영수증 ] MgtKey : 파트너 ᄆ...
if MgtKey == None or MgtKey == "" : raise PopbillException ( - 99999999 , "관리번호가 입력되지 않았습니다." ) if ItemCode == None or ItemCode == "" : raise PopbillException ( - 99999999 , "명세서 종류 코드가 입력되지 않았습니다." ) return self . _httpget ( '/Statement/' + str ( ItemCode ) + '/' + MgtKey + '/Logs' , CorpNum )
def all ( self ) : """: return : array of file objects ( 200 status code )"""
url = "{url_base}/resource/{pid}/files/" . format ( url_base = self . hs . url_base , pid = self . pid ) r = self . hs . _request ( 'GET' , url ) return r
def chunk_by ( n , iterable , fillvalue = None ) : """Iterate over a given ` ` iterable ` ` by ` ` n ` ` elements at a time . > > > for x , y in chunk _ by ( 2 , [ 1 , 2 , 3 , 4 , 5 ] ) : . . . # iteration no 1 : x = 1 , y = 2 . . . # iteration no 2 : x = 3 , y = 4 . . . # iteration no 3 : x = 5 , y = None ...
args = [ iter ( iterable ) ] * n return zip_longest ( * args , fillvalue = fillvalue )
def find_reference_section ( docbody ) : """Search in document body for its reference section . More precisely , find the first line of the reference section . Effectively , the function starts at the end of a document and works backwards , line - by - line , looking for the title of a reference section . I...
ref_details = None title_patterns = get_reference_section_title_patterns ( ) # Try to find refs section title : for title_pattern in title_patterns : # Look for title pattern in docbody for reversed_index , line in enumerate ( reversed ( docbody ) ) : title_match = title_pattern . match ( line ) if ...
def coord_pyramid ( coord , zoom_start , zoom_stop ) : """generate full pyramid for coord Generate the full pyramid for a single coordinate . Note that zoom _ stop is exclusive ."""
if zoom_start <= coord . zoom : yield coord for child_coord in coord_children_range ( coord , zoom_stop ) : if zoom_start <= child_coord . zoom : yield child_coord
def calculate_checksum_on_iterator ( itr , algorithm = d1_common . const . DEFAULT_CHECKSUM_ALGORITHM ) : """Calculate the checksum of an iterator . Args : itr : iterable Object which supports the iterator protocol . algorithm : str Checksum algorithm , ` ` MD5 ` ` or ` ` SHA1 ` ` / ` ` SHA - 1 ` ` . Re...
checksum_calc = get_checksum_calculator_by_dataone_designator ( algorithm ) for chunk in itr : checksum_calc . update ( chunk ) return checksum_calc . hexdigest ( )
def subquery ( self , name = None ) : """The recipe ' s query as a subquery suitable for use in joins or other queries ."""
query = self . query ( ) return query . subquery ( name = name )
def get_help_datapacks ( module_name , server_prefix ) : """Get the help datapacks for a module Args : module _ name ( str ) : The module to get help data for server _ prefix ( str ) : The command prefix for this server Returns : datapacks ( list ) : The help datapacks for the module"""
_dir = os . path . realpath ( os . path . join ( os . getcwd ( ) , os . path . dirname ( __file__ ) ) ) module_dir = "{}/../{}" . format ( _dir , module_name , "_help.json" ) if os . path . isdir ( module_dir ) : module_help_path = "{}/{}" . format ( module_dir , "_help.json" ) if os . path . isfile ( module_he...
def _process_targeting_reagents ( self , reagent_type , limit = None ) : """This method processes the gene targeting knockdown reagents , such as morpholinos , talens , and crisprs . We create triples for the reagents and pass the data into a hash map for use in the pheno _ enviro method . Morpholinos work ...
LOG . info ( "Processing Gene Targeting Reagents" ) if self . test_mode : graph = self . testgraph else : graph = self . graph line_counter = 0 model = Model ( graph ) geno = Genotype ( graph ) if reagent_type not in [ 'morph' , 'talen' , 'crispr' ] : LOG . error ( "You didn't specify the right kind of file...
def await_socket ( self , timeout ) : """Wait up to a given timeout for a process to write socket info ."""
return self . await_metadata_by_name ( self . _name , 'socket' , timeout , self . _socket_type )
def serialize ( self ) -> str : """Dump current object to a JSON - compatible dictionary . : return : dict representation of current DIDDoc"""
return { '@context' : DIDDoc . CONTEXT , 'id' : canon_ref ( self . did , self . did ) , 'publicKey' : [ pubkey . to_dict ( ) for pubkey in self . pubkey . values ( ) ] , 'authentication' : [ { 'type' : pubkey . type . authn_type , 'publicKey' : canon_ref ( self . did , pubkey . id ) } for pubkey in self . pubkey . valu...
def add ( self , method_name , completeness = False , ** fields ) : """Class decorator . Decorate ` method _ name ` by adding a call to ` set _ defaults ` and ` check _ config ` . Then , save into the registry a callable function with the same signature of the original method . : param str method _ name : ...
def class_decorator ( class_obj ) : original_method = getattr ( class_obj , method_name ) if sys . version [ 0 ] == '2' : # Python 2 original_method = original_method . im_func def caller ( fn , obj , catalogue , config = None , * args , ** kwargs ) : config = config or { } self . se...
def generate_export_pipeline_code ( pipeline_tree , operators ) : """Generate code specific to the construction of the sklearn Pipeline for export _ pipeline . Parameters pipeline _ tree : list List of operators in the current optimized pipeline Returns Source code for the sklearn pipeline"""
steps = _process_operator ( pipeline_tree , operators ) # number of steps in a pipeline num_step = len ( steps ) if num_step > 1 : pipeline_text = "make_pipeline(\n{STEPS}\n)" . format ( STEPS = _indent ( ",\n" . join ( steps ) , 4 ) ) # only one operator ( root = True ) else : pipeline_text = "{STEPS}" . forma...
def str2long ( s ) : """Convert a string to a long integer ."""
if type ( s ) not in ( types . StringType , types . UnicodeType ) : raise ValueError ( 'the input must be a string' ) l = 0 for i in s : l <<= 8 l |= ord ( i ) return l
def rename ( self , dest_path : str ) : '''use ` os . rename ( ) ` to move the node .'''
if not isinstance ( dest_path , str ) : raise TypeError os . rename ( self . _path , dest_path ) self . _path = Path ( dest_path ) . get_abspath ( )
def commit_account_vesting ( self , block_height ) : """vest any tokens at this block height"""
# save all state log . debug ( "Commit all database state before vesting" ) self . db . commit ( ) if block_height in self . vesting : traceback . print_stack ( ) log . fatal ( "Tried to vest tokens twice at {}" . format ( block_height ) ) os . abort ( ) # commit all vesting in one transaction cur = self . ...
def _safe_type ( value ) : """Converts Python type names to XGMML - safe type names ."""
if type ( value ) is str : dtype = 'string' if type ( value ) is unicode : dtype = 'string' if type ( value ) is int : dtype = 'integer' if type ( value ) is float : dtype = 'real' return dtype
def set_up ( self ) : """Set up your applications and the test environment ."""
self . path . state = self . path . gen . joinpath ( "state" ) if self . path . state . exists ( ) : self . path . state . rmtree ( ignore_errors = True ) self . path . state . mkdir ( ) for script in self . given . get ( "scripts" , [ ] ) : script_path = self . path . state . joinpath ( script ) if not scr...
def get_mask ( cls , azim ) : """Linear interpolation between two points of the mask"""
if cls . mask is None : raise ValueError ( "No mask defined for the station {}" . format ( cls . name ) ) azim %= 2 * np . pi if azim in cls . mask [ 0 , : ] : return cls . mask [ 1 , np . where ( azim == cls . mask [ 0 , : ] ) [ 0 ] [ 0 ] ] for next_i , mask_azim in enumerate ( cls . mask [ 0 , : ] ) : if ...
def check_internal_consistency ( self , ** kwargs ) : """Check whether the database is internally consistent We check that all variables are equal to the sum of their sectoral components and that all the regions add up to the World total . If the check is passed , None is returned , otherwise a dictionary of ...
inconsistent_vars = { } for variable in self . variables ( ) : diff_agg = self . check_aggregate ( variable , ** kwargs ) if diff_agg is not None : inconsistent_vars [ variable + "-aggregate" ] = diff_agg diff_regional = self . check_aggregate_region ( variable , ** kwargs ) if diff_regional is ...
def get_elections ( self , obj ) : """All elections held on an election day ."""
election_day = ElectionDay . objects . get ( date = self . context [ "election_date" ] ) kwargs = { "race__office__body" : obj , "election_day" : election_day } if self . context . get ( "division" ) and obj . slug == "senate" : kwargs [ "division" ] = self . context [ "division" ] elif self . context . get ( "divi...
def bulk_add_dimensions ( dimension_list , ** kwargs ) : """Save all the dimensions contained in the passed list ."""
added_dimensions = [ ] for dimension in dimension_list : added_dimensions . append ( add_dimension ( dimension , ** kwargs ) ) return JSONObject ( { "dimensions" : added_dimensions } )
def _netbsd_gpu_data ( ) : '''num _ gpus : int gpus : - vendor : nvidia | amd | ati | . . . model : string'''
known_vendors = [ 'nvidia' , 'amd' , 'ati' , 'intel' , 'cirrus logic' , 'vmware' , 'matrox' , 'aspeed' ] gpus = [ ] try : pcictl_out = __salt__ [ 'cmd.run' ] ( 'pcictl pci0 list' ) for line in pcictl_out . splitlines ( ) : for vendor in known_vendors : vendor_match = re . match ( r'[0-9:]+ (...
def _check_items ( items ) : '''Check : - that the list of items is iterable and finite . - that the list is not empty'''
num_items = 0 # Check that the list is iterable and finite try : num_items = len ( items ) except : raise TypeError ( "The item list ({}) is not a finite iterable (has no length)" . format ( items ) ) # Check that the list has items if num_items == 0 : raise ValueError ( "The item list is empty." )
def _get_symbol_index ( stroke_id_needle , segmentation ) : """Parameters stroke _ id _ needle : int Identifier for the stroke of which the symbol should get found . segmentation : list of lists of integers An ordered segmentation of strokes to symbols . Returns The symbol index in which stroke _ id _ n...
for symbol_index , symbol in enumerate ( segmentation ) : if stroke_id_needle in symbol : return symbol_index return None
def get_chunk_path_from_string ( string , chunk = 3 ) : """Return a chunked path from string ."""
return os . path . join ( * list ( generate_chunks ( string , chunk ) ) )
def unpublish_all_versions ( self , ** args ) : '''Sends a PID update request for the unpublication of all versions of a dataset currently published at the given data node . If the library has solr access , it will try to find all the dataset versions and their handles from solr , and send individual messag...
# Check args mandatory_args = [ 'drs_id' ] esgfpid . utils . check_presence_of_mandatory_args ( args , mandatory_args ) # Check if data node is given if self . __data_node is None : msg = 'No data_node given (but it is mandatory for publication)' logwarn ( LOGGER , msg ) raise esgfpid . exceptions . Argumen...
def with_img_type ( self , image_type ) : """Returns the search results having the specified image type : param image _ type : the desired image type ( valid values are provided by the ` pyowm . commons . enums . ImageTypeEnum ` enum ) : type image _ type : ` pyowm . commons . databoxes . ImageType ` instance...
assert isinstance ( image_type , ImageType ) return list ( filter ( lambda x : x . image_type == image_type , self . metaimages ) )
def query ( self , files = True ) : """Queries the depot to get the current status of the changelist"""
if self . _change : cl = str ( self . _change ) self . _p4dict = { camel_case ( k ) : v for k , v in six . iteritems ( self . _connection . run ( [ 'change' , '-o' , cl ] ) [ 0 ] ) } if files : self . _files = [ ] if self . _p4dict . get ( 'status' ) == 'pending' or self . _change == 0 : change ...
def read_all ( self ) : """Read all data until EOF ; block until connection closed ."""
self . process_rawq ( ) while not self . eof : self . fill_rawq ( ) self . process_rawq ( ) buf = self . cookedq . getvalue ( ) self . cookedq . seek ( 0 ) self . cookedq . truncate ( ) return buf
def channels_unarchive ( self , * , channel : str , ** kwargs ) -> SlackResponse : """Unarchives a channel . Args : channel ( str ) : The channel id . e . g . ' C1234567890'"""
self . _validate_xoxp_token ( ) kwargs . update ( { "channel" : channel } ) return self . api_call ( "channels.unarchive" , json = kwargs )
def main ( ) : """Starting point for the program execution ."""
# Create command line parser . parser = argparse . ArgumentParser ( ) # Adding command line arguments . parser . add_argument ( "-o" , "--out" , help = "Output file" , default = None ) parser . add_argument ( "pyfile" , help = "Python file to be profiled" , default = None ) # Parse command line arguments . arguments = ...
def create_refobject ( self , ) : """Create a refobject in the scene that represents the : class : ` Reftrack ` instance . . . Note : : This will not set the reftrack object . : returns : the created reftrack object : rtype : scene object : raises : None"""
parent = self . get_parent ( ) if parent : prefobj = parent . get_refobj ( ) else : prefobj = None refobj = self . get_refobjinter ( ) . create ( self . get_typ ( ) , self . get_id ( ) , prefobj ) return refobj
def square ( m , eff_max , c , m0 , sigma , m1 = 21 ) : """eff _ max : Maximum of the efficiency function ( peak efficiency ) c : shape of the drop - off in the efficiency at bright end m0 : transition to tappering at faint magnitudes sigma : width of the transition in efficeincy m1 : magnitude at which pea...
return ( eff_max - c * ( m - 21 ) ** 2 ) / ( 1 + numpy . exp ( ( m - m0 ) / sigma ) )
def publication_history ( self ) : """List of tuples of authored publications in the form ( title , abbreviation , type , issn ) , where issn is only given for journals . abbreviation and issn may be None ."""
pub_hist = self . xml . findall ( 'author-profile/journal-history/' ) hist = [ ] for pub in pub_hist : try : issn = pub . find ( "issn" ) . text except AttributeError : issn = None try : abbr = pub . find ( "sourcetitle-abbrev" ) . text except AttributeError : abbr = None...
def get_regions_and_coremasks ( self ) : """Generate a set of ordered paired region and core mask representations . . . note : : The region and core masks are ordered such that ` ` ( region < < 32 ) | core _ mask ` ` is monotonically increasing . Consequently region and core masks generated by this method c...
region_code = ( ( self . base_x << 24 ) | ( self . base_y << 16 ) | ( self . level << 16 ) ) # Generate core masks for any regions which are selected at this level # Create a mapping from subregion mask to core numbers subregions_cores = collections . defaultdict ( lambda : 0x0 ) for core , subregions in enumerate ( se...
def past_trades ( self , timestamp = 0 , symbol = 'btcusd' ) : """Fetch past trades : param timestamp : : param symbol : : return :"""
payload = { "request" : "/v1/mytrades" , "nonce" : self . _nonce , "symbol" : symbol , "timestamp" : timestamp } signed_payload = self . _sign_payload ( payload ) r = requests . post ( self . URL + "/mytrades" , headers = signed_payload , verify = True ) json_resp = r . json ( ) return json_resp
def classify_wherex ( scope_ , fromx , wherex ) : "helper for wherex _ to _ rowlist . returns [ SingleTableCond , . . . ] , [ CartesianCond , . . . ]"
exprs = [ ] for exp in fromx : if isinstance ( exp , sqparse2 . JoinX ) : # todo : probably just add exp . on _ stmt as a CartesianCond . don ' t write this until tests are ready . # todo : do join - on clauses get special scoping w . r . t . column names ? check spec . raise NotImplementedError ( 'join...
def _get_macros ( chain ) : """Get all macros of a chain Cut ' $ ' char and create a dict with the following structure : : { ' MacroSTR1 ' : { ' val ' : ' ' , ' type ' : ' unknown ' } ' MacroSTR2 ' : { ' val ' : ' ' , ' type ' : ' unknown ' } : param chain : chain to parse : type chain : str : return : ...
regex = re . compile ( r'(\$)' ) elts = regex . split ( chain ) macros = { } in_macro = False for elt in elts : if elt == '$' : in_macro = not in_macro elif in_macro : macros [ elt ] = { 'val' : '' , 'type' : 'unknown' } return macros
def get_yaml_parser_roundtrip ( ) : """Create the yaml parser object with this factory method . The round - trip parser preserves : - comments - block style and key ordering are kept , so you can diff the round - tripped source - flow style sequences ( ‘ a : b , c , d ’ ) ( based on request and test by ...
yaml_writer = yamler . YAML ( typ = 'rt' , pure = True ) # if this isn ' t here the yaml doesn ' t format nicely indented for humans yaml_writer . indent ( mapping = 2 , sequence = 4 , offset = 2 ) return yaml_writer
def attr_subresource ( raml_resource , route_name ) : """Determine if : raml _ resource : is an attribute subresource . : param raml _ resource : Instance of ramlfications . raml . ResourceNode . : param route _ name : Name of the : raml _ resource : ."""
static_parent = get_static_parent ( raml_resource , method = 'POST' ) if static_parent is None : return False schema = resource_schema ( static_parent ) or { } properties = schema . get ( 'properties' , { } ) if route_name in properties : db_settings = properties [ route_name ] . get ( '_db_settings' , { } ) ...
def combine_sources ( sources , chunksize = None ) : r"""Combines multiple data sources to stream from . The given source objects ( readers and transformers , eg . TICA ) are concatenated in dimension axis during iteration . This can be used to couple arbitrary features in order to pass them to an Estimator exp...
from pyemma . coordinates . data . sources_merger import SourcesMerger return SourcesMerger ( sources , chunk = chunksize )
def match_envs ( declared_envs , desired_envs , passthru ) : """Determine the envs that match the desired _ envs . If ` ` passthru ` is True , and none of the declared envs match the desired envs , then the desired envs will be used verbatim . : param declared _ envs : The envs that are declared in the tox co...
matched = [ declared for declared in declared_envs if any ( env_matches ( declared , desired ) for desired in desired_envs ) ] return desired_envs if not matched and passthru else matched
def close ( self ) : """Close the file ."""
# ignore closing a closed file if not self . _is_open ( ) : return # for raw io , all writes are flushed immediately if self . allow_update and not self . raw_io : self . flush ( ) if self . _filesystem . is_windows_fs and self . _changed : self . file_object . st_mtime = time . time ( ) if self . _...
def ensure_ndarray_or_sparse ( A , shape = None , uniform = None , ndim = None , size = None , dtype = None , kind = None ) : r"""Ensures A is an ndarray or a scipy sparse matrix and does an assert _ array with the given parameters Returns A : ndarray If A is already an ndarray , it is just returned . Otherwi...
if not isinstance ( A , np . ndarray ) and not scisp . issparse ( A ) : try : A = np . array ( A ) except : raise AssertionError ( 'Given argument cannot be converted to an ndarray:\n' + str ( A ) ) assert_array ( A , shape = shape , uniform = uniform , ndim = ndim , size = size , dtype = dtype ...
def maximum_active_partitions ( self ) : """Integer : The maximum number of active logical partitions or partitions of this CPC . The following table shows the maximum number of active logical partitions or partitions by machine generations supported at the HMC API : Machine generation Maximum partitions ...
machine_type = self . get_property ( 'machine-type' ) try : max_parts = self . _MAX_PARTITIONS_BY_MACHINE_TYPE [ machine_type ] except KeyError : raise ValueError ( "Unknown machine type: {!r}" . format ( machine_type ) ) return max_parts
def present ( name , provider ) : '''Ensure the RackSpace queue exists . name Name of the Rackspace queue . provider Salt Cloud Provider'''
ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } } is_present = list ( __salt__ [ 'cloud.action' ] ( 'queues_exists' , provider = provider , name = name ) [ provider ] . values ( ) ) [ 0 ] if not is_present : if __opts__ [ 'test' ] : msg = 'Rackspace queue {0} is set to be created....
def get_for_model ( self , model ) : """Returns tuple ( Entry instance , created ) for specified model instance . : rtype : wagtailplus . wagtailrelations . models . Entry ."""
return self . get_or_create ( content_type = ContentType . objects . get_for_model ( model ) , object_id = model . pk )
def show ( name , root = None ) : '''. . versionadded : : 2014.7.0 Show properties of one or more units / jobs or the manager root Enable / disable / mask unit files in the specified root directory CLI Example : salt ' * ' service . show < service name >'''
ret = { } out = __salt__ [ 'cmd.run' ] ( _systemctl_cmd ( 'show' , name , root = root ) , python_shell = False ) for line in salt . utils . itertools . split ( out , '\n' ) : comps = line . split ( '=' ) name = comps [ 0 ] value = '=' . join ( comps [ 1 : ] ) if value . startswith ( '{' ) : valu...
def _loadData ( self , data ) : """Load attribute values from Plex XML response ."""
self . _data = data self . id = utils . cast ( int , data . attrib . get ( 'id' ) ) self . serverId = utils . cast ( int , data . attrib . get ( 'serverId' ) ) self . machineIdentifier = data . attrib . get ( 'machineIdentifier' ) self . name = data . attrib . get ( 'name' ) self . lastSeenAt = utils . toDatetime ( dat...
def restore_comments ( self , restore_data ) : """Restore comment styles and data"""
for start , end , styles , items in restore_data : log . debug ( "range: %d-%d" % ( start , end ) ) self . style [ start : end ] = styles for i in range ( start , end ) : rawindex , comment = items [ i ] if comment : log . debug ( " restoring comment: rawindex=%d, '%s'" % ( rawi...
def sort_members ( tup , names ) : """Return two pairs of members , scalar and tuple members . The scalars will be sorted s . t . the unbound members are at the top ."""
scalars , tuples = partition ( lambda x : not is_tuple_node ( tup . member [ x ] . value ) , names ) unbound , bound = partition ( lambda x : tup . member [ x ] . value . is_unbound ( ) , scalars ) return usorted ( unbound ) + usorted ( bound ) , usorted ( tuples )
def generate_html ( self , notifications ) : """Generates rendered HTML content using supplied notifications . : param notifications : Notification QuerySet Object : return : Rendered HTML ."""
html_chunks = [ ] for nf in notifications : extra = nf . as_json ( ) if self . target == 'box' else { } html = render_notification ( nf , render_target = self . target , ** extra ) html_chunks . append ( html ) if not html_chunks : html_chunks . append ( _ ( "<b>No notifications yet.</b>" ) ) html_strin...
def getIPaddresses ( self ) : """identify the IP addresses where this process client will launch the SC2 client"""
if not self . ipAddress : self . ipAddress = ipAddresses . getAll ( ) # update with IP address return self . ipAddress
def get_gateway_info ( self ) : """Return the gateway info . Returns a Command ."""
def process_result ( result ) : return GatewayInfo ( result ) return Command ( 'get' , [ ROOT_GATEWAY , ATTR_GATEWAY_INFO ] , process_result = process_result )
def filter_sum ( self , inst_rc , threshold , take_abs = True ) : '''Filter a network ' s rows or columns based on the sum across rows or columns .'''
inst_df = self . dat_to_df ( ) if inst_rc == 'row' : inst_df = run_filter . df_filter_row_sum ( inst_df , threshold , take_abs ) elif inst_rc == 'col' : inst_df = run_filter . df_filter_col_sum ( inst_df , threshold , take_abs ) self . df_to_dat ( inst_df )
def write ( self , mdata , name ) : """Write an input file to disk Parameters mdata : : obj : ` pymagicc . io . MAGICCData ` A MAGICCData instance with the data to write name : str The name of the file to write . The file will be written to the MAGICC instance ' s run directory i . e . ` ` self . run _ ...
mdata . write ( join ( self . run_dir , name ) , self . version )
def members ( self , name = None , status = None , tags = None ) : """Lists members of a Serf cluster , optionally filtered by one or more filters : ` name ` is a string , supporting regex matching on node names . ` status ` is a string , supporting regex matching on node status . ` tags ` is a dict of tag ...
filters = { } if name is not None : filters [ 'Name' ] = name if status is not None : filters [ 'Status' ] = status if tags is not None : filters [ 'Tags' ] = tags if len ( filters ) == 0 : return self . connection . call ( 'members' ) else : return self . connection . call ( 'members-filtered' , fi...
def load_from_args ( args ) : """Return a Loci object giving the loci specified on the command line . If no loci - related arguments are specified , return None . This makes it possible to distinguish an empty set of loci , for example due to filters removing all loci , from the case where the user didn ' t s...
if not args . locus : return None loci_iterator = ( Locus . parse ( locus ) for locus in args . locus ) # if args . neighbor _ offsets : # loci _ iterator = expand _ with _ neighbors ( # loci _ iterator , args . neighbor _ offsets ) return Loci ( loci_iterator )
def extend ( self , ampal_container ) : """Extends an ` AmpalContainer ` with another ` AmpalContainer ` ."""
if isinstance ( ampal_container , AmpalContainer ) : self . _ampal_objects . extend ( ampal_container ) else : raise TypeError ( 'Only AmpalContainer objects may be merged with ' 'an AmpalContainer.' ) return
def UploadImage ( client , filepath ) : """Uploads a . jpg image with the given filepath via the AdWords MediaService . Args : client : an AdWordsClient instance . filepath : a str filepath to the . jpg file to be uploaded . Returns : The created Image as a sudsobject ."""
media_service = client . GetService ( 'MediaService' , 'v201809' ) with open ( filepath , 'rb' ) as image_handle : image_data = image_handle . read ( ) . decode ( 'utf-8' ) image = [ { 'xsi_type' : 'Image' , 'data' : image_data , 'type' : 'IMAGE' } ] image = media_service . upload ( image ) [ 0 ] return image
def has_kwargs ( function ) : r'''Determine whether a function has \ * \ * kwargs . Parameters function : callable The function to test Returns True if function accepts arbitrary keyword arguments . False otherwise .'''
if six . PY2 : return inspect . getargspec ( function ) . keywords is not None else : sig = inspect . signature ( function ) for param in sig . parameters . values ( ) : if param . kind == param . VAR_KEYWORD : return True return False
def merge ( a , b ) : """Merge two unicode Robot Framework reports so that report ' b ' is merged into report ' a ' . This merge may not be complete and may be is lossy . Still , note that the original single test reports will remain untouched ."""
global loglevel # Iterate throughout the currently merged node set for child in b . iterchildren ( ) : # Merge suites if child . tag == 'suite' : source = child . get ( 'source' ) suites = a . xpath ( 'suite[@source="%s"]' % source ) # When matching suite is found , merge if suites :...
def percentile ( self , percentile ) : """Get a percentile of all floats in the map . Since the sorting is done in - place , the map is no longer safe to use after calling this or median ( )"""
percentile = float ( percentile ) if percentile != percentile or percentile < 0 or percentile > 100 : raise ValueError ( 'Expected a 0 <= percentile <= 100' ) result = c_float ( ) if not Gauged . map_percentile ( self . ptr , percentile , byref ( result ) ) : raise MemoryError return result . value
def download ( url ) : """输入文件url , 下载该文件"""
file_name = os . path . split ( url ) [ 1 ] file = urlopen ( url ) with open ( file_name , 'wb' ) as f : f . write ( file . read ( ) ) print ( "文件下载成功:%s " % file_name )
def check_collections_are_supported ( saved_model_handler , supported ) : """Checks that SavedModelHandler only uses supported collections ."""
for meta_graph in saved_model_handler . meta_graphs : used_collection_keys = set ( meta_graph . collection_def . keys ( ) ) unsupported = used_collection_keys - supported if unsupported : raise ValueError ( "Unsupported collections in graph: %s\n" "Use hub.create_module_spec(..., drop_collections=[....
def _createGsshaPyObjects ( self , mapTables , indexMaps , replaceParamFile , directory , session , spatial , spatialReferenceID ) : """Create GSSHAPY Mapping Table ORM Objects Method"""
for mt in mapTables : # Create GSSHAPY MapTable object try : # Make sure the index map name listed with the map table is in the list of # index maps read from the top of the mapping table file ( Note that the index maps for the sediment # and contaminant tables will have names of None , so we skip these cas...
def finish_parallel ( self ) : """Orderly shutdown of workers ."""
for process in self . processes : process . join ( ) # Shutdown the log thread log . debug ( 'Joining log thread' ) self . log_queue . put ( POISON_PILL ) self . log_thread . join ( ) self . log_queue . close ( ) # Close all queues log . debug ( 'Closing queues' ) self . task_queue . close ( ) self . result_queue ....
def _emit_to_memory ( self , module , use_object = False ) : """Returns bytes of object code of the module . Args use _ object : bool Emit object code or ( if False ) emit assembly code ."""
with ffi . OutputString ( ) as outerr : mb = ffi . lib . LLVMPY_TargetMachineEmitToMemory ( self , module , int ( use_object ) , outerr ) if not mb : raise RuntimeError ( str ( outerr ) ) bufptr = ffi . lib . LLVMPY_GetBufferStart ( mb ) bufsz = ffi . lib . LLVMPY_GetBufferSize ( mb ) try : return s...
def get_tunnel_info_output_tunnel_bfd_state ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_tunnel_info = ET . Element ( "get_tunnel_info" ) config = get_tunnel_info output = ET . SubElement ( get_tunnel_info , "output" ) tunnel = ET . SubElement ( output , "tunnel" ) bfd_state = ET . SubElement ( tunnel , "bfd-state" ) bfd_state . text = kwargs . pop ( 'bfd_state' ) cal...
def apply ( self , doc ) : """Generate MentionFigures from a Document by parsing all of its Figures . : param doc : The ` ` Document ` ` to parse . : type doc : ` ` Document ` ` : raises TypeError : If the input doc is not of type ` ` Document ` ` ."""
if not isinstance ( doc , Document ) : raise TypeError ( "Input Contexts to MentionFigures.apply() must be of type Document" ) for figure in doc . figures : if self . types is None or any ( figure . url . lower ( ) . endswith ( type ) for type in self . types ) : yield TemporaryFigureMention ( figure )
def product ( * args , ** kwargs ) : """Yields all permutations with replacement : list ( product ( " cat " , repeat = 2 ) ) = > [ ( " c " , " c " ) , ( " c " , " a " ) , ( " c " , " t " ) , ( " a " , " c " ) , ( " a " , " a " ) , ( " a " , " t " ) , ( " t " , " c " ) , ( " t " , " a " ) , ( " t...
p = [ [ ] ] for iterable in map ( tuple , args ) * kwargs . get ( "repeat" , 1 ) : p = [ x + [ y ] for x in p for y in iterable ] for p in p : yield tuple ( p )
def isempty ( path ) : """Returns True if the given file or directory path is empty . * * Examples * * : auxly . filesys . isempty ( " foo . txt " ) # Works on files . . . auxly . filesys . isempty ( " bar " ) # . . . or directories !"""
if op . isdir ( path ) : return [ ] == os . listdir ( path ) elif op . isfile ( path ) : return 0 == os . stat ( path ) . st_size return None
def query ( self , criteria , ** opts ) : """Returns a dict of the query , including the results : param critera : string of search criteria : param * * opts : : formats : json / xml ( default : json ) : timezone : timezone to use ( default : UTC ) : time _ from : 15m ago from now ( datetime ) : time _ ...
time_now = datetime . datetime . now ( ) . replace ( second = 0 , microsecond = 0 ) right_now = time_now . isoformat ( ) minutes_ago = ( time_now - datetime . timedelta ( minutes = 15 ) ) . isoformat ( ) formats = opts . get ( 'formats' , 'json' ) timezone = opts . get ( 'timezone' , 'UTC' ) time_from = opts . get ( 't...
def load ( self , addr , length = 1 ) : """Load one or more addresses . : param addr : byte address of load location : param length : All address from addr until addr + length ( exclusive ) are loaded ( default : 1)"""
if addr is None : return elif not isinstance ( addr , Iterable ) : self . first_level . load ( addr , length = length ) else : self . first_level . iterload ( addr , length = length )
def gen_columns_for_uninstrumented_class ( cls : Type ) -> Generator [ Tuple [ str , Column ] , None , None ] : """Generate ` ` ( attr _ name , Column ) ` ` tuples from an UNINSTRUMENTED class , i . e . one that does not inherit from ` ` declarative _ base ( ) ` ` . Use this for mixins of that kind . SUBOPTIM...
# noqa for attrname in dir ( cls ) : potential_column = getattr ( cls , attrname ) if isinstance ( potential_column , Column ) : yield attrname , potential_column
def GetTransPosition ( df , field , dic , refCol = "transcript_id" ) : """Maps a genome position to transcript positon " : param df : a Pandas dataframe : param field : the head of the column containing the genomic position : param dic : a dictionary containing for each transcript the respective bases eg . { ...
try : gen = str ( int ( df [ field ] ) ) transid = df [ refCol ] bases = dic . get ( transid ) . split ( "," ) bases = bases . index ( str ( gen ) ) + 1 except : bases = np . nan return bases
def stmts_to_json ( stmts_in , use_sbo = False ) : """Return the JSON - serialized form of one or more INDRA Statements . Parameters stmts _ in : Statement or list [ Statement ] A Statement or list of Statement objects to serialize into JSON . use _ sbo : Optional [ bool ] If True , SBO annotations are ad...
if not isinstance ( stmts_in , list ) : json_dict = stmts_in . to_json ( use_sbo = use_sbo ) return json_dict else : json_dict = [ st . to_json ( use_sbo = use_sbo ) for st in stmts_in ] return json_dict
def getControllerState ( self , unControllerDeviceIndex , unControllerStateSize = sizeof ( VRControllerState_t ) ) : """Fills the supplied struct with the current state of the controller . Returns false if the controller index is invalid . This function is deprecated in favor of the new IVRInput system ."""
fn = self . function_table . getControllerState pControllerState = VRControllerState_t ( ) result = fn ( unControllerDeviceIndex , byref ( pControllerState ) , unControllerStateSize ) return result , pControllerState
def overlay_gateway_monitor_session ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) overlay_gateway = ET . SubElement ( config , "overlay-gateway" , xmlns = "urn:brocade.com:mgmt:brocade-tunnels" ) name_key = ET . SubElement ( overlay_gateway , "name" ) name_key . text = kwargs . pop ( 'name' ) monitor = ET . SubElement ( overlay_gateway , "monitor" ) session = ET . ...
def ensure_dict ( param , default_value , default_key = None ) : """Retrieves a dict and a default value from given parameter . if parameter is not a dict , it will be promoted as the default value . : param param : : type param : : param default _ value : : type default _ value : : param default _ key ...
if not param : param = default_value if not isinstance ( param , dict ) : if param : default_value = param return { default_key : param } , default_value return param , default_value
def options ( self , context , module_options ) : '''THOROUGH Searches entire filesystem for certain file extensions ( default : False ) ALLDOMAIN Queries Active Direcotry for a list of all domain - joined computers and runs SessionGopher against all of them ( default : False )'''
self . thorough = False self . all_domain = False if 'THOROUGH' in module_options : self . thorough = bool ( module_options [ 'THOROUGH' ] ) if 'ALLDOMAIN' in module_options : self . all_domain = bool ( module_options [ 'ALLDOMAIN' ] ) self . ps_script2 = obfs_ps_script ( 'sessiongopher/SessionGopher.ps1' )
def strategy ( self ) : 'Returns resulting strategy that generates configured char set'
max_codepoint = None if self . _unicode else 127 strategies = [ ] if self . _negate : if self . _categories or self . _whitelist_chars : strategies . append ( hs . characters ( blacklist_categories = self . _categories | set ( [ 'Cc' , 'Cs' ] ) , blacklist_characters = self . _whitelist_chars , max_codepoin...
def _decodeUserData ( byteIter , userDataLen , dataCoding , udhPresent ) : """Decodes PDU user data ( UDHI ( if present ) and message text )"""
result = { } if udhPresent : # User Data Header is present result [ 'udh' ] = [ ] udhLen = next ( byteIter ) ieLenRead = 0 # Parse and store UDH fields while ieLenRead < udhLen : ie = InformationElement . decode ( byteIter ) ieLenRead += len ( ie ) result [ 'udh' ] . append (...
def enum_doc ( name , enum , header_level , source_location ) : """Generate markdown for an enum Parameters name : str Name of the thing being documented enum : EnumMeta Enum to document header _ level : int Heading level source _ location : str URL of repo containing source code"""
lines = [ f"{'#'*header_level} Enum **{name}**\n\n" ] lines . append ( f"```python\n{name}\n```\n" ) lines . append ( get_source_link ( enum , source_location ) ) try : doc = NumpyDocString ( inspect . getdoc ( thing ) ) . _parsed_data lines += summary ( doc ) except : pass lines . append ( f"{'#'*(header_l...
def visitPrefixDecl ( self , ctx : ShExDocParser . PrefixDeclContext ) : """prefixDecl : KW _ PREFIX PNAME _ NS IRIREF"""
iri = self . context . iriref_to_shexj_iriref ( ctx . IRIREF ( ) ) prefix = ctx . PNAME_NS ( ) . getText ( ) if iri not in self . context . ld_prefixes : self . context . prefixes . setdefault ( prefix , iri . val )