signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _get_encryption_headers ( key , source = False ) : """Builds customer encryption key headers : type key : bytes : param key : 32 byte key to build request key and hash . : type source : bool : param source : If true , return headers for the " source " blob ; otherwise , return headers for the " destin...
if key is None : return { } key = _to_bytes ( key ) key_hash = hashlib . sha256 ( key ) . digest ( ) key_hash = base64 . b64encode ( key_hash ) key = base64 . b64encode ( key ) if source : prefix = "X-Goog-Copy-Source-Encryption-" else : prefix = "X-Goog-Encryption-" return { prefix + "Algorithm" : "AES256"...
def infer_format ( filename : str ) -> str : """Return extension identifying format of given filename"""
_ , ext = os . path . splitext ( filename ) return ext
def _decode_message_set_iter ( cls , data ) : """Iteratively decode a MessageSet Reads repeated elements of ( offset , message ) , calling decode _ message to decode a single message . Since compressed messages contain futher MessageSets , these two methods have been decoupled so that they may recurse easil...
cur = 0 read_message = False while cur < len ( data ) : try : ( ( offset , ) , cur ) = relative_unpack ( '>q' , data , cur ) ( msg , cur ) = read_int_string ( data , cur ) for ( offset , message ) in KafkaProtocol . _decode_message ( msg , offset ) : read_message = True ...
def json_event_feed ( request , location_id = None , room_id = None ) : '''The Jquery fullcalendar app requires a JSON news feed , so this function creates the feed from upcoming PrivateEvent objects'''
if not getConstant ( 'calendar__privateCalendarFeedEnabled' ) or not request . user . is_staff : return JsonResponse ( { } ) this_user = request . user startDate = request . GET . get ( 'start' , '' ) endDate = request . GET . get ( 'end' , '' ) timeZone = request . GET . get ( 'timezone' , getattr ( settings , 'TI...
def float_to_knx2 ( floatval ) : """Convert a float to a 2 byte KNX float value"""
if floatval < - 671088.64 or floatval > 670760.96 : raise KNXException ( "float {} out of valid range" . format ( floatval ) ) floatval = floatval * 100 i = 0 for i in range ( 0 , 15 ) : exp = pow ( 2 , i ) if ( ( floatval / exp ) >= - 2048 ) and ( ( floatval / exp ) < 2047 ) : break if floatval < 0...
def to_file ( epub , file ) : """Export to ` ` file ` ` , which is a * file * or * file - like object * ."""
directory = tempfile . mkdtemp ( '-epub' ) # Write out the contents to the filesystem . package_filenames = [ ] for package in epub : opf_filepath = Package . to_file ( package , directory ) opf_filename = os . path . basename ( opf_filepath ) package_filenames . append ( opf_filename ) # Create the contain...
def content_children ( self ) : """A sequence containing the text - container child elements of this ` ` < a : p > ` ` element , i . e . ( a : r | a : br | a : fld ) ."""
text_types = { CT_RegularTextRun , CT_TextLineBreak , CT_TextField } return tuple ( elm for elm in self if type ( elm ) in text_types )
def set_resolved_url ( self , item = None , subtitles = None ) : '''Takes a url or a listitem to be played . Used in conjunction with a playable list item with a path that calls back into your addon . : param item : A playable list item or url . Pass None to alert XBMC of a failure to resolve the item . . ....
if self . _end_of_directory : raise Exception ( 'Current XBMC handle has been removed. Either ' 'set_resolved_url(), end_of_directory(), or ' 'finish() has already been called.' ) self . _end_of_directory = True succeeded = True if item is None : # None item indicates the resolve url failed . item = { } suc...
def position_p ( self ) : """The proportional constant for the position PID ."""
self . _position_p , value = self . get_attr_int ( self . _position_p , 'hold_pid/Kp' ) return value
def get_file_mime_encoding ( parts ) : """Get encoding value from splitted output of file - - mime - - uncompress ."""
for part in parts : for subpart in part . split ( " " ) : if subpart . startswith ( "compressed-encoding=" ) : mime = subpart . split ( "=" ) [ 1 ] . strip ( ) return Mime2Encoding . get ( mime ) return None
def _find_variable ( self , pattern , logline ) : """Return the variable parts of the code given a tuple of strings pattern . Example : ( this , is , a , pattern ) - > ' this is a good pattern ' - > [ good ]"""
var_subs = [ ] # find the beginning of the pattern first_index = logline . index ( pattern [ 0 ] ) beg_str = logline [ : first_index ] # strip the beginning substring var_subs . append ( self . _strip_datetime ( beg_str ) ) for patt , patt_next in zip ( pattern [ : - 1 ] , pattern [ 1 : ] ) : # regular expression patte...
def _new_conn ( self ) : """Return a fresh : class : ` httplib . HTTPConnection ` ."""
self . num_connections += 1 log . info ( "Starting new HTTP connection (%d): %s" % ( self . num_connections , self . host ) ) return HTTPConnection ( host = self . host , port = self . port )
def binary_shader_for_rules ( self , output_jar , jar , rules , jvm_options = None ) : """Yields an ` Executor . Runner ` that will perform shading of the binary ` jar ` when ` run ( ) ` . No default rules are applied ; only the rules passed in as a parameter will be used . : param unicode output _ jar : The pa...
with self . temporary_rules_file ( rules ) as rules_file : logger . debug ( 'Running jarjar with rules:\n{}' . format ( ' ' . join ( rule . render ( ) for rule in rules ) ) ) yield self . _executor . runner ( classpath = self . _jarjar_classpath , main = 'org.pantsbuild.jarjar.Main' , jvm_options = jvm_options ...
def _handle_tag_definefontalignzones ( self ) : """Handle the DefineFontAlignZones tag ."""
obj = _make_object ( "DefineFontAlignZones" ) obj . FontId = unpack_ui16 ( self . _src ) bc = BitConsumer ( self . _src ) obj . CSMTableHint = bc . u_get ( 2 ) obj . Reserved = bc . u_get ( 6 ) obj . ZoneTable = zone_records = [ ] glyph_count = self . _last_defined_glyphs_quantity self . _last_defined_glyphs_quantity =...
def get_paths ( folder , ignore_endswith = ignore_endswith ) : '''Return hologram file paths Parameters folder : str or pathlib . Path Path to search folder ignore _ endswith : list List of filename ending strings indicating which files should be ignored .'''
folder = pathlib . Path ( folder ) . resolve ( ) files = folder . rglob ( "*" ) for ie in ignore_endswith : files = [ ff for ff in files if not ff . name . endswith ( ie ) ] return sorted ( files )
def execute ( self , command ) : """Start a new MIP run ."""
process = subprocess . Popen ( command , preexec_fn = lambda : signal . signal ( signal . SIGPIPE , signal . SIG_DFL ) ) return process
def get_unique_fields ( fld_lists ) : """Get unique namedtuple fields , despite potential duplicates in lists of fields ."""
flds = [ ] fld_set = set ( [ f for flst in fld_lists for f in flst ] ) fld_seen = set ( ) # Add unique fields to list of fields in order that they appear for fld_list in fld_lists : for fld in fld_list : # Add fields if the field has not yet been seen if fld not in fld_seen : flds . append ( fld...
def wrap ( vtkdataset ) : """This is a convenience method to safely wrap any given VTK data object to its appropriate ` ` vtki ` ` data object ."""
wrappers = { 'vtkUnstructuredGrid' : vtki . UnstructuredGrid , 'vtkRectilinearGrid' : vtki . RectilinearGrid , 'vtkStructuredGrid' : vtki . StructuredGrid , 'vtkPolyData' : vtki . PolyData , 'vtkImageData' : vtki . UniformGrid , 'vtkStructuredPoints' : vtki . UniformGrid , 'vtkMultiBlockDataSet' : vtki . MultiBlock , }...
def RegisterCredentials ( cls , credentials ) : """Registers a path specification credentials . Args : credentials ( Credentials ) : credentials . Raises : KeyError : if credentials object is already set for the corresponding type indicator ."""
if credentials . type_indicator in cls . _credentials : raise KeyError ( 'Credentials object already set for type indicator: {0:s}.' . format ( credentials . type_indicator ) ) cls . _credentials [ credentials . type_indicator ] = credentials
def nick ( self , nick ) : """Sets your nick . Required arguments : * nick - New nick or a tuple of possible new nicks ."""
nick_set_successfully = False try : self . _nick ( nick ) nick_set_successfully = True except TypeError : for nick_ in nick : try : self . _nick ( nick_ ) nick_set_successfully = True break except self . NicknameInUse : pass if not nick_set_suc...
def qteRegisterApplet ( self , cls , replaceApplet : bool = False ) : """Register ` ` cls ` ` as an applet . The name of the applet is the class name of ` ` cls ` ` itself . For instance , if the applet was defined and registered as class NewApplet17 ( QtmacsApplet ) : app _ name = qteRegisterApplet ( New...
# Check type of input arguments . if not issubclass ( cls , QtmacsApplet ) : args = ( 'cls' , 'class QtmacsApplet' , inspect . stack ( ) [ 0 ] [ 3 ] ) raise QtmacsArgumentError ( * args ) # Extract the class name as string , because this is the name # under which the applet will be known . class_name = cls . __...
def getWindowPID ( self , hwnd ) : """Gets the process ID that the specified window belongs to"""
for w in self . _get_window_list ( ) : if "kCGWindowNumber" in w and w [ "kCGWindowNumber" ] == hwnd : return w [ "kCGWindowOwnerPID" ]
def set ( self , val ) : """Set the value"""
import time now = time . time ( ) expected_value = [ ] new_val = { } new_val [ 'timestamp' ] = now if self . _value != None : new_val [ 'last_value' ] = self . _value expected_value = [ 'current_value' , str ( self . _value ) ] new_val [ 'current_value' ] = val try : self . db . put_attributes ( self . id ,...
def v_type_base ( ctx , stmt , no_error_report = False ) : """verify that the referenced identity exists ."""
# Find the identity name = stmt . arg stmt . i_identity = None if name . find ( ":" ) == - 1 : prefix = None else : [ prefix , name ] = name . split ( ':' , 1 ) if prefix is None or stmt . i_module . i_prefix == prefix : # check local identities pmodule = stmt . i_module else : # this is a prefixed name , c...
def get_float ( self , key : str ) -> Optional [ float ] : """Returns an optional configuration value , as a float , by its key , or None if it doesn ' t exist . If the configuration value isn ' t a legal float , this function will throw an error . : param str key : The requested configuration key . : return ...
v = self . get ( key ) if v is None : return None try : return float ( v ) except : raise ConfigTypeError ( self . full_key ( key ) , v , 'float' )
def _set_tag ( self , tag = None , tags = None , value = True ) : """Sets the value of a specific tag or merges existing tags with a dict of new tags . Either tag or tags must be None . : param tag : Tag which needs to be set . : param tags : Set of tags which needs to be merged with existing tags . : param...
existing_tags = self . _requirements . get ( "tags" ) if tags and not tag : existing_tags = merge ( existing_tags , tags ) self . _requirements [ "tags" ] = existing_tags elif tag and not tags : existing_tags [ tag ] = value self . _requirements [ "tags" ] = existing_tags
def verify ( self , ** kwargs ) : """Implementations MUST either return both a Client Configuration Endpoint and a Registration Access Token or neither of them . : param kwargs : : return : True if the message is OK otherwise False"""
super ( RegistrationResponse , self ) . verify ( ** kwargs ) has_reg_uri = "registration_client_uri" in self has_reg_at = "registration_access_token" in self if has_reg_uri != has_reg_at : raise VerificationError ( ( "Only one of registration_client_uri" " and registration_access_token present" ) , self ) return Tr...
def duplicates ( table , key = None , presorted = False , buffersize = None , tempdir = None , cache = True ) : """Select rows with duplicate values under a given key ( or duplicate rows where no key is given ) . E . g . : : > > > import petl as etl > > > table1 = [ [ ' foo ' , ' bar ' , ' baz ' ] , . . . [...
return DuplicatesView ( table , key = key , presorted = presorted , buffersize = buffersize , tempdir = tempdir , cache = cache )
def update_flapping ( self , notif_period , hosts , services ) : """Compute the sample list ( self . flapping _ changes ) and determine whether the host / service is flapping or not : param notif _ period : notification period object for this host / service : type notif _ period : alignak . object . timeperio...
flap_history = self . __class__ . flap_history # We compute the flapping change in % res = 0.0 i = 0 for has_changed in self . flapping_changes : i += 1 if has_changed : res += i * ( 1.2 - 0.8 ) / flap_history + 0.8 res = res / flap_history res *= 100 # We can update our value self . percent_state_chang...
def quote_name ( self , name ) : """Returns a quoted version of the given table , index or column name . Does not quote the given name if it ' s already been quoted ."""
if name . startswith ( self . left_sql_quote ) and name . endswith ( self . right_sql_quote ) : return name # Quoting once is enough . return '%s%s%s' % ( self . left_sql_quote , name , self . right_sql_quote )
def record_close ( object_id , input_params = { } , always_retry = True , ** kwargs ) : """Invokes the / record - xxxx / close API method . For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Data - Object - Lifecycle # API - method % 3A - % 2Fclass - xxxx % 2Fclose"""
return DXHTTPRequest ( '/%s/close' % object_id , input_params , always_retry = always_retry , ** kwargs )
def doesNotMatch ( self , value , caseSensitive = True ) : """Sets the operator type to Query . Op . DoesNotMatch and sets the value to the inputted value . : param value < variant > : return self ( useful for chaining ) : usage | > > > from orb import Query as Q | > > > query = Q ( ' comments ' ) . doesNot...
newq = self . copy ( ) newq . setOp ( Query . Op . DoesNotMatch ) newq . setValue ( value ) newq . setCaseSensitive ( caseSensitive ) return newq
def get ( project , credentials = None ) : """Main Get method : Get project state , parameters , outputindex"""
user , oauth_access_token = parsecredentials ( credentials ) if not Project . exists ( project , user ) : return withheaders ( flask . make_response ( "Project " + project + " was not found for user " + user , 404 ) , headers = { 'allow_origin' : settings . ALLOW_ORIGIN } ) # 404 else : # if user and not Projec...
def python_portable_string ( string , encoding = 'utf-8' ) : """Converts bytes into a string type . Valid string types are retuned without modification . So in Python 2 , type str and unicode are not converted . In Python 3 , type bytes is converted to type str ( unicode )"""
if isinstance ( string , six . string_types ) : return string if six . PY3 : return string . decode ( encoding ) raise ValueError ( 'Unsupported type %s' % str ( type ( string ) ) )
def attribute_node ( self , name , ns_uri = None ) : """: param string name : the name of the attribute to return . : param ns _ uri : a URI defining a namespace constraint on the attribute . : type ns _ uri : string or None : return : this element ' s attributes that match ` ` ns _ uri ` ` as : class : ` A...
attr_impl_node = self . adapter . get_node_attribute_node ( self . impl_node , name , ns_uri ) return self . adapter . wrap_node ( attr_impl_node , self . adapter . impl_document , self . adapter )
def quantile ( arg , quantile , interpolation = 'linear' ) : """Return value at the given quantile , a la numpy . percentile . Parameters quantile : float / int or array - like 0 < = quantile < = 1 , the quantile ( s ) to compute interpolation : { ' linear ' , ' lower ' , ' higher ' , ' midpoint ' , ' neare...
if isinstance ( quantile , collections . abc . Sequence ) : op = ops . MultiQuantile ( arg , quantile , interpolation ) else : op = ops . Quantile ( arg , quantile , interpolation ) return op . to_expr ( )
def call ( payload = None ) : '''This function captures the query string and sends it to the Palo Alto device .'''
r = None try : if DETAILS [ 'method' ] == 'dev_key' : # Pass the api key without the target declaration conditional_payload = { 'key' : DETAILS [ 'apikey' ] } payload . update ( conditional_payload ) r = __utils__ [ 'http.query' ] ( DETAILS [ 'url' ] , data = payload , method = 'POST' , deco...
def _log_failed_submission ( self , data ) : """Log a reasonable representation of an event that should have been sent to Sentry"""
message = data . pop ( 'message' , '<no message value>' ) output = [ message ] if 'exception' in data and 'stacktrace' in data [ 'exception' ] [ 'values' ] [ - 1 ] : # try to reconstruct a reasonable version of the exception for frame in data [ 'exception' ] [ 'values' ] [ - 1 ] [ 'stacktrace' ] . get ( 'frames' , ...
def parse_type ( field ) : """Function to pull a type from the binary payload ."""
if field . type_id == 'string' : if 'size' in field . options : return "parser.getString(%d)" % field . options [ 'size' ] . value else : return "parser.getString()" elif field . type_id in JAVA_TYPE_MAP : # Primitive java types have extractor methods in SBPMessage . Parser return "parser.ge...
def check_scope ( self , token , request ) : http_method = request . method if not hasattr ( self , http_method ) : raise OAuthError ( "HTTP method is not recognized" ) required_scopes = getattr ( self , http_method ) # a None scope means always allowed if required_scopes is None : r...
# for non iterable types if isinstance ( required_scopes , six . string_types ) : if token . allow_scopes ( required_scopes . split ( ) ) : return [ required_scopes ] return [ ] allowed_scopes = [ ] try : for scope in required_scopes : if token . allow_scopes ( scope . split ( ) ) : ...
def Binomial ( n , p , tag = None ) : """A Binomial random variate Parameters n : int The number of trials p : scalar The probability of success"""
assert ( int ( n ) == n and n > 0 ) , 'Binomial number of trials "n" must be an integer greater than zero' assert ( 0 < p < 1 ) , 'Binomial probability "p" must be between zero and one, non-inclusive' return uv ( ss . binom ( n , p ) , tag = tag )
def load_map_coordinates ( map_file ) : """Loads map coordinates from netCDF or pickle file created by util . makeMapGrids . Args : map _ file : Filename for the file containing coordinate information . Returns : Latitude and longitude grids as numpy arrays ."""
if map_file [ - 4 : ] == ".pkl" : map_data = pickle . load ( open ( map_file ) ) lon = map_data [ 'lon' ] lat = map_data [ 'lat' ] else : map_data = Dataset ( map_file ) if "lon" in map_data . variables . keys ( ) : lon = map_data . variables [ 'lon' ] [ : ] lat = map_data . variable...
def input_stages ( self ) : """List ( int ) : Entry IDs for stages that were inputs for this stage ."""
if self . _properties . get ( "inputStages" ) is None : return [ ] return [ _helpers . _int_or_none ( entry ) for entry in self . _properties . get ( "inputStages" ) ]
def _chunk_with_padding ( self , iterable , n , fillvalue = None ) : "Collect data into fixed - length chunks or blocks"
# _ chunk _ with _ padding ( ' ABCDEFG ' , 3 , ' x ' ) - - > ABC DEF Gxx " args = [ iter ( iterable ) ] * n return zip_longest ( * args , fillvalue = fillvalue )
def from_dict ( cls , parm , vrf = None ) : """Create new VRF - object from dict . Suitable for creating objects from XML - RPC data . All available keys must exist ."""
if vrf is None : vrf = VRF ( ) vrf . id = parm [ 'id' ] vrf . rt = parm [ 'rt' ] vrf . name = parm [ 'name' ] vrf . description = parm [ 'description' ] vrf . tags = { } for tag_name in parm [ 'tags' ] : tag = Tag . from_dict ( { 'name' : tag_name } ) vrf . tags [ tag_name ] = tag vrf . avps = parm [ 'avps'...
def show_usage ( docstring , short , stream , exitcode ) : """Print program usage information and exit . : arg str docstring : the program help text This function just prints * docstring * and exits . In most cases , the function : func : ` check _ usage ` should be used : it automatically checks : data : `...
if stream is None : from sys import stdout as stream if not short : print ( 'Usage:' , docstring . strip ( ) , file = stream ) else : intext = False for l in docstring . splitlines ( ) : if intext : if not len ( l ) : break print ( l , file = stream ) ...
def equals ( self , rhs ) : """Check to see if the RHS is an instance of class _ name . Args : # rhs : the right hand side of the test rhs : object Returns : bool"""
try : return isinstance ( rhs , self . _class_name ) except TypeError : # Check raw types if there was a type error . This is helpful for # things like cStringIO . StringIO . return type ( rhs ) == type ( self . _class_name )
def mac ( address = '' , interface = '' , vlan = 0 , ** kwargs ) : # pylint : disable = unused - argument '''Returns the MAC Address Table on the device . : param address : MAC address to filter on : param interface : Interface name to filter on : param vlan : VLAN identifier : return : A list of dictionari...
proxy_output = salt . utils . napalm . call ( napalm_device , # pylint : disable = undefined - variable 'get_mac_address_table' , ** { } ) if not proxy_output . get ( 'result' ) : # if negative , leave the output unchanged return proxy_output mac_address_table = proxy_output . get ( 'out' ) if vlan and isinstance (...
def _load_first ( self , target_uris , load_method , ** kwargs ) : """Load first yamldict target found in uri list . : param target _ uris : Uris to try and open : param load _ method : load callback : type target _ uri : list or string : type load _ method : callback : returns : yamldict"""
if isinstance ( target_uris , string_types ) : target_uris = [ target_uris ] # TODO : Move the list logic into the extension , otherwise a # load will always try all missing files first . # TODO : How would multiple protocols work , should the registry hold # persist copies ? for target_uri in target_uris : tar...
def update_task ( self , task_id , revision , title = None , assignee_id = None , completed = None , recurrence_type = None , recurrence_count = None , due_date = None , starred = None , remove = None ) : '''Updates the task with the given ID to have the given information NOTE : The ' remove ' parameter is an opt...
return tasks_endpoint . update_task ( self , task_id , revision , title = title , assignee_id = assignee_id , completed = completed , recurrence_type = recurrence_type , recurrence_count = recurrence_count , due_date = due_date , starred = starred , remove = remove )
def _incident_transform ( incident ) : """Get output dict from incident ."""
return { 'id' : incident . get ( 'cdid' ) , 'type' : incident . get ( 'type' ) , 'timestamp' : incident . get ( 'date' ) , 'lat' : incident . get ( 'lat' ) , 'lon' : incident . get ( 'lon' ) , 'location' : incident . get ( 'address' ) , 'link' : incident . get ( 'link' ) }
def add ( self , * args , ** kwargs ) : """Add to list of cats"""
return self . cat . select . add ( * args , ** kwargs )
def matrix_to_timeseries ( image , matrix , mask = None ) : """converts a matrix to a ND image . ANTsR function : ` matrix2timeseries ` Arguments image : reference ND image matrix : matrix to convert to image mask : mask image defining voxels of interest Returns ANTsImage Example > > > import ants...
if mask is None : mask = temp [ 0 ] * 0 + 1 temp = matrix_to_images ( matrix , mask ) newImage = utils . list_to_ndimage ( image , temp ) iio . copy_image_info ( image , newImage ) return ( newImage )
def add_chain ( self , chain ) : """Add block in a chain in the correct order . Also add all of the blocks to the cache before doing a purge ."""
with self . _lock : chain . sort ( key = lambda x : x . block_num ) for block in chain : block_id = block . header_signature if block_id not in self . _cache : self . _cache [ block_id ] = self . CachedValue ( block ) if block . previous_block_id in self . _cache : ...
def dfs ( node , expand = expansion_all , callback = None , silent = True ) : """Perform a depth - first search on the node graph : param node : GraphNode : param expand : Returns the list of Nodes to explore from a Node : param callback : Callback to run in each node : param silent : Don ' t throw exceptio...
nodes = deque ( ) for n in expand ( node ) : nodes . append ( n ) while nodes : n = nodes . pop ( ) n . visits += 1 if callback : callback ( n ) for k in expand ( n ) : if k . visits < 1 : nodes . append ( k ) else : if not silent : rai...
def view_pmap ( token , dstore ) : """Display the mean ProbabilityMap associated to a given source group name"""
grp = token . split ( ':' ) [ 1 ] # called as pmap : grp pmap = { } rlzs_assoc = dstore [ 'csm_info' ] . get_rlzs_assoc ( ) pgetter = getters . PmapGetter ( dstore , rlzs_assoc ) pmap = pgetter . get_mean ( grp ) return str ( pmap )
def _REOM ( y , t , pot , l2 ) : """NAME : _ REOM PURPOSE : implements the EOM , i . e . , the right - hand side of the differential equation INPUT : y - current phase - space position t - current time pot - ( list of ) Potential instance ( s ) l2 - angular momentum squared OUTPUT : dy / dt ...
return [ y [ 1 ] , l2 / y [ 0 ] ** 3. + _evaluateplanarRforces ( pot , y [ 0 ] , t = t ) ]
def sample_bitstrings ( self , n_samples ) : """Sample bitstrings from the distribution defined by the wavefunction . Qubit 0 is at ` ` out [ : , 0 ] ` ` . : param n _ samples : The number of bitstrings to sample : return : An array of shape ( n _ samples , n _ qubits )"""
if self . rs is None : raise ValueError ( "You have tried to perform a stochastic operation without setting the " "random state of the simulator. Might I suggest using a PyQVM object?" ) probabilities = np . abs ( self . wf ) ** 2 possible_bitstrings = all_bitstrings ( self . n_qubits ) inds = self . rs . choice ( ...
def delaunay_graph ( X , weighted = False ) : '''Delaunay triangulation graph .'''
e1 , e2 = _delaunay_edges ( X ) pairs = np . column_stack ( ( e1 , e2 ) ) w = paired_distances ( X [ e1 ] , X [ e2 ] ) if weighted else None return Graph . from_edge_pairs ( pairs , num_vertices = X . shape [ 0 ] , symmetric = True , weights = w )
def append_sint32 ( self , value ) : """Appends a 32 - bit integer to our buffer , zigzag - encoded and then varint - encoded ."""
zigzag_value = wire_format . zig_zag_encode ( value ) self . _stream . append_var_uint32 ( zigzag_value )
def tune ( runner , kernel_options , device_options , tuning_options ) : """Find the best performing kernel configuration in the parameter space : params runner : A runner from kernel _ tuner . runners : type runner : kernel _ tuner . runner : param kernel _ options : A dictionary with all options for the ker...
dna_size = len ( tuning_options . tune_params . keys ( ) ) pop_size = 20 generations = 100 tuning_options [ "scaling" ] = False tune_params = tuning_options . tune_params population = random_population ( dna_size , pop_size , tune_params ) best_time = 1e20 all_results = [ ] cache = { } for generation in range ( generat...
async def is_pairwise_exists ( wallet_handle : int , their_did : str ) -> bool : """Check if pairwise is exists . : param wallet _ handle : wallet handler ( created by open _ wallet ) . : param their _ did : encoded Did . : return : true - if pairwise is exists , false - otherwise"""
logger = logging . getLogger ( __name__ ) logger . debug ( "is_pairwise_exists: >>> wallet_handle: %r, their_did: %r" , wallet_handle , their_did ) if not hasattr ( is_pairwise_exists , "cb" ) : logger . debug ( "is_pairwise_exists: Creating callback" ) is_pairwise_exists . cb = create_cb ( CFUNCTYPE ( None , c...
def surround_parse ( self , node , pre_char , post_char ) : """Parse the subnodes of a given node . Subnodes with tags in the ` ignore ` list are ignored . Prepend ` pre _ char ` and append ` post _ char ` to the output in self . pieces ."""
self . add_text ( pre_char ) self . subnode_parse ( node ) self . add_text ( post_char )
def make_datalab_help_action ( self ) : """Custom action for - - datalab - help . The action output the package specific parameters and will be part of " % % ml train " help string ."""
datalab_help = self . datalab_help epilog = self . datalab_epilog class _CustomAction ( argparse . Action ) : def __init__ ( self , option_strings , dest , help = None ) : super ( _CustomAction , self ) . __init__ ( option_strings = option_strings , dest = dest , nargs = 0 , help = help ) def __call__ (...
def sign ( user_id , user_type = None , today = None , session = None ) : """Check user id for validity , then sign user in if they are signed out , or out if they are signed in . : param user _ id : The ID of the user to sign in or out . : param user _ type : ( optional ) Specify whether user is signing in a...
# noqa if session is None : session = Session ( ) else : session = session if today is None : today = date . today ( ) else : today = today user = ( session . query ( User ) . filter ( User . user_id == user_id ) . one_or_none ( ) ) if user : signed_in_entries = ( user . entries . filter ( Entry . d...
def iter_shortcuts ( ) : """Iterate over keyboard shortcuts ."""
for context_name , keystr in CONF . items ( 'shortcuts' ) : context , name = context_name . split ( "/" , 1 ) yield context , name , keystr
def aget ( dct , key ) : r"""Allow to get values deep in a dict with iterable keys Accessing leaf values is quite straightforward : > > > dct = { ' a ' : { ' x ' : 1 , ' b ' : { ' c ' : 2 } } } > > > aget ( dct , ( ' a ' , ' x ' ) ) > > > aget ( dct , ( ' a ' , ' b ' , ' c ' ) ) If key is empty , it retur...
key = iter ( key ) try : head = next ( key ) except StopIteration : return dct if isinstance ( dct , list ) : try : idx = int ( head ) except ValueError : raise IndexNotIntegerError ( "non-integer index %r provided on a list." % head ) try : value = dct [ idx ] except Ind...
def process ( self ) : """This method handles the actual processing of Modules and Transforms"""
self . modules . sort ( key = lambda x : x . priority ) for module in self . modules : transforms = module . transform ( self . data ) transforms . sort ( key = lambda x : x . linenum , reverse = True ) for transform in transforms : linenum = transform . linenum if isinstance ( transform . d...
def scopusParser ( scopusFile ) : """Parses a scopus file , _ scopusFile _ , to extract the individual lines as [ ScopusRecords ] ( . . / classes / ScopusRecord . html # metaknowledge . scopus . ScopusRecord ) . A Scopus file is a csv ( Comma - separated values ) with a complete header , see [ ` scopus . scopusHe...
# assumes the file is Scopus recSet = set ( ) error = None lineNum = 0 try : with open ( scopusFile , 'r' , encoding = 'utf-8' ) as openfile : # Get rid of the BOM openfile . read ( 1 ) header = openfile . readline ( ) [ : - 1 ] . split ( ',' ) if len ( set ( header ) ^ set ( scopusHeader ) ...
def get_obsolete_messages ( self , domain ) : """Returns obsolete valid messages after operation . @ type domain : str @ rtype : dict"""
if domain not in self . domains : raise ValueError ( 'Invalid domain: {0}' . format ( domain ) ) if domain not in self . messages or 'obsolete' not in self . messages [ domain ] : self . _process_domain ( domain ) return self . messages [ domain ] [ 'obsolete' ]
def remove_cert ( name , thumbprint , context = _DEFAULT_CONTEXT , store = _DEFAULT_STORE ) : '''Remove the certificate from the given certificate store . : param str thumbprint : The thumbprint value of the target certificate . : param str context : The name of the certificate store location context . : para...
ret = { 'name' : name , 'changes' : dict ( ) , 'comment' : six . text_type ( ) , 'result' : None } store_path = r'Cert:\{0}\{1}' . format ( context , store ) current_certs = __salt__ [ 'win_pki.get_certs' ] ( context = context , store = store ) if thumbprint not in current_certs : ret [ 'comment' ] = "Certificate '...
def create_swagger_json_handler ( app , ** kwargs ) : """Create a handler that returns the swagger definition for an application . This method assumes the application is using the TransmuteUrlDispatcher as the router ."""
spec = getattr ( app , SWAGGER_ATTR_NAME , SwaggerSpec ( ) ) _add_blueprint_specs ( app , spec ) spec_dict = spec . swagger_definition ( ** kwargs ) encoded_spec = json . dumps ( spec_dict ) . encode ( "UTF-8" ) def swagger ( ) : return Response ( encoded_spec , # we allow CORS , so this can be requested at swagger...
def a_return_and_reconnect ( ctx ) : """Send new line and reconnect ."""
ctx . ctrl . send ( "\r" ) ctx . device . connect ( ctx . ctrl ) return True
def touch ( self , mode = 0o666 , exist_ok = True ) : """Create a fake file for the path with the given access mode , if it doesn ' t exist . Args : mode : the file mode for the file if it does not exist exist _ ok : if the file already exists and this is True , nothing happens , otherwise FileExistError ...
if self . _closed : self . _raise_closed ( ) if self . exists ( ) : if exist_ok : self . filesystem . utime ( self . _path ( ) , None ) else : self . filesystem . raise_os_error ( errno . EEXIST , self . _path ( ) ) else : fake_file = self . open ( 'w' ) fake_file . close ( ) sel...
def _validate_configuration_type ( self , configuration_type ) : """Validate configuration type : param configuration _ type : configuration _ type , should be Startup or Running : raise Exception :"""
if configuration_type . lower ( ) != 'running' and configuration_type . lower ( ) != 'startup' : raise Exception ( self . __class__ . __name__ , 'Configuration Type is invalid. Should be startup or running' )
def set_We ( self , We , Eemin = None , Eemax = None , amplitude_name = None ) : """Normalize particle distribution so that the total energy in electrons between Eemin and Eemax is We Parameters We : : class : ` ~ astropy . units . Quantity ` float Desired energy in electrons . Eemin : : class : ` ~ astro...
We = validate_scalar ( "We" , We , physical_type = "energy" ) oldWe = self . compute_We ( Eemin = Eemin , Eemax = Eemax ) if amplitude_name is None : try : self . particle_distribution . amplitude *= ( We / oldWe ) . decompose ( ) except AttributeError : log . error ( "The particle distribution ...
def validate ( self , value , param_name , exc = None , logger = None ) : """: param value : value to validate : param param _ name : name of the value ( for logging purpose ) : param exc : exception to raise ( default is " ValidatorError " ) : param logger : logger to use ( default will be " Validator . logg...
if exc is not None : self . exc = exc if logger is not None : self . logger = logger if self . type is not None and not type ( value ) == self . type : # pylint : disable = unidiomatic - typecheck self . error ( f'invalid type for parameter "{param_name}": {type(value)} (value: {value}) -- expected {self.ty...
def start ( self , timeout = None ) : """Install the server on its IOLoop , optionally starting the IOLoop . Parameters timeout : float or None , optional Time in seconds to wait for server thread to start ."""
if self . _running . isSet ( ) : raise RuntimeError ( 'Server already started' ) self . _stopped . clear ( ) # Make sure we have an ioloop self . ioloop = self . _ioloop_manager . get_ioloop ( ) self . _ioloop_manager . start ( ) # Set max _ buffer _ size to ensure streams are closed # if too - large messages are r...
def run ( ctx , commandline ) : """Run command with environment variables present ."""
file = ctx . obj [ 'FILE' ] dotenv_as_dict = dotenv_values ( file ) if not commandline : click . echo ( 'No command given.' ) exit ( 1 ) ret = run_command ( commandline , dotenv_as_dict ) exit ( ret )
def move_to_customer_quote ( self , quote_id , product_data , store_view = None ) : """Allows you to move products from the current quote to a customer quote . : param quote _ id : Shopping cart ID ( quote ID ) : param product _ data , list of dicts of product details , example ' product _ id ' : 1, ' qty '...
return bool ( self . call ( 'cart_product.moveToCustomerQuote' , [ quote_id , product_data , store_view ] ) )
def _read_info_as_dict ( fid , values ) : """Convenience function to read info in axon data to a nicely organized dict ."""
output = { } for key , fmt in values : val = unpack ( fmt , fid . read ( calcsize ( fmt ) ) ) if len ( val ) == 1 : output [ key ] = val [ 0 ] else : output [ key ] = val return output
def present ( name , createdb = None , createroles = None , encrypted = None , superuser = None , inherit = None , login = None , replication = None , password = None , refresh_password = None , groups = None , user = None , maintenance_db = None , db_password = None , db_host = None , db_port = None , db_user = None )...
ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : 'Group {0} is already present' . format ( name ) } # default to encrypted passwords if encrypted is not False : encrypted = postgres . _DEFAULT_PASSWORDS_ENCRYPTION # maybe encrypt if it ' s not already and necessary password = postgres . _mayb...
def update_launch_config ( self , scaling_group , server_name = None , image = None , flavor = None , disk_config = None , metadata = None , personality = None , networks = None , load_balancers = None , key_name = None , config_drive = False , user_data = None ) : """Updates the server launch configuration for an ...
return self . _manager . update_launch_config ( scaling_group , server_name = server_name , image = image , flavor = flavor , disk_config = disk_config , metadata = metadata , personality = personality , networks = networks , load_balancers = load_balancers , key_name = key_name , config_drive = config_drive , user_dat...
def atlas_node_stop ( atlas_state ) : """Stop the atlas node threads"""
for component in atlas_state . keys ( ) : log . debug ( "Stopping Atlas component '%s'" % component ) atlas_state [ component ] . ask_join ( ) atlas_state [ component ] . join ( ) return True
def _get_repo_file_url ( namespace , filename ) : """Return the URL for hosted file in Gluon repository . Parameters namespace : str Namespace of the file . filename : str Name of the file"""
return '{base_url}{namespace}/{filename}' . format ( base_url = _get_repo_url ( ) , namespace = namespace , filename = filename )
def uniq ( args ) : """% prog uniq fasta uniq . fasta remove fasta records that are the same"""
p = OptionParser ( uniq . __doc__ ) p . add_option ( "--seq" , default = False , action = "store_true" , help = "Uniqify the sequences [default: %default]" ) p . add_option ( "-t" , "--trimname" , dest = "trimname" , action = "store_true" , default = False , help = "turn on the defline trim to first space [default: %de...
def check_type ( param , datatype ) : """Make sure that param is of type datatype and return it . If param is None , return it . If param is an instance of datatype , return it . If param is not an instance of datatype and is not None , cast it as datatype and return it ."""
if param is None : return param if getattr ( datatype , 'clean' , None ) and callable ( datatype . clean ) : try : return datatype . clean ( param ) except ValueError : raise BadArgumentError ( param ) elif isinstance ( datatype , str ) : # You ' ve given it something like ` ' bool ' ` as a ...
def reset_indent ( token_class ) : """Reset the indentation levels ."""
def callback ( lexer , match , context ) : text = match . group ( ) context . indent_stack = [ ] context . indent = - 1 context . next_indent = 0 context . block_scalar_indent = None yield match . start ( ) , token_class , text context . pos = match . end ( ) return callback
def get_service_url ( request , redirect_to = None ) : """Generates application django service URL for CAS"""
if hasattr ( django_settings , 'CAS_ROOT_PROXIED_AS' ) : service = django_settings . CAS_ROOT_PROXIED_AS + request . path else : protocol = get_protocol ( request ) host = request . get_host ( ) service = urllib_parse . urlunparse ( ( protocol , host , request . path , '' , '' , '' ) , ) if not django_s...
def _fisher_jenks_means ( values , classes = 5 , sort = True ) : """Jenks Optimal ( Natural Breaks ) algorithm implemented in Python . Notes The original Python code comes from here : http : / / danieljlewis . org / 2010/06/07 / jenks - natural - breaks - algorithm - in - python / and is based on a JAVA and...
if sort : values . sort ( ) n_data = len ( values ) mat1 = np . zeros ( ( n_data + 1 , classes + 1 ) , dtype = np . int32 ) mat2 = np . zeros ( ( n_data + 1 , classes + 1 ) , dtype = np . float32 ) mat1 [ 1 , 1 : ] = 1 mat2 [ 2 : , 1 : ] = np . inf v = np . float32 ( 0 ) for l in range ( 2 , len ( values ) + 1 ) : ...
def set_log_level ( self , level , keep = True ) : """Set the log level . If keep is True , then it will not change along with global log changes ."""
self . _set_log_level ( level ) self . _log_level_set_explicitly = keep
def rename_pickled_ontology ( filename , newname ) : """try to rename a cached ontology"""
pickledfile = ONTOSPY_LOCAL_CACHE + "/" + filename + ".pickle" newpickledfile = ONTOSPY_LOCAL_CACHE + "/" + newname + ".pickle" if os . path . isfile ( pickledfile ) and not GLOBAL_DISABLE_CACHE : os . rename ( pickledfile , newpickledfile ) return True else : return None
def _calc_real_and_point ( self ) : """Determines the self energy - ( eta / pi ) * * ( 1/2 ) * sum _ { i = 1 } ^ { N } q _ i * * 2"""
fcoords = self . _s . frac_coords forcepf = 2.0 * self . _sqrt_eta / sqrt ( pi ) coords = self . _coords numsites = self . _s . num_sites ereal = np . empty ( ( numsites , numsites ) , dtype = np . float ) forces = np . zeros ( ( numsites , 3 ) , dtype = np . float ) qs = np . array ( self . _oxi_states ) epoint = - qs...
def _addconfig ( config , * paths ) : """Add path to CONF _ DIRS if exists ."""
for path in paths : if path is not None and exists ( path ) : config . append ( path )
def get_tasks ( ) : '''Get a list of known tasks with their routing queue'''
return { name : get_task_queue ( name , cls ) for name , cls in celery . tasks . items ( ) # Exclude celery internal tasks if not name . startswith ( 'celery.' ) # Exclude udata test tasks and not name . startswith ( 'test-' ) }
def variance ( data , data_mean = None ) : """Return variance of a sequence of numbers . : param data _ mean : Precomputed mean of the sequence ."""
data_mean = data_mean or mean ( data ) return sum ( ( x - data_mean ) ** 2 for x in data ) / len ( data )
def _add_zoho_token ( self , uri , http_method = "GET" , body = None , headers = None , token_placement = None ) : """Add a zoho token to the request uri , body or authorization header . follows bearer pattern"""
headers = self . prepare_zoho_headers ( self . access_token , headers ) return uri , headers , body
def _pool_event_lifecycle_cb ( conn , pool , event , detail , opaque ) : '''Storage pool lifecycle events handler'''
_salt_send_event ( opaque , conn , { 'pool' : { 'name' : pool . name ( ) , 'uuid' : pool . UUIDString ( ) } , 'event' : _get_libvirt_enum_string ( 'VIR_STORAGE_POOL_EVENT_' , event ) , 'detail' : 'unknown' # currently unused } )
def leverages ( self , block = 'X' ) : """Calculate the leverages for each observation : return : : rtype :"""
# TODO check with matlab and simca try : if block == 'X' : return np . dot ( self . scores_t , np . dot ( np . linalg . inv ( np . dot ( self . scores_t . T , self . scores_t ) , self . scores_t . T ) ) ) elif block == 'Y' : return np . dot ( self . scores_u , np . dot ( np . linalg . inv ( np ....
def loo ( data , pointwise = False , reff = None , scale = "deviance" ) : """Pareto - smoothed importance sampling leave - one - out cross - validation . Calculates leave - one - out ( LOO ) cross - validation for out of sample predictive model fit , following Vehtari et al . ( 2017 ) . Cross - validation is co...
inference_data = convert_to_inference_data ( data ) for group in ( "posterior" , "sample_stats" ) : if not hasattr ( inference_data , group ) : raise TypeError ( "Must be able to extract a {group}" "group from data!" . format ( group = group ) ) if "log_likelihood" not in inference_data . sample_stats : ...