signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def step ( self , x ) : r"""perform a single Brownian dynamics step"""
return x - self . coeff_A * self . gradient ( x ) + self . coeff_B * np . random . normal ( size = self . dim )
def execute_sql ( server_context , schema_name , sql , container_path = None , max_rows = None , sort = None , offset = None , container_filter = None , save_in_session = None , parameters = None , required_version = None , timeout = _default_timeout ) : """Execute sql query against a LabKey server . : param serv...
url = server_context . build_url ( 'query' , 'executeSql.api' , container_path = container_path ) payload = { 'schemaName' : schema_name , 'sql' : sql } if container_filter is not None : payload [ 'containerFilter' ] = container_filter if max_rows is not None : payload [ 'maxRows' ] = max_rows if offset is not ...
def _generate_request ( self , callname , request ) : """Generate a request object for delivery to the API"""
# Retrieve path from API class schema = self . api . request_schema ( ) schema . context [ 'callname' ] = callname return schema . dump ( request ) . data . get ( "payload" )
def _create_response_record ( self , response ) : """Creates record for lexicon API calls"""
record = dict ( ) record [ 'id' ] = response [ 'id' ] record [ 'type' ] = response [ 'type' ] record [ 'name' ] = self . _full_name ( response [ 'name' ] ) if 'content' in response : record [ 'content' ] = response [ 'content' ] or "" if 'ttl' in response : record [ 'ttl' ] = response [ 'ttl' ] if 'prio' in res...
def _get_from_java_home ( self ) : """Retrieves the Java library path according to the JAVA _ HOME environment variable : return : The path to the JVM library , or None"""
# Get the environment variable java_home = os . getenv ( "JAVA_HOME" ) if java_home and os . path . exists ( java_home ) : # Get the real installation path java_home = os . path . realpath ( java_home ) # Cygwin has a bug in realpath if not os . path . exists ( java_home ) : java_home = os . getenv ...
def changelog_file_option_validator ( ctx , param , value ) : """Checks that the given file path exists in the current working directory . Returns a : class : ` ~ pathlib . Path ` object . If the file does not exist raises a : class : ` ~ click . UsageError ` exception ."""
path = Path ( value ) if not path . exists ( ) : filename = click . style ( path . name , fg = "blue" , bold = True ) ctx . fail ( "\n" f" {x_mark} Unable to find {filename}\n" ' Run "$ brau init" to create one' ) return path
def search_worker ( self , regex , directory_path , names , binary = False , callback = None ) : """build a DirectoryResult for the given regex , directory path , and file names"""
try : result = DirectoryResult ( directory_path ) def find_matches ( name ) : full_path = path . join ( directory_path , name ) file_contents = get_file_contents ( full_path , binary ) start = 0 match = regex . search ( file_contents , start ) while match : re...
def indexbox ( msg = "Shall I continue?" , title = " " , choices = ( "Yes" , "No" ) , image = None ) : """Display a buttonbox with the specified choices . Return the index of the choice selected ."""
reply = buttonbox ( msg = msg , choices = choices , title = title , image = image ) index = - 1 for choice in choices : index = index + 1 if reply == choice : return index raise AssertionError ( "There is a program logic error in the EasyGui code for indexbox." )
def multi_p_run ( tot_num , _func , worker , params , n_process ) : """Run _ func with multi - process using params ."""
from multiprocessing import Process , Queue out_q = Queue ( ) procs = [ ] split_num = split_seq ( list ( range ( 0 , tot_num ) ) , n_process ) print ( tot_num , ">>" , split_num ) split_len = len ( split_num ) if n_process > split_len : n_process = split_len for i in range ( n_process ) : _p = Process ( target ...
def present ( name , level , devices , ** kwargs ) : '''Verify that the raid is present . . versionchanged : : 2014.7.0 name The name of raid device to be created level The RAID level to use when creating the raid . devices A list of devices used to build the array . kwargs Optional arguments to b...
ret = { 'changes' : { } , 'comment' : '' , 'name' : name , 'result' : True } # Device exists raids = __salt__ [ 'raid.list' ] ( ) present = raids . get ( name ) # Decide whether to create or assemble missing = [ ] uuid_dict = { } new_devices = [ ] for dev in devices : if dev == 'missing' or not __salt__ [ 'file.acc...
def merge_equal_neighbors ( self ) : """Merge neighbors with same speaker ."""
IDX_LENGTH = 3 merged = self . segs . copy ( ) current_start = 0 j = 0 seg = self . segs . iloc [ 0 ] for i in range ( 1 , self . num_segments ) : seg = self . segs . iloc [ i ] last = self . segs . iloc [ i - 1 ] if seg . speaker == last . speaker : merged . iat [ j , IDX_LENGTH ] = seg . start + s...
def _handle_start_node ( self , attrs ) : """Handle opening node element : param attrs : Attributes of the element : type attrs : Dict"""
self . _curr = { 'attributes' : dict ( attrs ) , 'lat' : None , 'lon' : None , 'node_id' : None , 'tags' : { } } if attrs . get ( 'id' , None ) is not None : self . _curr [ 'node_id' ] = int ( attrs [ 'id' ] ) del self . _curr [ 'attributes' ] [ 'id' ] if attrs . get ( 'lat' , None ) is not None : self . _c...
def _from_frame ( cls , frame ) : "Copy constructor"
assert frame . _framespec == cls . _framespec new = cls ( flags = frame . flags , frameno = frame . frameno ) for spec in cls . _framespec : setattr ( new , spec . name , getattr ( frame , spec . name , None ) ) return new
def delete_where_user_id ( cls , user_id ) : """delete by email"""
result = cls . where_user_id ( user_id ) if result is None : return None result . delete ( ) return True
def parse_GPL ( filepath , entry_name = None , partial = None ) : """Parse GPL entry from SOFT file . Args : filepath ( : obj : ` str ` or : obj : ` Iterable ` ) : Path to file with 1 GPL entry or list of lines representing GPL from GSE file . entry _ name ( : obj : ` str ` , optional ) : Name of the entry ...
gsms = { } gses = { } gpl_soft = [ ] has_table = False gpl_name = entry_name database = None if isinstance ( filepath , str ) : with utils . smart_open ( filepath ) as soft : groupper = groupby ( soft , lambda x : x . startswith ( "^" ) ) for is_new_entry , group in groupper : if is_new_...
def download ( link , outdir = '.' , chunk_size = 4096 ) : '''This is the Main function , which downloads a given link and saves on outdir ( default = current directory )'''
url = None fh = None eta = 'unknown ' bytes_so_far = 0 filename = filename_from_url ( link ) or "." cj = cjar . CookieJar ( ) # get filename for temp file in current directory ( fd_tmp , tmpfile ) = tempfile . mkstemp ( ".tmp" , prefix = filename + "." , dir = outdir ) os . close ( fd_tmp ) os . unlink ( tmpfile ) try ...
def _get_criteria_matching_disks ( logical_disk , physical_drives ) : """Finds the physical drives matching the criteria of logical disk . This method finds the physical drives matching the criteria of the logical disk passed . : param logical _ disk : The logical disk dictionary from raid config : param ph...
matching_physical_drives = [ ] criteria_to_consider = [ x for x in FILTER_CRITERIA if x in logical_disk ] for physical_drive_object in physical_drives : for criteria in criteria_to_consider : logical_drive_value = logical_disk . get ( criteria ) physical_drive_value = getattr ( physical_drive_object...
def add_optionals ( self , optionals_in , optionals_out ) : """Add optional inputs and outputs to the model spec . Parameters optionals _ in : [ str ] List of inputs that are optionals . optionals _ out : [ str ] List of outputs that are optionals . See Also set _ input , set _ output"""
spec = self . spec if ( not optionals_in ) and ( not optionals_out ) : return # assuming single sizes here input_types = [ datatypes . Array ( dim ) for ( name , dim ) in optionals_in ] output_types = [ datatypes . Array ( dim ) for ( name , dim ) in optionals_out ] input_names = [ str ( name ) for ( name , dim ) i...
def _build ( self , inputs , prev_state ) : """Connects the GRU module into the graph . If this is not the first time the module has been connected to the graph , the Tensors provided as inputs and state must have the same final dimension , in order for the existing variables to be the correct size for thei...
input_size = inputs . get_shape ( ) [ 1 ] weight_shape = ( input_size , self . _hidden_size ) u_shape = ( self . _hidden_size , self . _hidden_size ) bias_shape = ( self . _hidden_size , ) self . _wz = tf . get_variable ( GRU . WZ , weight_shape , dtype = inputs . dtype , initializer = self . _initializers . get ( GRU ...
def authenticate ( self , username = None , password = None , ** kwargs ) : """" username " being passed is really email address and being compared to as such ."""
try : user = User . objects . get ( email = username ) if user . check_password ( password ) : return user except ( User . DoesNotExist , User . MultipleObjectsReturned ) : logging . warning ( 'Unsuccessful login attempt using username/email: {0}' . format ( username ) ) return None
def _format_data ( self , data , charset ) : """Format data into XML ."""
if data is None or data == '' : return u'' stream = StringIO . StringIO ( ) xml = SimplerXMLGenerator ( stream , charset ) xml . startDocument ( ) xml . startElement ( self . _root_element_name ( ) , { } ) self . _to_xml ( xml , data ) xml . endElement ( self . _root_element_name ( ) ) xml . endDocument ( ) return ...
def match_rules ( tree , rules , fun = None , multi = False ) : """Matches a Tree structure with the given query rules . Query rules are represented as a dictionary of template to action . Action is either a function , or a dictionary of subtemplate parameter to rules : : rules = { ' template ' : { ' key ' : ...
if multi : context = match_rules_context_multi ( tree , rules ) else : context = match_rules_context ( tree , rules ) if not context : return None if fun : args = fun . __code__ . co_varnames if multi : res = [ ] for c in context : action_context = { } ...
def download ( url , params = None , accept = "xml" , ** kwds ) : """Helper function to download a file and return its content . Parameters url : string The URL to be parsed . params : dict ( optional ) Dictionary containing query parameters . For required keys and accepted values see e . g . https : ...
# Value check accepted = ( "json" , "xml" , "atom+xml" ) if accept . lower ( ) not in accepted : raise ValueError ( 'accept parameter must be one of ' + ', ' . join ( accepted ) ) # Get credentials key = config . get ( 'Authentication' , 'APIKey' ) header = { 'X-ELS-APIKey' : key } if config . has_option ( 'Authent...
def removeClass ( self , * classes : str ) -> None : """[ Not Standard ] Remove classes from this node ."""
_remove_cl = [ ] for class_ in classes : if class_ not in self . classList : if class_ in self . get_class_list ( ) : logger . warning ( 'tried to remove class-level class: ' '{}' . format ( class_ ) ) else : logger . warning ( 'tried to remove non-existing class: {}' . forma...
def Run ( self , args ) : """Run ."""
# Open the file . fd = vfs . VFSOpen ( args . pathspec , progress_callback = self . Progress ) if args . address_family == rdf_client_network . NetworkAddress . Family . INET : family = socket . AF_INET elif args . address_family == rdf_client_network . NetworkAddress . Family . INET6 : family = socket . AF_INE...
def get_obj ( self , objpath , metahash , dst_path ) : """Get object from cache , write it to dst _ path . Args : objpath : filename relative to buildroot ( example : mini - boot / blahblah / somefile . bin ) metahash : metahash . See targets / base . py dst _ path : Absolute path where the file should be...
incachepath = self . path_in_cache ( objpath , metahash ) if not os . path . exists ( incachepath ) : raise CacheMiss ( '%s not in cache.' % incachepath ) else : log . debug ( 'Cache hit! %s~%s' , objpath , metahash . hexdigest ( ) ) if not os . path . exists ( os . path . dirname ( dst_path ) ) : o...
def eeg_to_df ( eeg , index = None , include = "all" , exclude = None , hemisphere = "both" , central = True ) : """Convert mne Raw or Epochs object to dataframe or dict of dataframes . DOCS INCOMPLETE : ("""
if isinstance ( eeg , mne . Epochs ) : data = { } if index is None : index = range ( len ( eeg ) ) for epoch_index , epoch in zip ( index , eeg . get_data ( ) ) : epoch = pd . DataFrame ( epoch . T ) epoch . columns = eeg . ch_names epoch . index = eeg . times selecti...
def search_for_vcs ( self , dependency ) : # type : ( VCSDependency ) - > List [ Package ] """Search for the specifications that match the given VCS dependency . Basically , we clone the repository in a temporary directory and get the information we need by checking out the specified reference ."""
if dependency . vcs != "git" : raise ValueError ( "Unsupported VCS dependency {}" . format ( dependency . vcs ) ) tmp_dir = Path ( mkdtemp ( prefix = "pypoetry-git-{}" . format ( dependency . name ) ) ) try : git = Git ( ) git . clone ( dependency . source , tmp_dir ) git . checkout ( dependency . refer...
def occurs_in_type ( v , type2 ) : """Checks whether a type variable occurs in a type expression . Note : Must be called with v pre - pruned Args : v : The TypeVariable to be tested for type2 : The type in which to search Returns : True if v occurs in type2 , otherwise False"""
pruned_type2 = prune ( type2 ) if pruned_type2 == v : return True elif isinstance ( pruned_type2 , TypeOperator ) : return occurs_in ( v , pruned_type2 . types ) return False
def expectScreen ( self , filename , maxrms = 0 ) : """Wait until the display matches a target image filename : an image file to read and compare against maxrms : the maximum root mean square between histograms of the screen and target image"""
log . debug ( 'expectScreen %s' , filename ) return self . _expectFramebuffer ( filename , 0 , 0 , maxrms )
def intermediate_cpfs ( self ) -> List [ CPF ] : '''Returns list of intermediate - fluent CPFs in level order .'''
_ , cpfs = self . cpfs interm_cpfs = [ cpf for cpf in cpfs if cpf . name in self . intermediate_fluents ] interm_cpfs = sorted ( interm_cpfs , key = lambda cpf : ( self . intermediate_fluents [ cpf . name ] . level , cpf . name ) ) return interm_cpfs
def _json_to_subscriptions ( response_body ) : """Returns a list of Subscription objects"""
data = json . loads ( response_body ) subscriptions = [ ] for subscription_data in data . get ( "subscriptionList" , [ ] ) : subscriptions . append ( Subscription ( ) . from_json ( data . get ( 'uwNetID' ) , subscription_data ) ) return subscriptions
def validate ( self , value , validator ) : """Validates and returns the value . If the value does not validate against the schema , SchemaValidationError will be raised . : param value : A value to validate ( usually a dict ) . : param validator : An instance of a jsonschema validator class , as created ...
try : validator . validate ( value ) except Exception as e : logging . debug ( e , exc_info = e ) if isinstance ( e , DoctorError ) : raise else : # Gather all the validation errors validation_errors = sorted ( validator . iter_errors ( value ) , key = lambda e : e . path ) error...
def dbus_readBytesTwoFDs ( self , fd1 , fd2 , byte_count ) : """Reads byte _ count from fd1 and fd2 . Returns concatenation ."""
result = bytearray ( ) for fd in ( fd1 , fd2 ) : f = os . fdopen ( fd , 'rb' ) result . extend ( f . read ( byte_count ) ) f . close ( ) return result
def speziale_grun ( v , v0 , gamma0 , q0 , q1 ) : """calculate Gruneisen parameter for the Speziale equation : param v : unit - cell volume in A ^ 3 : param v0 : unit - cell volume in A ^ 3 at 1 bar : param gamma0 : Gruneisen parameter at 1 bar : param q0 : logarithmic derivative of Gruneisen parameter : ...
if isuncertainties ( [ v , v0 , gamma0 , q0 , q1 ] ) : gamma = gamma0 * unp . exp ( q0 / q1 * ( ( v / v0 ) ** q1 - 1. ) ) else : gamma = gamma0 * np . exp ( q0 / q1 * ( ( v / v0 ) ** q1 - 1. ) ) return gamma
def scrape_wikinews ( conn , project , articleset , query ) : """Scrape wikinews articles from the given query @ param conn : The AmcatAPI object @ param articleset : The target articleset ID @ param category : The wikinews category name"""
url = "http://en.wikinews.org/w/index.php?search={}&limit=50" . format ( query ) logging . info ( url ) for page in get_pages ( url ) : urls = get_article_urls ( page ) arts = list ( get_articles ( urls ) ) logging . info ( "Adding {} articles to set {}:{}" . format ( len ( arts ) , project , articleset ) )...
def wait_for_n_keypresses ( self , key , n = 1 ) : """Waits till one key was pressed n times . : param key : the key to be pressed as defined by pygame . E . g . pygame . K _ LEFT for the left arrow key : type key : int : param n : number of repetitions till the function returns : type n : int"""
my_const = "key_consumed" counter = 0 def keypress_listener ( e ) : return my_const if e . type == pygame . KEYDOWN and e . key == key else EventConsumerInfo . DONT_CARE while counter < n : if self . listen ( keypress_listener ) == my_const : counter += 1
def get_current_transport_info ( self ) : """Get the current playback state . Returns : dict : The following information about the speaker ' s playing state : * current _ transport _ state ( ` ` PLAYING ` ` , ` ` TRANSITIONING ` ` , ` ` PAUSED _ PLAYBACK ` ` , ` ` STOPPED ` ` ) * current _ transport _ s...
response = self . avTransport . GetTransportInfo ( [ ( 'InstanceID' , 0 ) , ] ) playstate = { 'current_transport_status' : '' , 'current_transport_state' : '' , 'current_transport_speed' : '' } playstate [ 'current_transport_state' ] = response [ 'CurrentTransportState' ] playstate [ 'current_transport_status' ] = resp...
def max_interval_intersec ( S ) : """determine a value that is contained in a largest number of given intervals : param S : list of half open intervals : complexity : O ( n log n ) , where n = len ( S )"""
B = ( [ ( left , + 1 ) for left , right in S ] + [ ( right , - 1 ) for left , right in S ] ) B . sort ( ) c = 0 best = ( c , None ) for x , d in B : c += d if best [ 0 ] < c : best = ( c , x ) return best
def null_space ( M , k , k_skip = 1 , eigen_solver = 'arpack' , random_state = None , solver_kwds = None ) : """Find the null space of a matrix M : eigenvectors associated with 0 eigenvalues Parameters M : { array , matrix , sparse matrix , LinearOperator } Input covariance matrix : should be symmetric positi...
eigen_solver , solver_kwds = check_eigen_solver ( eigen_solver , solver_kwds , size = M . shape [ 0 ] , nvec = k + k_skip ) random_state = check_random_state ( random_state ) if eigen_solver == 'arpack' : # This matches the internal initial state used by ARPACK v0 = random_state . uniform ( - 1 , 1 , M . shape [ 0 ...
def txn_storeAssociation ( self , server_url , association ) : """Set the association for the server URL . Association - > NoneType"""
a = association self . db_set_assoc ( server_url , a . handle , self . blobEncode ( a . secret ) , a . issued , a . lifetime , a . assoc_type )
def do_p ( self , arg ) : """p expression Print the value of the expression ."""
try : self . message ( bdb . safe_repr ( self . _getval ( arg ) ) ) except Exception : pass
async def download_file ( self , file_path : base . String , destination : Optional [ base . InputFile ] = None , timeout : Optional [ base . Integer ] = sentinel , chunk_size : Optional [ base . Integer ] = 65536 , seek : Optional [ base . Boolean ] = True ) -> Union [ io . BytesIO , io . FileIO ] : """Download fi...
if destination is None : destination = io . BytesIO ( ) url = api . Methods . file_url ( token = self . __token , path = file_path ) dest = destination if isinstance ( destination , io . IOBase ) else open ( destination , 'wb' ) async with self . session . get ( url , timeout = timeout , proxy = self . proxy , prox...
def plot_rank ( data , var_names = None , coords = None , bins = None , ref_line = True , figsize = None , axes = None ) : """Plot rank order statistics of chains . From the paper : Rank plots are histograms of the ranked posterior draws ( ranked over all chains ) plotted separately for each chain . If all of...
posterior_data = convert_to_dataset ( data , group = "posterior" ) if coords is not None : posterior_data = posterior_data . sel ( ** coords ) var_names = _var_names ( var_names , posterior_data ) plotters = list ( xarray_var_iter ( posterior_data , var_names = var_names , combined = True ) ) if bins is None : # Us...
def flush ( self ) : """Commit backing storage to disk This method is largely internal , and it is not necessary to call this from user code . It should not be explicitly invoked and may be removed in future versions ."""
if self . kind == TraceField : self . filehandle . putth ( self . traceno , self . buf ) elif self . kind == BinField : self . filehandle . putbin ( self . buf ) else : msg = 'Object corrupted: kind {} not valid' raise RuntimeError ( msg . format ( self . kind ) )
def content_break ( self , el ) : """Break on specified boundaries ."""
should_break = False if self . type == 'odp' : if el . name == 'page' and el . namespace and el . namespace == self . namespaces [ 'draw' ] : should_break = True return should_break
def parse ( some_text , ** kwargs ) : """Creates request to AddressParser and returns list of Address objects"""
ap = parser . AddressParser ( ** kwargs ) return ap . parse ( some_text )
def get ( cls , xuid , scid , clip_id ) : '''Gets a specific game clip : param xuid : xuid of an xbox live user : param scid : scid of a clip : param clip _ id : id of a clip'''
url = ( 'https://gameclipsmetadata.xboxlive.com/users' '/xuid(%(xuid)s)/scids/%(scid)s/clips/%(clip_id)s' % { 'xuid' : xuid , 'scid' : scid , 'clip_id' : clip_id , } ) resp = xbox . client . _get ( url ) # scid does not seem to matter when fetching clips , # as long as it looks like a uuid it should be fine . # perhaps...
def getPID ( self ) : """Returns the PID for the associated app ( or - 1 , if no app is associated or the app is not running )"""
if self . _pid is not None : if not PlatformManager . isPIDValid ( self . _pid ) : self . _pid = - 1 return self . _pid return - 1
def update ( self , * , name = None , position = None , visibility = None ) : """Changes the name , position or visibility of this worksheet"""
if name is None and position is None and visibility is None : raise ValueError ( 'Provide at least one parameter to update' ) data = { } if name : data [ 'name' ] = name if position : data [ 'position' ] = position if visibility : data [ 'visibility' ] = visibility response = self . session . patch ( se...
def _get_rs_id ( variant , rs_map , variant_type ) : """Given a variant dict , return unambiguous RS ID TODO Some sequence alterations appear to have mappings to dbsnp ' s notation for example , reference allele : TTTTT variant allele : TTTTT Is theoretically the same as - / T , we should clarify with U...
rs_id = None if variant_type == 'snp' : variant_key = "{0}-{1}" . format ( variant [ 'chromosome' ] , variant [ 'position' ] ) if variant_key in rs_map : snp_candidates = [ rs_dict for rs_dict in rs_map [ variant_key ] if rs_dict [ 'type' ] == 'snp' ] if len ( snp_candidates ) == 1 : ...
def set_key ( key , value , host = None , port = None , db = None , password = None ) : '''Set redis key value CLI Example : . . code - block : : bash salt ' * ' redis . set _ key foo bar'''
server = _connect ( host , port , db , password ) return server . set ( key , value )
def eagle ( args ) : """% prog eagle fastafile"""
p = OptionParser ( eagle . __doc__ ) p . add_option ( "--share" , default = "/usr/local/share/EAGLE/" , help = "Default EAGLE share path" ) add_sim_options ( p ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastafile , = args share = opts . share depth = opts . ...
def read_config ( config_path = CONFIG_PATH ) : """Read the config information from the config file . Args : config _ path ( str ) : Relative path to the email config file . Returns : defaultdict : A defaultdict with the config information . Raises : IOError"""
if not os . path . isfile ( config_path ) : raise IOError ( "No config file found at %s" % config_path ) config_parser = configparser . ConfigParser ( ) config_parser . read ( config_path ) config = _config_parser_to_defaultdict ( config_parser ) return config
def search_pages ( self , page_ids = None , begin = 0 , count = 10 ) : """查询页面列表 详情请参考 http : / / mp . weixin . qq . com / wiki / 5/6626199ea8757c752046d8e46cf13251 . html : param page _ ids : 指定页面的id列表 : param begin : 页面列表的起始索引值 : param count : 待查询的页面个数 : return : 页面查询结果信息"""
if not page_ids : data = { 'type' : 2 , 'begin' : begin , 'count' : count } else : if not isinstance ( page_ids , ( tuple , list ) ) : page_ids = [ page_ids ] data = { 'type' : 1 , 'page_ids' : page_ids } res = self . _post ( 'shakearound/page/search' , data = data , result_processor = lambda x : x ...
def fpy_interface ( fpy , static , interface , typedict ) : """Splices the full list of subroutines and the module procedure list into the static . f90 file . : arg static : the string contents of the static . f90 file . : arg interface : the name of the interface * field * being replaced . : arg typedict :...
modprocs = [ ] subtext = [ ] for dtype , combos in list ( typedict . items ( ) ) : for tcombo in combos : kind , suffix = tcombo xnames , sub = fpy_interface_sub ( fpy , dtype , kind , suffix ) modprocs . extend ( xnames ) subtext . append ( sub ) subtext . append ( "\n" ) # Next...
def modifyInPlace ( self , * , sort = None , purge = False , done = None ) : """Like Model . modify , but changes existing database instead of returning a new one ."""
self . data = self . modify ( sort = sort , purge = purge , done = done )
def _decimal_to_128 ( value ) : """Converts a decimal . Decimal to BID ( high bits , low bits ) . : Parameters : - ` value ` : An instance of decimal . Decimal"""
with decimal . localcontext ( _DEC128_CTX ) as ctx : value = ctx . create_decimal ( value ) if value . is_infinite ( ) : return _NINF if value . is_signed ( ) else _PINF sign , digits , exponent = value . as_tuple ( ) if value . is_nan ( ) : if digits : raise ValueError ( "NaN with debug payload is ...
def switch_to_table ( self , event ) : """Switches grid to table Parameters event . newtable : Integer \t Table that the grid is switched to"""
newtable = event . newtable no_tabs = self . grid . code_array . shape [ 2 ] - 1 if 0 <= newtable <= no_tabs : self . grid . current_table = newtable self . grid . SetToolTip ( None ) # Delete renderer cache self . grid . grid_renderer . cell_cache . clear ( ) # Delete video cells video_cells = ...
def draw_scatter_plot ( world , size , target ) : """This function can be used on a generic canvas ( either an image to save on disk or a canvas part of a GUI )"""
# Find min and max values of humidity and temperature on land so we can # normalize temperature and humidity to the chart humid = numpy . ma . masked_array ( world . layers [ 'humidity' ] . data , mask = world . layers [ 'ocean' ] . data ) temp = numpy . ma . masked_array ( world . layers [ 'temperature' ] . data , mas...
def string ( self , * args ) : """return string stored in node"""
data = self . bytes ( * args ) if data is not None : return data . rstrip ( b"\x00" ) . decode ( 'utf-8' )
def wrap_text ( paragraph , line_count , min_char_per_line = 0 ) : """Wraps the given text to the specified number of lines ."""
one_string = strip_all_white_space ( paragraph ) if min_char_per_line : lines = wrap ( one_string , width = min_char_per_line ) try : return lines [ : line_count ] except IndexError : return lines else : return wrap ( one_string , len ( one_string ) / line_count )
def read_tb ( path ) : """path : a tensorboard file OR a directory , where we will find all TB files of the form events . *"""
import pandas import numpy as np from glob import glob from collections import defaultdict import tensorflow as tf if osp . isdir ( path ) : fnames = glob ( osp . join ( path , "events.*" ) ) elif osp . basename ( path ) . startswith ( "events." ) : fnames = [ path ] else : raise NotImplementedError ( "Expe...
def _parse_doc ( doc = '' ) : """Parse a docstring into title and description . Args doc : str A docstring , optionally with a title line , separated from a description line by at least one blank line . Returns title : str The first line of the docstring . description : str The rest of a docstring...
title , description = '' , '' if doc : sp = doc . split ( '\n' , 1 ) title = sp [ 0 ] . strip ( ) if len ( sp ) > 1 : description = textwrap . dedent ( sp [ 1 ] ) . strip ( ) return ( title , description )
def authenticate ( self , auth_url = None , ** kwargs ) : """Authenticates a user via the Keystone Identity API ."""
LOG . debug ( 'Beginning user authentication' ) if not auth_url : auth_url = settings . OPENSTACK_KEYSTONE_URL auth_url , url_fixed = utils . fix_auth_url_version_prefix ( auth_url ) if url_fixed : LOG . warning ( "The OPENSTACK_KEYSTONE_URL setting points to a v2.0 " "Keystone endpoint, but v3 is specified as ...
def _pusher_connect_handler ( self , data ) : """Event handler for the connection _ established event . Binds the shortlink _ scanned event"""
self . channel = self . pusher . subscribe ( self . pos_callback_chan ) for listener in self . pusher_connected_listeners : listener ( data )
def _validate_json_for_global_workflow ( json_spec , args ) : """Validates fields used for building a global workflow . Since building a global workflow is done after all the underlying workflows are built , which may be time - consuming , we validate as much as possible here ."""
# TODO : verify the billTo can build the workflow # TODO : if the global workflow build fails add an option to interactively change billto # TODO : ( or other simple fields ) instead of failing altogether # TODO : get a confirmation before building a workflow that may be costly if 'name' not in json_spec : raise Wo...
def plot_roc_curve ( y_true , y_probas , title = 'ROC Curves' , curves = ( 'micro' , 'macro' , 'each_class' ) , ax = None , figsize = None , cmap = 'nipy_spectral' , title_fontsize = "large" , text_fontsize = "medium" ) : """Generates the ROC curves from labels and predicted scores / probabilities Args : y _ tr...
y_true = np . array ( y_true ) y_probas = np . array ( y_probas ) if 'micro' not in curves and 'macro' not in curves and 'each_class' not in curves : raise ValueError ( 'Invalid argument for curves as it ' 'only takes "micro", "macro", or "each_class"' ) classes = np . unique ( y_true ) probas = y_probas fpr = dict...
def stdout_redirector ( ) : """Simplify redirect of stdout . Taken from here : https : / / eli . thegreenplace . net / 2015 / redirecting - all - kinds - of - stdout - in - python /"""
old_stdout = sys . stdout sys . stdout = Stream ( ) try : yield sys . stdout finally : sys . stdout . close ( ) sys . stdout = old_stdout
def _get_implied_apps ( self , detected_apps ) : """Get the set of apps implied by ` detected _ apps ` ."""
def __get_implied_apps ( apps ) : _implied_apps = set ( ) for app in apps : try : _implied_apps . update ( set ( self . apps [ app ] [ 'implies' ] ) ) except KeyError : pass return _implied_apps implied_apps = __get_implied_apps ( detected_apps ) all_implied_apps = se...
def set_of_vars ( arg_plot ) : """Build set of needed variables . Args : arg _ plot ( str ) : string with variable names separated with ` ` , ` ` . Returns : set of str : set of variables ."""
return set ( var for var in arg_plot . split ( ',' ) if var in phyvars . PLATES )
def main ( ) -> None : """The main CLI interface entry point ."""
parser = argparse . ArgumentParser ( description = "Security analysis of Ethereum smart contracts" ) create_parser ( parser ) # Get config values args = parser . parse_args ( ) parse_args ( parser = parser , args = args )
def get_point_index ( point , all_points , eps = 1e-4 ) : """Get the index of a point in an array"""
inds = np . where ( np . linalg . norm ( point - all_points , axis = 1 ) < eps ) if inds [ 0 ] . shape [ 0 ] == 0 : return - 1 return inds [ 0 ] [ 0 ]
def _m_to_e ( cls , e , M ) : """Conversion from Mean Anomaly to Eccentric anomaly Procedures for solving Kepler ' s Equation , A . W . Odell and R . H . Gooding , Celestial Mechanics 38 ( 1986 ) 307-334"""
k1 = 3 * np . pi + 2 k2 = np . pi - 1 k3 = 6 * np . pi - 1 A = 3 * k2 ** 2 / k1 B = k3 ** 2 / ( 6 * k1 ) m1 = float ( M ) if abs ( m1 ) < 1 / 6 : E = m1 + e * ( 6 * m1 ) ** ( 1 / 3 ) - m1 elif m1 < 0 : w = np . pi + m1 E = m1 + e * ( A * w / ( B - w ) - np . pi - m1 ) else : w = np . pi - m1 E = m1 ...
def find_stages ( document ) : """Find * * stages * * in document . Args : document ( dict ) : validated spline document loaded from a yaml file . Returns : list : stages as a part of the spline document or an empty list if not given . > > > find _ stages ( { ' pipeline ' : [ { ' stage ( Prepare ) ' : 1 }...
names = [ ] if 'pipeline' in document : for entry in document [ 'pipeline' ] : # each entry is dictionary with one key only key , _ = list ( entry . items ( ) ) [ 0 ] if key . startswith ( "stage(" ) : names . append ( key . replace ( 'stage(' , '' ) . replace ( ')' , '' ) ) return names
def batch_get ( self , offset = 0 , count = 50 , status_list = None ) : """批量查询卡券信息"""
card_data = { 'offset' : offset , 'count' : count } if status_list : card_data [ 'status_list' ] = status_list return self . _post ( 'card/batchget' , data = card_data )
def pipecmd ( cmd1 , cmd2 ) : """Return output of " cmd1 | cmd2 " ."""
p1 = subprocess . Popen ( cmd1 , stdout = subprocess . PIPE ) p2 = subprocess . Popen ( cmd2 , stdin = p1 . stdout , stdout = subprocess . PIPE ) p1 . stdout . close ( ) # Allow p1 to receive a SIGPIPE if p2 exits . return p2 . communicate ( ) [ 0 ]
def apply_plugin_settings ( self , options ) : """Apply configuration file ' s plugin settings"""
font_n = 'plugin_font' font_o = self . get_plugin_font ( ) help_n = 'connect_to_oi' help_o = CONF . get ( 'help' , 'connect/ipython_console' ) color_scheme_n = 'color_scheme_name' color_scheme_o = CONF . get ( 'appearance' , 'selected' ) show_time_n = 'show_elapsed_time' show_time_o = self . get_option ( show_time_n ) ...
def accept ( self ) : # type : ( ) - > str """The content - type for the response to the client . Returns : ( str ) : The value of the header ' Accept ' or the user - supplied SAGEMAKER _ DEFAULT _ INVOCATIONS _ ACCEPT environment variable ."""
accept = self . headers . get ( 'Accept' ) if not accept or accept == _content_types . ANY : return self . _default_accept else : return accept
def reduce_to_2d ( arr ) : """Given a np . npdarray with nDims > 2 , reduce it to 2d . It does this by selecting the zeroth coordinate for every dimension greater than two . Args : arr : a numpy ndarray of dimension at least 2. Returns : A two - dimensional subarray from the input array . Raises : V...
if not isinstance ( arr , np . ndarray ) : raise ValueError ( 'reduce_to_2d requires a numpy.ndarray' ) ndims = len ( arr . shape ) if ndims < 2 : raise ValueError ( 'reduce_to_2d requires an array of dimensionality >=2' ) # slice ( None ) is equivalent to ` : ` , so we take arr [ 0,0 , . . . 0 , : , : ] slices...
def get_arguments ( ) : """Get parsed arguments ."""
parser = argparse . ArgumentParser ( "Lupupy: Command Line Utility" ) parser . add_argument ( '-u' , '--username' , help = 'Username' , required = False ) parser . add_argument ( '-p' , '--password' , help = 'Password' , required = False ) parser . add_argument ( '--arm' , help = 'Arm alarm to mode' , required = False ...
async def update ( self ) : """Updates this interface ' s messages with the latest data ."""
if self . update_lock . locked ( ) : return async with self . update_lock : if self . update_lock . locked ( ) : # if this engagement has caused the semaphore to exhaust , # we are overloaded and need to calm down . await asyncio . sleep ( 1 ) if not self . message : # too fast , stagger so this...
def validate_err_calc ( val ) : """Validation function for the : attr : ` psy _ simple . plotter . FldmeanPlotter . err _ calc ` formatoption"""
try : val = validate_float ( val ) except ( ValueError , TypeError ) : pass else : if val <= 100 and val >= 0 : return val raise ValueError ( "Percentiles for the error calculation must lie " "between 0 and 100, not %s" % val ) try : val = ValidateList ( float , 2 ) ( val ) except ( ValueErr...
def check_regularizers ( regularizers , keys ) : """Checks the given regularizers . This checks that ` regularizers ` is a dictionary that only contains keys in ` keys ` , and furthermore the entries in ` regularizers ` are functions or further dictionaries ( the latter used , for example , in passing regular...
if regularizers is None : return { } _assert_is_dictlike ( regularizers , valid_keys = keys ) keys = set ( keys ) if not set ( regularizers ) <= keys : extra_keys = set ( regularizers ) - keys raise KeyError ( "Invalid regularizer keys {}, regularizers can only " "be provided for {}" . format ( ", " . join ...
def get_player_img ( player_id ) : """Returns the image of the player from stats . nba . com as a numpy array and saves the image as PNG file in the current directory . Parameters player _ id : int The player ID used to find the image . Returns player _ img : ndarray The multidimensional numpy array o...
url = "http://stats.nba.com/media/players/230x185/" + str ( player_id ) + ".png" img_file = str ( player_id ) + ".png" pic = urlretrieve ( url , img_file ) player_img = plt . imread ( pic [ 0 ] ) return player_img
def prior ( self ) : """Model prior for particular model . Product of eclipse probability ( ` ` self . prob ` ` ) , the fraction of scenario that is allowed by the various constraints ( ` ` self . selectfrac ` ` ) , and all additional factors in ` ` self . priorfactors ` ` ."""
prior = self . prob * self . selectfrac for f in self . priorfactors : prior *= self . priorfactors [ f ] return prior
def width_tuple ( value ) : """test if value is a valid width indicator ( for a sub - widget in a column ) . This can either be ( ' fit ' , min , max ) : use the length actually needed for the content , padded to use at least width min , and cut of at width max . Here , min and max are positive integers or ...
if value is None : res = 'fit' , 0 , 0 elif not isinstance ( value , ( list , tuple ) ) : raise VdtTypeError ( value ) elif value [ 0 ] not in [ 'fit' , 'weight' ] : raise VdtTypeError ( value ) if value [ 0 ] == 'fit' : if not isinstance ( value [ 1 ] , int ) or not isinstance ( value [ 2 ] , int ) : ...
def get_cluster_interfaces ( cluster , extra_cond = lambda nic : True ) : """Get the network interfaces names corresponding to a criteria . Note that the cluster is passed ( not the individual node names ) , thus it is assumed that all nodes in a cluster have the same interface names same configuration . In a...
nics = get_nics ( cluster ) # NOTE ( msimonin ) : Since 05/18 nics on g5k nodes have predictable names but # the api description keep the legacy name ( device key ) and the new # predictable name ( key name ) . The legacy names is still used for api # request to the vlan endpoint This should be fixed in # https : / / i...
def plt_goea_results ( fout_img , goea_results , ** kws ) : """Plot a single page ."""
go_sources = [ rec . GO for rec in goea_results ] go2obj = { rec . GO : rec . goterm for rec in goea_results } gosubdag = GoSubDag ( go_sources , go2obj , rcntobj = True ) godagplot = GoSubDagPlot ( gosubdag , goea_results = goea_results , ** kws ) godagplot . plt_dag ( fout_img )
def read_text ( self ) : # type : ( ) - > Dict [ str , str ] """Get version out of ad - hoc version . txt : return :"""
found = { } for file in self . file_inventory . text_files : if not os . path . isfile ( file ) : continue with self . file_opener . open_this ( file , "r" ) as infile : text = infile . readline ( ) found [ file ] = text . strip ( " \n" ) return found
def parse_security_group ( self , global_params , region , security_group ) : """Parse a single Redsfhit security group : param global _ params : Parameters shared for all regions : param region : Name of the AWS region : param security ) _ group : Security group"""
name = security_group . pop ( 'ClusterSecurityGroupName' ) security_group [ 'name' ] = name self . security_groups [ 'name' ] = security_group
def disable_svc_notifications ( self , service ) : """Disable notifications for a service Format of the line that triggers function call : : DISABLE _ SVC _ NOTIFICATIONS ; < host _ name > ; < service _ description > : param service : service to edit : type service : alignak . objects . service . Service ...
if service . notifications_enabled : service . modified_attributes |= DICT_MODATTR [ "MODATTR_NOTIFICATIONS_ENABLED" ] . value service . notifications_enabled = False self . send_an_element ( service . get_update_status_brok ( ) )
def _get_mean ( self , imt , mag , hypo_depth , rrup , d ) : """Return mean value as defined in equation 3.5.1-1 page 148"""
# clip magnitude at 8.3 as per note at page 3-36 in table Table 3.3.2-6 # in " Technical Reports on National Seismic Hazard Maps for Japan " mag = min ( mag , 8.3 ) if imt . name == 'PGV' : mean = ( 0.58 * mag + 0.0038 * hypo_depth + d - 1.29 - np . log10 ( rrup + 0.0028 * 10 ** ( 0.5 * mag ) ) - 0.002 * rrup ) els...
def keys ( self ) : """Return a copy of the flat dictionary ' s list of keys . See the note for : meth : ` flatdict . FlatDict . items ` . : rtype : list"""
keys = [ ] for key , value in self . _values . items ( ) : if isinstance ( value , ( FlatDict , dict ) ) : nested = [ self . _delimiter . join ( [ key , k ] ) for k in value . keys ( ) ] keys += nested if nested else [ key ] else : keys . append ( key ) return sorted ( keys )
def buildNavigation ( self ) : """Chooses the appropriate layout navigation component based on user prefs"""
if self . buildSpec [ 'navigation' ] == constants . TABBED : navigation = Tabbar ( self , self . buildSpec , self . configs ) else : navigation = Sidebar ( self , self . buildSpec , self . configs ) if self . buildSpec [ 'navigation' ] == constants . HIDDEN : navigation . Hide ( ) return navigation
def _process ( self , data_buffer ) : """Handle incoming packet from server ."""
packet = json . loads ( data_buffer ) if packet [ 'cmd' ] == 'out' : # Call os . write manually . In Python2.6 , sys . stdout . write doesn ' t use UTF - 8. original_mode = DWORD ( 0 ) windll . kernel32 . GetConsoleMode ( self . _hconsole , byref ( original_mode ) ) windll . kernel32 . SetConsoleMode ( self...
def initialize_fields ( self , content ) : """Initializes the : class : ` Field ` elements in the ` Array ` with the * values * in the * content * list . If the * content * list is shorter than the ` Array ` then the * content * list is used as a rotating fill pattern for the : class : ` Field ` elements in...
if isinstance ( content , ( list , tuple ) ) : capacity = len ( content ) for i in range ( 0 , len ( self ) , capacity ) : for name , pair in enumerate ( zip ( self [ i : i + capacity ] , content ) , start = i ) : item , value = pair if is_mixin ( item ) : # Container or Pointer ...
def _prepare_load_balancers ( self ) : """Prepare load balancer variables"""
stack = { A . NAME : self [ A . NAME ] , A . VERSION : self [ A . VERSION ] , } for load_balancer in self . get ( R . LOAD_BALANCERS , [ ] ) : svars = { A . STACK : stack } load_balancer [ A . loadbalancer . VARS ] = svars
def get_top_edge_depth ( self ) : """Return minimum depth of surface ' s top edge . : returns : Float value , the vertical distance between the earth surface and the shallowest point in surface ' s top edge in km ."""
top_edge = self . mesh [ 0 : 1 ] if top_edge . depths is None : return 0 else : return numpy . min ( top_edge . depths )
def extractFieldsFromResult ( data ) : '''Method that parses Infobel textual information to return a series of attributes . : return : a list of i3visio - like objects .'''
entities = [ ] # Defining the objects to extract fieldsRegExp = { } fieldsRegExp [ "i3visio.fullname" ] = "<span class=\"fn\">([^<]*)</span>" fieldsRegExp [ "i3visio.name" ] = " por <strong>[^ ]* ([^<]*)</strong>" fieldsRegExp [ "i3visio.surname" ] = " por <strong>([^ ]*) " fieldsRegExp [ "i3visio.location.addres...