signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def explain ( self , extended = False ) : """Prints the ( logical and physical ) plans to the console for debugging purpose . : param extended : boolean , default ` ` False ` ` . If ` ` False ` ` , prints only the physical plan . > > > df . explain ( ) = = Physical Plan = = * ( 1 ) Scan ExistingRDD [ age # ...
if extended : print ( self . _jdf . queryExecution ( ) . toString ( ) ) else : print ( self . _jdf . queryExecution ( ) . simpleString ( ) )
def graph ( self , node_source , edge_source , layout_provider , ** kwargs ) : '''Creates a network graph using the given node , edge and layout provider . Args : node _ source ( : class : ` ~ bokeh . models . sources . ColumnDataSource ` ) : a user - supplied data source for the graph nodes . An attempt will...
kw = _graph ( node_source , edge_source , ** kwargs ) graph_renderer = GraphRenderer ( layout_provider = layout_provider , ** kw ) self . renderers . append ( graph_renderer ) return graph_renderer
def validate_tz_from_dtype ( dtype , tz ) : """If the given dtype is a DatetimeTZDtype , extract the implied tzinfo object from it and check that it does not conflict with the given tz . Parameters dtype : dtype , str tz : None , tzinfo Returns tz : consensus tzinfo Raises ValueError : on tzinfo m...
if dtype is not None : if isinstance ( dtype , str ) : try : dtype = DatetimeTZDtype . construct_from_string ( dtype ) except TypeError : # Things like ` datetime64 [ ns ] ` , which is OK for the # constructors , but also nonsense , which should be validated # but not by ...
def pseudo_partial_waves ( self ) : """Dictionary with the pseudo partial waves indexed by state ."""
pseudo_partial_waves = OrderedDict ( ) for ( mesh , values , attrib ) in self . _parse_all_radfuncs ( "pseudo_partial_wave" ) : state = attrib [ "state" ] # val _ state = self . valence _ states [ state ] pseudo_partial_waves [ state ] = RadialFunction ( mesh , values ) return pseudo_partial_waves
def find_candidate_metadata_files ( names ) : """Filter files that may be METADATA files ."""
tuples = [ x . split ( '/' ) for x in map ( try_decode , names ) if 'METADATA' in x ] return [ x [ 1 ] for x in sorted ( [ ( len ( x ) , x ) for x in tuples ] ) ]
def random ( * args ) : """Counts up sequentially from a number based on the current time : rtype int :"""
current_frame = inspect . currentframe ( ) . f_back trace_string = "" while current_frame . f_back : trace_string = trace_string + current_frame . f_back . f_code . co_name current_frame = current_frame . f_back return counter . get_from_trace ( trace_string )
def _validate_pianoroll ( pianoroll ) : """Raise an error if the input array is not a standard pianoroll ."""
if not isinstance ( pianoroll , np . ndarray ) : raise TypeError ( "`pianoroll` must be of np.ndarray type." ) if not ( np . issubdtype ( pianoroll . dtype , np . bool_ ) or np . issubdtype ( pianoroll . dtype , np . number ) ) : raise TypeError ( "The data type of `pianoroll` must be np.bool_ or a " "subdtype ...
def _create_latent_variables ( self ) : """Creates model latent variables Returns None ( changes model attributes )"""
for ar_term in range ( self . ar ) : self . latent_variables . add_z ( 'AR(' + str ( ar_term + 1 ) + ')' , fam . Normal ( 0 , 0.5 , transform = None ) , fam . Normal ( 0 , 3 ) ) for sc_term in range ( self . sc ) : self . latent_variables . add_z ( 'SC(' + str ( sc_term + 1 ) + ')' , fam . Normal ( 0 , 0.5 , tr...
def search_user ( current ) : """Search users for adding to a public room or creating one to one direct messaging . . code - block : : python # request : ' view ' : ' _ zops _ search _ user ' , ' query ' : string , # response : ' results ' : [ ( ' full _ name ' , ' key ' , ' avatar _ url ' ) , ] , '...
current . output = { 'results' : [ ] , 'status' : 'OK' , 'code' : 201 } qs = UserModel ( current ) . objects . exclude ( key = current . user_id ) . search_on ( * settings . MESSAGING_USER_SEARCH_FIELDS , contains = current . input [ 'query' ] ) # FIXME : somehow exclude ( key = current . user _ id ) not working with s...
def to_packets ( pages , strict = False ) : """Construct a list of packet data from a list of Ogg pages . If strict is true , the first page must start a new packet , and the last page must end the last packet ."""
serial = pages [ 0 ] . serial sequence = pages [ 0 ] . sequence packets = [ ] if strict : if pages [ 0 ] . continued : raise ValueError ( "first packet is continued" ) if not pages [ - 1 ] . complete : raise ValueError ( "last packet does not complete" ) elif pages and pages [ 0 ] . continued : ...
def setup_logger ( ) : """Return a logger with a default ColoredFormatter ."""
formatter = ColoredFormatter ( "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s" , datefmt = None , reset = True , log_colors = { 'DEBUG' : 'cyan' , 'INFO' : 'green' , 'WARNING' : 'yellow' , 'ERROR' : 'red' , 'CRITICAL' : 'red' , } ) logger = logging . getLogger ( 'example' ) handler = logging . StreamHandler...
def encryption_cipher ( self ) : """Returns the name of the symmetric encryption cipher to use . The key length can be retrieved via the . key _ length property to disabiguate between different variations of TripleDES , AES , and the RC * ciphers . : return : A unicode string from one of the following : " r...
encryption_algo = self [ 'algorithm' ] . native if encryption_algo [ 0 : 7 ] in set ( [ 'aes128_' , 'aes192_' , 'aes256_' ] ) : return 'aes' if encryption_algo in set ( [ 'des' , 'rc2' , 'rc5' ] ) : return encryption_algo if encryption_algo == 'tripledes_3key' : return 'tripledes' if encryption_algo == 'pbe...
def itermonthdates ( cls , year , month ) : """Returns an iterator for the month in a year This iterator will return all days ( as NepDate objects ) for the month and all days before the start of the month or after the end of the month that are required to get a complete week ."""
curday = NepDate . from_bs_date ( year , month , 1 ) start_weekday = curday . weekday ( ) # Start _ weekday represents the number of days we have to pad for i in range ( start_weekday , 0 , - 1 ) : yield ( curday - timedelta ( days = i ) ) for i in range ( 0 , values . NEPALI_MONTH_DAY_DATA [ year ] [ month - 1 ] )...
def from_content ( cls , content ) : """Creates an instance of the class from the html content of a highscores page . Notes Tibia . com only shows up to 25 entries per page , so in order to obtain the full highscores , all 12 pages must be parsed and merged into one . Parameters content : : class : ` str ...
parsed_content = parse_tibiacom_content ( content ) tables = cls . _parse_tables ( parsed_content ) filters = tables . get ( "Highscores Filter" ) if filters is None : raise InvalidContent ( "content does is not from the highscores section of Tibia.com" ) world_filter , vocation_filter , category_filter = filters w...
def _query ( self , host_object ) : """Query the DNSBL service for given value . : param host _ object : an object representing host , created by self . _ host _ factory : returns : an instance of dns . resolver . Answer for given value if it is listed . Otherwise , it returns None ."""
host_to_query = host_object . relative_domain query_name = host_to_query . derelativize ( self . _query_suffix ) try : return query ( query_name ) except NXDOMAIN : return None
def filter_none ( list_of_points ) : """: param list _ of _ points : : return : list _ of _ points with None ' s removed"""
remove_elementnone = filter ( lambda p : p is not None , list_of_points ) remove_sublistnone = filter ( lambda p : not contains_none ( p ) , remove_elementnone ) return list ( remove_sublistnone )
def gen_totals ( report , file_type ) : """Print the gen totals ."""
label = clr . stringc ( file_type + " files " , "bright purple" ) ok = field_value ( report [ "ok_role" ] , "ok" , c . LOG_COLOR [ "ok" ] , 0 ) skipped = field_value ( report [ "skipped_role" ] , "skipped" , c . LOG_COLOR [ "skipped" ] , 16 ) changed = field_value ( report [ "changed_role" ] , "changed" , c . LOG_COL...
def get_flux ( self , energies ) : """Get the total flux of this particle source at the given energies ( summed over the components )"""
results = [ component . shape ( energies ) for component in self . components . values ( ) ] return numpy . sum ( results , 0 )
def set_distribute_alterations ( self , distribute_mods ) : """Sets the distribute alterations flag . This also sets distribute verbatim to ` ` true ` ` . arg : distribute _ mods ( boolean ) : right to distribute modifications raise : InvalidArgument - ` ` distribute _ mods ` ` is invalid raise : NoAccess...
# Implemented from template for osid . resource . ResourceForm . set _ group _ template if self . get_distribute_alterations_metadata ( ) . is_read_only ( ) : raise errors . NoAccess ( ) if not self . _is_valid_boolean ( distribute_mods ) : raise errors . InvalidArgument ( ) self . _my_map [ 'distributeAlterati...
def to_bel_path ( graph , path : str , mode : str = 'w' , ** kwargs ) -> None : """Write the BEL graph as a canonical BEL Script to the given path . : param BELGraph graph : the BEL Graph to output as a BEL Script : param path : A file path : param mode : The file opening mode . Defaults to ' w '"""
with open ( path , mode = mode , ** kwargs ) as bel_file : to_bel ( graph , bel_file )
def weighted_hamming ( b1 , b2 ) : """Hamming distance that emphasizes differences earlier in strings ."""
assert ( len ( b1 ) == len ( b2 ) ) hamming = 0 for i in range ( len ( b1 ) ) : if b1 [ i ] != b2 [ i ] : # differences at more significant ( leftward ) bits # are more important if i > 0 : hamming += 1 + 1.0 / i # This weighting is completely arbitrary return hamming
def from_files ( path_dir , dos_spin = 1 ) : """get a BoltztrapAnalyzer object from a set of files Args : path _ dir : directory where the boltztrap files are dos _ spin : in DOS mode , set to 1 for spin up and - 1 for spin down Returns : a BoltztrapAnalyzer object"""
run_type , warning , efermi , gap , doping_levels = BoltztrapAnalyzer . parse_outputtrans ( path_dir ) vol = BoltztrapAnalyzer . parse_struct ( path_dir ) intrans = BoltztrapAnalyzer . parse_intrans ( path_dir ) if run_type == "BOLTZ" : dos , pdos = BoltztrapAnalyzer . parse_transdos ( path_dir , efermi , dos_spin ...
def _xfer_file ( self , source_file = None , source_config = None , dest_file = None , file_system = None , TransferClass = FileTransfer ) : """Transfer file to remote device . By default , this will use Secure Copy if self . inline _ transfer is set , then will use Netmiko InlineTransfer method to transfer inl...
if not source_file and not source_config : raise ValueError ( "File source not specified for transfer." ) if not dest_file or not file_system : raise ValueError ( "Destination file or file system not specified." ) if source_file : kwargs = dict ( ssh_conn = self . device , source_file = source_file , dest_f...
def _remote ( self , args = None , kwargs = None , num_cpus = None , num_gpus = None , resources = None ) : """Create an actor . This method allows more flexibility than the remote method because resource requirements can be specified and override the defaults in the decorator . Args : args : The argument...
if args is None : args = [ ] if kwargs is None : kwargs = { } worker = ray . worker . get_global_worker ( ) if worker . mode is None : raise Exception ( "Actors cannot be created before ray.init() " "has been called." ) actor_id = ActorID ( _random_string ( ) ) # The actor cursor is a dummy object represent...
def verify_share_password ( uk , shareid , pwd , vcode = '' ) : '''验证共享文件的密码 . 如果密码正确 , 会在返回的请求头里加入一个cookie : BDCLND pwd - 四位的明文密码 vcode - 验证码 ; 目前还不支持'''
url = '' . join ( [ const . PAN_URL , 'share/verify?&clienttype=0&web=1&channel=chunlei' , '&shareid=' , shareid , '&uk=' , uk , ] ) data = 'pwd={0}&vcode={1}' . format ( pwd , vcode ) req = net . urlopen ( url , data = data . encode ( ) ) if req : content = req . data . decode ( ) info = json . loads ( content...
def value ( self ) -> Union [ bool , None ] : """Returns the concrete value of this bool if concrete , otherwise None . : return : Concrete value or None"""
self . simplify ( ) if self . is_true : return True elif self . is_false : return False else : return None
def dposition ( self , node , dcol = 0 ) : """Return deslocated line and column"""
nnode = self . dnode ( node ) return ( nnode . lineno , nnode . col_offset + dcol )
def process_mod ( self , data , name ) : """Processing one modulus per line : param data : : param name : : return :"""
ret = [ ] try : lines = [ x . strip ( ) for x in data . split ( bytes ( b'\n' ) ) ] for idx , line in enumerate ( lines ) : sub = self . process_mod_line ( line , name , idx ) ret . append ( sub ) except Exception as e : logger . debug ( 'Error in line mod file processing %s : %s' % ( name ,...
def _basic_get_ok ( self , args , msg ) : """Provide client with a message This method delivers a message to the client following a get method . A message delivered by ' get - ok ' must be acknowledged unless the no - ack option was set in the get method . PARAMETERS : delivery _ tag : longlong server -...
delivery_tag = args . read_longlong ( ) redelivered = args . read_bit ( ) exchange = args . read_shortstr ( ) routing_key = args . read_shortstr ( ) message_count = args . read_long ( ) msg . channel = self msg . delivery_info = { 'delivery_tag' : delivery_tag , 'redelivered' : redelivered , 'exchange' : exchange , 'ro...
def create_movie ( fig , update_figure , filename , title , fps = 15 , dpi = 100 ) : """Helps us to create a movie ."""
FFMpegWriter = manimation . writers [ 'ffmpeg' ] metadata = dict ( title = title ) writer = FFMpegWriter ( fps = fps , metadata = metadata ) with writer . saving ( fig , filename , dpi ) : t = 0 while True : if update_figure ( t ) : writer . grab_frame ( ) t += 1 else : ...
def check_if_dict_contains_object_reference_in_values ( object_to_check , dict_to_check ) : """Method to check if an object is inside the values of a dict . A simple object _ to _ check in dict _ to _ check . values ( ) does not work as it uses the _ _ eq _ _ function of the object and not the object reference ...
for key , value in dict_to_check . items ( ) : if object_to_check is value : return True return False
def publish ( self , channel , message ) : """Publish message to channel . : returns : a coroutine"""
if self . cfg . jsonpickle : message = jsonpickle . encode ( message ) return self . conn . publish ( channel , message )
def prepare ( self , context ) : """Add the usual suspects to the context . This adds ` request ` , ` response ` , and ` path ` to the ` RequestContext ` instance ."""
if __debug__ : log . debug ( "Preparing request context." , extra = dict ( request = id ( context ) ) ) # Bridge in WebOb ` Request ` and ` Response ` objects . # Extensions shouldn ' t rely on these , using ` environ ` where possible instead . context . request = Request ( context . environ ) context . response = ...
def to_simple_model ( self , instance , ** options ) : # noqa """Convert model to simple python structure ."""
options = self . init_options ( ** options ) fields , include , exclude , related = options [ 'fields' ] , options [ 'include' ] , options [ 'exclude' ] , options [ 'related' ] # noqa result = dict ( model = smart_unicode ( instance . _meta ) , pk = smart_unicode ( instance . _get_pk_val ( ) , strings_only = True ) , f...
def connect_to_queues ( region = None , public = True ) : """Creates a client for working with Queues ."""
return _create_client ( ep_name = "queues" , region = region , public = public )
def add_event_handler ( self , action ) : """Add a event handler into actions list : param action : event handler to add : type action : alignak . eventhandler . EventHandler : return : None"""
if action . uuid in self . actions : logger . info ( "Already existing event handler: %s" , action ) return self . actions [ action . uuid ] = action self . nb_event_handlers += 1
def hdf5_cache ( filepath = None , parent = None , group = None , names = None , typed = False , hashed_key = False , ** h5dcreate_kwargs ) : """HDF5 cache decorator . Parameters filepath : string , optional Path to HDF5 file . If None a temporary file name will be used . parent : string , optional Path t...
# initialise HDF5 file path if filepath is None : import tempfile filepath = tempfile . mktemp ( prefix = 'scikit_allel_' , suffix = '.h5' ) atexit . register ( os . remove , filepath ) # initialise defaults for dataset creation h5dcreate_kwargs . setdefault ( 'chunks' , True ) def decorator ( user_function...
def tiles_to_pixels ( self , tiles ) : """Convert tile coordinates into pixel coordinates"""
pixel_coords = Vector2 ( ) pixel_coords . X = tiles [ 0 ] * self . spritesheet [ 0 ] . width pixel_coords . Y = tiles [ 1 ] * self . spritesheet [ 0 ] . height return pixel_coords
def getsize ( store , path = None ) : """Compute size of stored items for a given path . If ` store ` provides a ` getsize ` method , this will be called , otherwise will return - 1."""
path = normalize_storage_path ( path ) if hasattr ( store , 'getsize' ) : # pass through return store . getsize ( path ) elif isinstance ( store , dict ) : # compute from size of values if path in store : v = store [ path ] size = buffer_size ( v ) else : members = listdir ( store , ...
def zip_clean_metaxml ( zip_src , logger = None ) : """Given a zipfile , cleans all * - meta . xml files in the zip for deployment by stripping all < packageVersions / > elements"""
zip_dest = zipfile . ZipFile ( io . BytesIO ( ) , "w" , zipfile . ZIP_DEFLATED ) changed = [ ] for name in zip_src . namelist ( ) : content = zip_src . read ( name ) if name . startswith ( META_XML_CLEAN_DIRS ) and name . endswith ( "-meta.xml" ) : try : content . decode ( "utf-8" ) ...
def style ( self ) : """Read / write . A | _ CharacterStyle | object representing the character style applied to this run . The default character style for the document ( often ` Default Character Font ` ) is returned if the run has no directly - applied character style . Setting this property to | None | r...
style_id = self . _r . style return self . part . get_style ( style_id , WD_STYLE_TYPE . CHARACTER )
def addSSLService ( self ) : "adds a SSLService to the instaitated HendrixService"
https_port = self . options [ 'https_port' ] self . tls_service = HendrixTCPServiceWithTLS ( https_port , self . hendrix . site , self . key , self . cert , self . context_factory , self . context_factory_kwargs ) self . tls_service . setServiceParent ( self . hendrix )
def step_impl07 ( context , len_list ) : """Check assertions . : param len _ list : expected number of variants . : param context : test context ."""
assert len ( context . fuzzed_string_list ) == len_list for fuzzed_string in context . fuzzed_string_list : assert len ( context . seed ) == len ( fuzzed_string ) count = number_of_modified_bytes ( context . seed , fuzzed_string ) assert count >= 0
def search ( request , abbr ) : '''Context : - search _ text - abbr - metadata - found _ by _ id - bill _ results - more _ bills _ available - legislators _ list - nav _ active Tempaltes : - billy / web / public / search _ results _ no _ query . html - billy / web / public / search _ results _...
if not request . GET : return render ( request , templatename ( 'search_results_no_query' ) , { 'abbr' : abbr } ) search_text = unicode ( request . GET [ 'search_text' ] ) . encode ( 'utf8' ) # First try to get by bill _ id . if re . search ( r'\d' , search_text ) : url = '/%s/bills?' % abbr url += urllib ....
def _apply_decorators ( func , decorators ) : """Apply a list of decorators to a given function . ` ` decorators ` ` may contain items that are ` ` None ` ` or ` ` False ` ` which will be ignored ."""
decorators = filter ( _is_not_none_or_false , reversed ( decorators ) ) for decorator in decorators : func = decorator ( func ) return func
def alter_column_type ( self , relation , column_name , new_column_type ) : """1 . Create a new column ( w / temp name and correct type ) 2 . Copy data over to it 3 . Drop the existing column ( cascade ! ) 4 . Rename the new column to existing column"""
kwargs = { 'relation' : relation , 'column_name' : column_name , 'new_column_type' : new_column_type , } self . execute_macro ( ALTER_COLUMN_TYPE_MACRO_NAME , kwargs = kwargs )
def has_rabf_motif ( self ) : """Checks if the sequence has enough RabF motifs within the G domain If there exists more than one G domain in the sequence enough RabF motifs is required in at least one of those domains to classify the sequence as a Rab ."""
if self . rabf_motifs : for gdomain in self . gdomain_regions : beg , end = map ( int , gdomain . split ( '-' ) ) motifs = [ x for x in self . rabf_motifs if x [ 1 ] >= beg and x [ 2 ] <= end ] if motifs : matches = int ( pairwise2 . align . globalxx ( '12345' , '' . join ( str (...
def derivative ( self , vf ) : """Derivative of the point - wise norm operator at ` ` vf ` ` . The derivative at ` ` F ` ` of the point - wise norm operator ` ` N ` ` with finite exponent ` ` p ` ` and weights ` ` w ` ` is the pointwise inner product with the vector field : : x - - > N ( F ) ( x ) ^ ( 1 - p...
if self . domain . field == ComplexNumbers ( ) : raise NotImplementedError ( 'operator not Frechet-differentiable ' 'on a complex space' ) if self . exponent == float ( 'inf' ) : raise NotImplementedError ( 'operator not Frechet-differentiable ' 'for exponent = inf' ) vf = self . domain . element ( vf ) vf_pwno...
def query_by_post ( postid ) : '''Get reply list of certain post .'''
return TabReply . select ( ) . where ( TabReply . post_id == postid ) . order_by ( TabReply . timestamp . desc ( ) )
def record_set_create_or_update ( name , zone_name , resource_group , record_type , ** kwargs ) : '''. . versionadded : : Fluorine Creates or updates a record set within a DNS zone . : param name : The name of the record set , relative to the name of the zone . : param zone _ name : The name of the DNS zone (...
dnsconn = __utils__ [ 'azurearm.get_client' ] ( 'dns' , ** kwargs ) try : record_set_model = __utils__ [ 'azurearm.create_object_model' ] ( 'dns' , 'RecordSet' , ** kwargs ) except TypeError as exc : result = { 'error' : 'The object model could not be built. ({0})' . format ( str ( exc ) ) } return result t...
def metadata ( self ) : """The build metadata is the union of the metadata in its test runs . Common keys with different values are transformed into a list with each of the different values ."""
if self . __metadata__ is None : metadata = { } for test_run in self . test_runs . defer ( None ) . all ( ) : for key , value in test_run . metadata . items ( ) : metadata . setdefault ( key , [ ] ) if value not in metadata [ key ] : metadata [ key ] . append ( va...
def update ( self , ng_template_id , name = NotUpdated , plugin_name = NotUpdated , hadoop_version = NotUpdated , flavor_id = NotUpdated , description = NotUpdated , volumes_per_node = NotUpdated , volumes_size = NotUpdated , node_processes = NotUpdated , node_configs = NotUpdated , floating_ip_pool = NotUpdated , secu...
data = { } self . _copy_if_updated ( data , name = name , plugin_name = plugin_name , hadoop_version = hadoop_version , flavor_id = flavor_id , description = description , volumes_per_node = volumes_per_node , volumes_size = volumes_size , node_processes = node_processes , node_configs = node_configs , floating_ip_pool...
def rpush ( self , key , * values ) : """Insert all the specified values at the tail of the list stored at key . : param key : The list ' s key : type key : : class : ` str ` , : class : ` bytes ` : param values : One or more positional arguments to insert at the tail of the list . : returns : the length ...
return self . _execute ( [ b'RPUSH' , key ] + list ( values ) )
def lcp ( s1 , s2 ) : '''longest common prefix > > > lcp ( ' abcdx ' , ' abcdy ' ) , lcp ( ' ' , ' a ' ) , lcp ( ' x ' , ' yz ' ) (4 , 0 , 0)'''
i = 0 for i , ( c1 , c2 ) in enumerate ( zip ( s1 , s2 ) ) : if c1 != c2 : return i return min ( len ( s1 ) , len ( s2 ) )
def _parse_remind ( self , filename , lines = '' ) : """Calls remind and parses the output into a dict filename - - the remind file ( included files will be used as well ) lines - - used as stdin to remind ( filename will be set to - )"""
files = { } reminders = { } if lines : filename = '-' files [ filename ] = lines reminders [ filename ] = { } cmd = [ 'remind' , '-l' , '-s%d' % self . _month , '-b1' , '-y' , '-r' , filename , str ( self . _startdate ) ] try : rem = Popen ( cmd , stdin = PIPE , stdout = PIPE ) . communicate ( input = l...
def start_prompt ( self ) : """Start the interpreter ."""
logger . show ( "Coconut Interpreter:" ) logger . show ( "(type 'exit()' or press Ctrl-D to end)" ) self . start_running ( ) while self . running : try : code = self . get_input ( ) if code : compiled = self . handle_input ( code ) if compiled : self . execute...
def plot_sections ( self , fout_dir = "." , ** kws_usr ) : """Plot groups of GOs which have been placed in sections ."""
kws_plt , _ = self . _get_kws_plt ( None , ** kws_usr ) PltGroupedGos ( self ) . plot_sections ( fout_dir , ** kws_plt )
def createGroup ( self , group , vendorSpecific = None ) : """See Also : createGroupResponse ( ) Args : group : vendorSpecific : Returns :"""
response = self . createGroupResponse ( group , vendorSpecific ) return self . _read_boolean_response ( response )
def datatype2schemacls ( _datatype , _registry = None , _factory = None , _force = True , _besteffort = True , ** kwargs ) : """Get a schema class which has been associated to input data type by the registry or the factory in this order . : param type datatype : data type from where get associated schema . : ...
result = None gdbt = getbydatatype if _registry is None else _registry . getbydatatype result = gdbt ( _datatype , besteffort = _besteffort ) if result is None : gscls = getschemacls if _factory is None else _factory . getschemacls result = gscls ( _datatype , besteffort = _besteffort ) if result is None and _f...
def get_input_signature ( self ) : """Returns : A list of : class : ` tf . TensorSpec ` , which describes the inputs of this model . The result is cached for each instance of : class : ` ModelDescBase ` ."""
with tf . Graph ( ) . as_default ( ) as G : # create these placeholder in a temporary graph inputs = self . inputs ( ) if isinstance ( inputs [ 0 ] , tf . Tensor ) : for p in inputs : assert "Placeholder" in p . op . type , "inputs() have to return TensorSpec or placeholders! Found {} instea...
def write_zarr ( self , store : Union [ MutableMapping , PathLike ] , chunks : Union [ bool , int , Tuple [ int , ... ] ] , ) : """Write a hierarchical Zarr array store . Parameters store The filename , a : class : ` ~ typing . MutableMapping ` , or a Zarr storage class . chunks Chunk shape ."""
from . readwrite . write import write_zarr write_zarr ( store , self , chunks = chunks )
def translate_comment ( self , comment , link_resolver ) : """Given a gtk - doc comment string , returns the comment translated to the desired format ."""
out = u'' self . translate_tags ( comment , link_resolver ) ast = self . comment_to_ast ( comment , link_resolver ) out += self . ast_to_html ( ast , link_resolver ) return out
def _minimize_neldermead ( func , x0 , args = ( ) , callback = None , xtol = 1e-4 , ftol = 1e-4 , maxiter = None , maxfev = None , disp = False , return_all = False , ) : # pragma : no cover """Minimization of scalar function of one or more variables using the Nelder - Mead algorithm . Options for the Nelder - ...
maxfun = maxfev retall = return_all fcalls , func = wrap_function ( func , args ) x0 = asfarray ( x0 ) . flatten ( ) N = len ( x0 ) rank = len ( x0 . shape ) if not - 1 < rank < 2 : raise ValueError ( "Initial guess must be a scalar or rank-1 sequence." ) if maxiter is None : maxiter = N * 200 if maxfun is None...
def authorization_request_verify ( authentication_request ) : """Verifies that all required parameters and correct values are included in the authentication request . : param authentication _ request : the authentication request to verify : raise InvalidAuthenticationRequest : if the authentication is incorrect...
try : authentication_request . verify ( ) except MessageException as e : raise InvalidAuthenticationRequest ( str ( e ) , authentication_request , oauth_error = 'invalid_request' ) from e
def swapkey ( self , old_key , new_key , new_value = None ) : """Replace a variable name , with a potentially new value . Parameters old _ key : str Current variable name to replace new _ key : str New variable name to replace ` old _ key ` with new _ value : object Value to be replaced along with the...
if self . has_resolvers : maps = self . resolvers . maps + self . scope . maps else : maps = self . scope . maps maps . append ( self . temps ) for mapping in maps : if old_key in mapping : mapping [ new_key ] = new_value return
def _studentized_residuals_fast ( self , p = None ) : """Returns a list of studentized residuals , ( ydata - model ) / error This function relies on a previous call to set _ data ( ) , and assumes self . _ massage _ data ( ) has been called ( to increase speed ) . Parameters p = None Function parameters t...
if len ( self . _set_xdata ) == 0 or len ( self . _set_ydata ) == 0 : return if p is None : if self . results is None : p = self . _pguess else : p = self . results [ 0 ] # evaluate the function for all the data , returns a list ! f = self . _evaluate_all_functions ( self . _xdata_massaged ,...
def send ( self , chat_id , msg_type , ** kwargs ) : """应用推送消息 详情请参考 : https : / / work . weixin . qq . com / api / doc # 90000/90135/90248 : param chat _ id : 群聊id : param msg _ type : 消息类型 , 可以为text / image / voice / video / file / textcard / news / mpnews / markdown : param kwargs : 具体消息类型的扩展参数 : retur...
data = { 'chatid' : chat_id , 'safe' : kwargs . get ( 'safe' ) or 0 } data . update ( self . _build_msg_content ( msg_type , ** kwargs ) ) return self . _post ( 'appchat/send' , data = data )
def poly ( self , return_coeffs = False ) : """returns the quadratic as a Polynomial object ."""
p = self . bpoints ( ) coeffs = ( p [ 0 ] - 2 * p [ 1 ] + p [ 2 ] , 2 * ( p [ 1 ] - p [ 0 ] ) , p [ 0 ] ) if return_coeffs : return coeffs else : return np . poly1d ( coeffs )
def set_PLOS_1column_fig_style ( self , ratio = 1 ) : '''figure size corresponding to Plos 1 column'''
plt . rcParams . update ( { 'figure.figsize' : [ self . PLOSwidth1Col , self . PLOSwidth1Col * ratio ] , } )
def _active_case ( self , value : ObjectValue ) -> Optional [ "CaseNode" ] : """Return receiver ' s case that ' s active in an instance node value ."""
for c in self . children : for cc in c . data_children ( ) : if cc . iname ( ) in value : return c
def sub_schema_raises ( doc , schema ) : '''Look for " raise _ error " , " raise _ warning " , and " raise _ log "'''
error_list = [ ] temp_schema = schema_match_up ( doc , schema ) for msg in temp_schema . list_values ( "raise_error" ) : error_list . append ( ( "[error]" , "doc" , doc . seq , "'{}'" . format ( msg ) ) ) for msg in temp_schema . list_values ( "raise_warning" ) : error_list . append ( ( "[warning]" , "doc" , do...
def on_menu ( self , event ) : '''handle menu selection'''
state = self . state # see if it is a popup menu if state . popup_object is not None : obj = state . popup_object ret = obj . popup_menu . find_selected ( event ) if ret is not None : ret . call_handler ( ) state . event_queue . put ( SlipMenuEvent ( state . popup_latlon , event , [ SlipObje...
def db_tables ( name , ** connection_args ) : '''Shows the tables in the given MySQL database ( if exists ) CLI Example : . . code - block : : bash salt ' * ' mysql . db _ tables ' database ' '''
if not db_exists ( name , ** connection_args ) : log . info ( 'Database \'%s\' does not exist' , name ) return False dbc = _connect ( ** connection_args ) if dbc is None : return [ ] cur = dbc . cursor ( ) s_name = quote_identifier ( name ) # identifiers cannot be used as values qry = 'SHOW TABLES IN {0}' ....
def printdict ( adict ) : """printdict"""
dlist = list ( adict . keys ( ) ) dlist . sort ( ) for i in range ( 0 , len ( dlist ) ) : print ( dlist [ i ] , adict [ dlist [ i ] ] )
def build_linestring_node ( line , with_depth = False ) : """Parses a line to a Node class : param line : Line as instance of : class : ` openquake . hazardlib . geo . line . Line ` : param bool with _ depth : Include the depth values ( True ) or not ( False ) : : returns : Instance of : class : ` openq...
geom = [ ] for p in line . points : if with_depth : geom . extend ( ( p . x , p . y , p . z ) ) else : geom . extend ( ( p . x , p . y ) ) poslist_node = Node ( "gml:posList" , text = geom ) return Node ( "gml:LineString" , nodes = [ poslist_node ] )
def device_to_user_distance ( self , dx , dy ) : """Transform a distance vector from device space to user space . This method is similar to : meth : ` Context . device _ to _ user ` except that the translation components of the inverse CTM will be ignored when transforming ` ` ( dx , dy ) ` ` . : param dx :...
xy = ffi . new ( 'double[2]' , [ dx , dy ] ) cairo . cairo_device_to_user_distance ( self . _pointer , xy + 0 , xy + 1 ) self . _check_status ( ) return tuple ( xy )
def detect_intent_with_texttospeech_response ( project_id , session_id , texts , language_code ) : """Returns the result of detect intent with texts as inputs and includes the response in an audio format . Using the same ` session _ id ` between requests allows continuation of the conversaion ."""
import dialogflow_v2beta1 as dialogflow session_client = dialogflow . SessionsClient ( ) session_path = session_client . session_path ( project_id , session_id ) print ( 'Session path: {}\n' . format ( session_path ) ) for text in texts : text_input = dialogflow . types . TextInput ( text = text , language_code = l...
def get_msms_df_on_file ( pdb_file , outfile = None , outdir = None , outext = '_msms.df' , force_rerun = False ) : """Run MSMS ( using Biopython ) on a PDB file . Saves a CSV file of : chain : chain ID resnum : residue number ( PDB numbering ) icode : residue insertion code res _ depth : average depth of...
# Create the output file name outfile = ssbio . utils . outfile_maker ( inname = pdb_file , outname = outfile , outdir = outdir , outext = outext ) if ssbio . utils . force_rerun ( flag = force_rerun , outfile = outfile ) : # Load the structure my_structure = StructureIO ( pdb_file ) model = my_structure . firs...
def create_ospf_profile ( ) : """An OSPF Profile contains administrative distance and redistribution settings . An OSPF Profile is applied at the engine level . When creating an OSPF Profile , you must reference a OSPFDomainSetting . An OSPFDomainSetting holds the settings of the area border router ( ABR ) ty...
OSPFDomainSetting . create ( name = 'custom' , abr_type = 'cisco' ) ospf_domain = OSPFDomainSetting ( 'custom' ) # obtain resource ospf_profile = OSPFProfile . create ( name = 'myospfprofile' , domain_settings_ref = ospf_domain . href ) print ( ospf_profile )
def is_partial ( self , filename ) : """Check if a file is a partial . Partial files are not rendered , but they are used in rendering templates . A file is considered a partial if it or any of its parent directories are prefixed with an ` ` ' _ ' ` ` . : param filename : the name of the file to check"""
return any ( ( x . startswith ( "_" ) for x in filename . split ( os . path . sep ) ) )
def blink ( self , on_time = 1 , off_time = 1 , fade_in_time = 0 , fade_out_time = 0 , on_color = ( 1 , 1 , 1 ) , off_color = ( 0 , 0 , 0 ) , n = None , background = True ) : """Make the device turn on and off repeatedly . : param float on _ time : Number of seconds on . Defaults to 1 second . : param float o...
if isinstance ( self . _leds [ 0 ] , LED ) : if fade_in_time : raise ValueError ( 'fade_in_time must be 0 with non-PWM RGBLEDs' ) if fade_out_time : raise ValueError ( 'fade_out_time must be 0 with non-PWM RGBLEDs' ) self . _stop_blink ( ) self . _blink_thread = GPIOThread ( target = self . _bli...
def sample_logits ( embedding , bias , labels , inputs , sampler ) : """embedding : an nn . Embedding layer bias : [ n _ vocab ] labels : [ b1 , b2] inputs : [ b1 , b2 , n _ emb ] sampler : you may use a LogUniformSampler Return logits : [ b1 , b2 , 1 + n _ sample ]"""
true_log_probs , samp_log_probs , neg_samples = sampler . sample ( labels ) n_sample = neg_samples . size ( 0 ) b1 , b2 = labels . size ( 0 ) , labels . size ( 1 ) all_ids = torch . cat ( [ labels . view ( - 1 ) , neg_samples ] ) all_w = embedding ( all_ids ) true_w = all_w [ : - n_sample ] . view ( b1 , b2 , - 1 ) sam...
def _compute_term1 ( self , C , mag ) : """Compute magnitude dependent terms ( 2nd and 3rd ) in equation 3 page 46."""
mag_diff = mag - 6 return C [ 'c2' ] * mag_diff + C [ 'c3' ] * mag_diff ** 2
def _condition_as_text ( lambda_inspection : icontract . _represent . ConditionLambdaInspection ) -> str : """Format condition lambda function as reST ."""
lambda_ast_node = lambda_inspection . node assert isinstance ( lambda_ast_node , ast . Lambda ) body_node = lambda_ast_node . body text = None # type : Optional [ str ] if isinstance ( body_node , ast . BoolOp ) and isinstance ( body_node . op , ast . Or ) and len ( body_node . values ) == 2 : left , right = body_n...
def handle_msg ( self , c , e ) : """The Heart and Soul of IrcBot ."""
if e . type not in [ 'authenticate' , 'error' , 'join' , 'part' , 'quit' ] : nick = e . source . nick else : nick = e . source if e . arguments is None : msg = "" else : msg = " " . join ( e . arguments ) . strip ( ) # Send the response to private messages to the sending nick . target = nick if e . type...
def isothermal_gas ( rho , fd , P1 = None , P2 = None , L = None , D = None , m = None ) : # pragma : no cover '''> > > isothermal _ gas ( rho = 11.3 * u . kg / u . m * * 3 , fd = 0.00185 * u . dimensionless , P1 = 1E6 * u . Pa , P2 = 9E5 * u . Pa , L = 1000 * u . m , D = 0.5 * u . m ) < Quantity ( 145.484757264 ...
ans = wrapped_isothermal_gas ( rho , fd , P1 , P2 , L , D , m ) if m is None and ( None not in [ P1 , P2 , L , D ] ) : return ans * u . kg / u . s elif L is None and ( None not in [ P1 , P2 , D , m ] ) : return ans * u . m elif P1 is None and ( None not in [ L , P2 , D , m ] ) : return ans * u . Pa elif P2 ...
def _get_user ( self ) -> Dict : """Same thing as for ` _ get _ chat ( ) ` but for the user related to the message ."""
if 'callback_query' in self . _update : return self . _update [ 'callback_query' ] [ 'from' ] elif 'inline_query' in self . _update : return self . _update [ 'inline_query' ] [ 'from' ] elif 'message' in self . _update : return self . _update [ 'message' ] [ 'from' ]
def get_submissions_for_student_item ( request , course_id , student_id , item_id ) : """Retrieve all submissions associated with the given student item . Developer utility for accessing all the submissions associated with a student item . The student item is specified by the unique combination of course , st...
student_item_dict = dict ( course_id = course_id , student_id = student_id , item_id = item_id , ) context = dict ( ** student_item_dict ) try : submissions = get_submissions ( student_item_dict ) context [ "submissions" ] = submissions except SubmissionRequestError : context [ "error" ] = "The specified st...
def write_group ( self , grp , overwrite = False , ** kwargs ) : """Write the concatenated alignment to disk in the location specified by self . cache _ dir"""
id_ = self . get_id ( grp ) alignment_done , result_done = self . check_work_done ( grp ) self . cache [ grp ] = id_ al_filename = os . path . join ( self . cache_dir , '{}.phy' . format ( id_ ) ) qfile_filename = os . path . join ( self . cache_dir , '{}.partitions.txt' . format ( id_ ) ) if overwrite or not ( alignme...
def _LeaseMessageHandlerRequests ( self , lease_time , limit ) : """Read and lease some outstanding message handler requests ."""
leased_requests = [ ] now = rdfvalue . RDFDatetime . Now ( ) zero = rdfvalue . RDFDatetime . FromSecondsSinceEpoch ( 0 ) expiration_time = now + lease_time leases = self . message_handler_leases for requests in itervalues ( self . message_handler_requests ) : for r in itervalues ( requests ) : existing_leas...
def verify_string_dxid ( dxid , expected_classes ) : ''': param dxid : Value to verify as a DNAnexus ID of class * expected _ class * : param expected _ classes : Single string or list of strings of allowed classes of the ID , e . g . " file " or [ " project " , " container " ] : type expected _ classes : strin...
if isinstance ( expected_classes , basestring ) : expected_classes = [ expected_classes ] if not isinstance ( expected_classes , list ) or len ( expected_classes ) == 0 : raise DXError ( 'verify_string_dxid: expected_classes should be a string or list of strings' ) if not ( isinstance ( dxid , basestring ) and ...
def slugify ( text , delim = '-' ) : """Generates an slightly worse ASCII - only slug ."""
punctuation_re = re . compile ( r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.:]+' ) result = [ ] for word in punctuation_re . split ( text . lower ( ) ) : word = normalize_text ( word ) if word : result . append ( word ) return delim . join ( result )
def is_expired ( self ) : """` ` True ` ` if the signature has an expiration date , and is expired . Otherwise , ` ` False ` `"""
expires_at = self . expires_at if expires_at is not None and expires_at != self . created : return expires_at < datetime . utcnow ( ) return False
def execute ( self , sql , param = ( ) , times = 1 ) : """This function is the most use one , with the paramter times it will try x times to execute the sql , default is 1."""
self . log and self . log . debug ( '%s %s' % ( 'SQL:' , sql ) ) if param is not ( ) : self . log and self . log . debug ( '%s %s' % ( 'PARAMs:' , param ) ) for i in xrange ( times ) : try : ret , res = self . _execute ( sql , param ) return ret , res except Exception , e : self . lo...
def synchronize_files ( inputpaths , outpath , database = None , tqdm_bar = None , report_file = None , ptee = None , verbose = False ) : '''Main function to synchronize files contents by majority vote The main job of this function is to walk through the input folders and align the files , so that we can compare ...
# ( Generator ) Files Synchronization Algorithm : # Needs a function stable _ dir _ walking , which will walk through directories recursively but in always the same order on all platforms ( same order for files but also for folders ) , whatever order it is , as long as it is stable . # Until there ' s no file in any of...
def publish ( self , user = None , when = None ) : """Publishes a item and any sub items . A new transaction will be started if we aren ' t already in a transaction . Should only be run on draft items"""
assert self . state == self . DRAFT user_published = 'code' if user : user_published = user . username now = timezone . now ( ) with xact ( ) : # If this item hasn ' t got live yet and no new date was specified # delete the old scheduled items and schedule this one on that date published = False if getattr ...
def print_model ( self ) : """Return the assembled cards as a JSON string . Returns cards _ json : str The JSON string representing the assembled cards ."""
cards = [ c . card for c in self . cards ] # If there is only one card , print it as a single # card not as a list if len ( cards ) == 1 : cards = cards [ 0 ] cards_json = json . dumps ( cards , indent = 1 ) return cards_json
def share ( self , options = None , ** kwds ) : """Endpoint : / photos [ / < options > / share . json Not currently implemented ."""
option_string = self . _build_option_string ( options ) return self . _client . post ( "/photos%s/share.json" % option_string , ** kwds ) [ "result" ]
def get_choices ( self ) : """Return a list of choices for source files found in configured layout template directories ."""
choices = [ ] for label_prefix , templates_dir , template_name_prefix in appsettings . LAYOUT_TEMPLATES : source_dir = os . path . join ( templates_dir , template_name_prefix ) # Walk directories , appending a choice for each source file . for local , dirs , files in os . walk ( source_dir , followlinks = T...
def validate ( self , node ) : """Validate DjangoQL AST tree vs . current schema"""
assert isinstance ( node , Node ) if isinstance ( node . operator , Logical ) : self . validate ( node . left ) self . validate ( node . right ) return assert isinstance ( node . left , Name ) assert isinstance ( node . operator , Comparison ) assert isinstance ( node . right , ( Const , List ) ) # Check th...