signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def make_grover_circuit ( input_qubits , output_qubit , oracle ) : """Find the value recognized by the oracle in sqrt ( N ) attempts ."""
# For 2 input qubits , that means using Grover operator only once . c = cirq . Circuit ( ) # Initialize qubits . c . append ( [ cirq . X ( output_qubit ) , cirq . H ( output_qubit ) , cirq . H . on_each ( * input_qubits ) , ] ) # Query oracle . c . append ( oracle ) # Construct Grover operator . c . append ( cirq . H ....
def tickPrice ( self , tickerId , field , price , canAutoExecute ) : """tickPrice ( EWrapper self , TickerId tickerId , TickType field , double price , int canAutoExecute )"""
return _swigibpy . EWrapper_tickPrice ( self , tickerId , field , price , canAutoExecute )
def export_serving ( self , filename , tags = [ tf . saved_model . SERVING if is_tfv2 ( ) else tf . saved_model . tag_constants . SERVING ] , signature_name = 'prediction_pipeline' ) : """Converts a checkpoint and graph to a servable for TensorFlow Serving . Use TF ' s ` SavedModelBuilder ` to export a trained mo...
self . graph = self . config . _maybe_create_graph ( ) with self . graph . as_default ( ) : input = PlaceholderInput ( ) input . setup ( self . config . input_signature ) with PredictTowerContext ( '' ) : self . config . tower_func ( * input . get_input_tensors ( ) ) input_tensors = get_tensors_...
def get_classes_in_module ( module , superclass = object ) : """Returns a list with all classes in module that descend from parent Args : module : builtins . module superclass : a class Returns : list"""
ret = [ ] for classname in dir ( module ) : attr = module . __getattribute__ ( classname ) try : if issubclass ( attr , superclass ) and ( attr != superclass ) : ret . append ( attr ) except TypeError : # " issubclass ( ) arg 1 must be a class " pass except RuntimeError : # a...
def points ( points , T_points_world = None , color = np . array ( [ 0 , 1 , 0 ] ) , scale = 0.01 , n_cuts = 20 , subsample = None , random = False , name = None ) : """Scatter a point cloud in pose T _ points _ world . Parameters points : autolab _ core . BagOfPoints or ( n , 3 ) float The point set to visua...
if isinstance ( points , BagOfPoints ) : if points . dim != 3 : raise ValueError ( 'BagOfPoints must have dimension 3xN!' ) else : if type ( points ) is not np . ndarray : raise ValueError ( 'Points visualizer expects BagOfPoints or numpy array!' ) if len ( points . shape ) == 1 : po...
def euclidean ( a , b ) : "Returns euclidean distance between a and b"
return np . linalg . norm ( np . subtract ( a , b ) )
def stop ( self ) : """Stop a running SocketIO web server . This method must be called from a HTTP or SocketIO handler function ."""
if self . server . eio . async_mode == 'threading' : func = flask . request . environ . get ( 'werkzeug.server.shutdown' ) if func : func ( ) else : raise RuntimeError ( 'Cannot stop unknown web server' ) elif self . server . eio . async_mode == 'eventlet' : raise SystemExit elif self . ...
def dump_memdb ( self , with_source_contents = True , with_names = True ) : """Dumps a sourcemap in MemDB format into bytes ."""
len_out = _ffi . new ( 'unsigned int *' ) buf = rustcall ( _lib . lsm_view_dump_memdb , self . _get_ptr ( ) , len_out , with_source_contents , with_names ) try : rv = _ffi . unpack ( buf , len_out [ 0 ] ) finally : _lib . lsm_buffer_free ( buf ) return rv
def summary ( self ) : '''Create a dictionary with a summary of the updates in the collection . Returns : dict : Summary of the contents of the collection . . code - block : : cfg Summary of Updates : { ' Total ' : < total number of updates returned > , ' Available ' : < updates that are not downloaded ...
# https : / / msdn . microsoft . com / en - us / library / windows / desktop / aa386099 ( v = vs . 85 ) . aspx if self . count ( ) == 0 : return 'Nothing to return' # Build a dictionary containing a summary of updates available results = { 'Total' : 0 , 'Available' : 0 , 'Downloaded' : 0 , 'Installed' : 0 , 'Catego...
def get_details ( self ) : """: rtype list [ VmDataField ]"""
data = [ ] if isinstance ( self . model , vCenterCloneVMFromVMResourceModel ) : data . append ( VmDetailsProperty ( key = 'Cloned VM Name' , value = self . model . vcenter_vm ) ) if isinstance ( self . model , VCenterDeployVMFromLinkedCloneResourceModel ) : template = self . model . vcenter_vm snapshot = se...
def get_contents ( diff_part ) : """Returns a tuple of old content and new content ."""
old_sha = get_old_sha ( diff_part ) old_filename = get_old_filename ( diff_part ) old_contents = get_old_contents ( old_sha , old_filename ) new_filename = get_new_filename ( diff_part ) new_contents = get_new_contents ( new_filename ) return old_contents , new_contents
def create_process ( self , command , shell = True , stdout = None , stderr = None , env = None ) : """Execute a process using subprocess . Popen , setting the backend ' s DISPLAY"""
env = env if env is not None else dict ( os . environ ) env [ 'DISPLAY' ] = self . display return subprocess . Popen ( command , shell = shell , stdout = stdout , stderr = stderr , env = env )
def _trivialgraph_default_namer ( thing , is_edge = True ) : """Returns a " good " string for thing in printed graphs ."""
if is_edge : if thing . name is None or thing . name . startswith ( 'tmp' ) : return '' else : return '/' . join ( [ thing . name , str ( len ( thing ) ) ] ) elif isinstance ( thing , Const ) : return str ( thing . val ) elif isinstance ( thing , WireVector ) : return thing . name or '??...
def dependents ( self , on_predicate = None , from_predicate = None ) : """Returns a map from targets that satisfy the from _ predicate to targets they depend on that satisfy the on _ predicate . : API : public"""
core = set ( self . targets ( on_predicate ) ) dependees = defaultdict ( set ) for target in self . targets ( from_predicate ) : for dependency in target . dependencies : if dependency in core : dependees [ target ] . add ( dependency ) return dependees
def _setup ( self ) : """for each string defined in self . weights , the corresponding attribute in the wrapped module is referenced , then deleted , and subsequently registered as a new parameter with a slightly modified name . Args : None Returns : None"""
if isinstance ( self . module , torch . nn . RNNBase ) : self . module . flatten_parameters = noop for name_w in self . weights : w = getattr ( self . module , name_w ) del self . module . _parameters [ name_w ] self . module . register_parameter ( name_w + '_raw' , nn . Parameter ( w . data ) )
def append_table ( src_con , dst_con , table_name ) : """Append a table from source database to destination database . : param SimpleSQLite src _ con : Connection to the source database . : param SimpleSQLite dst _ con : Connection to the destination database . : param str table _ name : Table name to append ...
logger . debug ( "append table: src={src_db}.{src_tbl}, dst={dst_db}.{dst_tbl}" . format ( src_db = src_con . database_path , src_tbl = table_name , dst_db = dst_con . database_path , dst_tbl = table_name , ) ) src_con . verify_table_existence ( table_name ) dst_con . validate_access_permission ( [ "w" , "a" ] ) if dst...
def datediff ( end , start ) : """Returns the number of days from ` start ` to ` end ` . > > > df = spark . createDataFrame ( [ ( ' 2015-04-08 ' , ' 2015-05-10 ' ) ] , [ ' d1 ' , ' d2 ' ] ) > > > df . select ( datediff ( df . d2 , df . d1 ) . alias ( ' diff ' ) ) . collect ( ) [ Row ( diff = 32 ) ]"""
sc = SparkContext . _active_spark_context return Column ( sc . _jvm . functions . datediff ( _to_java_column ( end ) , _to_java_column ( start ) ) )
def getFormattedHTML ( self , indent = ' ' ) : '''getFormattedHTML - Get formatted and xhtml of this document , replacing the original whitespace with a pretty - printed version @ param indent - space / tab / newline of each level of indent , or integer for how many spaces per level @ return - < str > Format...
from . Formatter import AdvancedHTMLFormatter html = self . getHTML ( ) formatter = AdvancedHTMLFormatter ( indent , None ) # Do not double - encode formatter . feed ( html ) return formatter . getHTML ( )
def bind ( self , field_name , parent ) : """Initializes the field name and parent for the field instance . Called when a field is added to the parent serializer instance . Taken from DRF and modified to support drf _ haystack multiple index functionality ."""
# In order to enforce a consistent style , we error if a redundant # ' source ' argument has been used . For example : # my _ field = serializer . CharField ( source = ' my _ field ' ) assert self . source != field_name , ( "It is redundant to specify `source='%s'` on field '%s' in " "serializer '%s', because it is the...
def get_type_data ( name ) : """Return dictionary representation of type . Can be used to initialize primordium . type . primitives . Type"""
name = name . upper ( ) if name in CALENDAR_TYPES : domain = 'Calendar Types' calendar_name = CALENDAR_TYPES [ name ] elif name in ANCIENT_CALENDAR_TYPES : domain = 'Ancient Calendar Types' calendar_name = ANCIENT_CALENDAR_TYPES [ name ] elif name in ALTERNATE_CALENDAR_TYPES : domain = 'Alternative ...
def parse_pdb_file ( self ) : """Runs the PDB parser ."""
self . pdb_parse_tree = { 'info' : { } , 'data' : { self . state : { } } } try : for line in self . pdb_lines : self . current_line = line record_name = line [ : 6 ] . strip ( ) if record_name in self . proc_functions : self . proc_functions [ record_name ] ( ) else : ...
def segment_meander_angles ( neurites , neurite_type = NeuriteType . all ) : '''Inter - segment opening angles in a section'''
return list ( chain . from_iterable ( map_sections ( sectionfunc . section_meander_angles , neurites , neurite_type ) ) )
def backward_transfer_pair ( backward_channel : NettingChannelState , payer_transfer : LockedTransferSignedState , pseudo_random_generator : random . Random , block_number : BlockNumber , ) -> Tuple [ Optional [ MediationPairState ] , List [ Event ] ] : """Sends a transfer backwards , allowing the previous hop to t...
transfer_pair = None events : List [ Event ] = list ( ) lock = payer_transfer . lock lock_timeout = BlockTimeout ( lock . expiration - block_number ) # Ensure the refund transfer ' s lock has a safe expiration , otherwise don ' t # do anything and wait for the received lock to expire . if is_channel_usable ( backward_c...
def points ( self , points ) : """set points without copying"""
if not isinstance ( points , np . ndarray ) : raise TypeError ( 'Points must be a numpy array' ) # get the unique coordinates along each axial direction x = np . unique ( points [ : , 0 ] ) y = np . unique ( points [ : , 1 ] ) z = np . unique ( points [ : , 2 ] ) nx , ny , nz = len ( x ) , len ( y ) , len ( z ) # T...
def createL2456Columns ( network , networkConfig ) : """Create a network consisting of multiple L2456 columns as described in the file comments above ."""
# Create each column numCorticalColumns = networkConfig [ "numCorticalColumns" ] for i in xrange ( numCorticalColumns ) : networkConfigCopy = copy . deepcopy ( networkConfig ) randomSeedBase = networkConfigCopy [ "randomSeedBase" ] networkConfigCopy [ "L2Params" ] [ "seed" ] = randomSeedBase + i network...
def load_extra_vi_page_navigation_bindings ( ) : """Key bindings , for scrolling up and down through pages . This are separate bindings , because GNU readline doesn ' t have them ."""
registry = ConditionalRegistry ( Registry ( ) , ViMode ( ) ) handle = registry . add_binding handle ( Keys . ControlF ) ( scroll_forward ) handle ( Keys . ControlB ) ( scroll_backward ) handle ( Keys . ControlD ) ( scroll_half_page_down ) handle ( Keys . ControlU ) ( scroll_half_page_up ) handle ( Keys . ControlE ) ( s...
def from_client_config ( cls , client_config , scopes , ** kwargs ) : """Creates a : class : ` requests _ oauthlib . OAuth2Session ` from client configuration loaded from a Google - format client secrets file . Args : client _ config ( Mapping [ str , Any ] ) : The client configuration in the Google ` clien...
if 'web' in client_config : client_type = 'web' elif 'installed' in client_config : client_type = 'installed' else : raise ValueError ( 'Client secrets must be for a web or installed app.' ) session , client_config = ( google_auth_oauthlib . helpers . session_from_client_config ( client_config , scopes , **...
def default_get_arg_names_from_class_name ( class_name ) : """Converts normal class names into normal arg names . Normal class names are assumed to be CamelCase with an optional leading underscore . Normal arg names are assumed to be lower _ with _ underscores . Args : class _ name : a class name , e . g . ...
parts = [ ] rest = class_name if rest . startswith ( '_' ) : rest = rest [ 1 : ] while True : m = re . match ( r'([A-Z][a-z]+)(.*)' , rest ) if m is None : break parts . append ( m . group ( 1 ) ) rest = m . group ( 2 ) if not parts : return [ ] return [ '_' . join ( part . lower ( ) for...
def _init_catalog ( self , proxy = None , runtime = None ) : """Initialize this session as an OsidCatalog based session ."""
self . _init_proxy_and_runtime ( proxy , runtime ) osid_name = self . _session_namespace . split ( '.' ) [ 0 ] try : config = self . _runtime . get_configuration ( ) parameter_id = Id ( 'parameter:' + osid_name + 'CatalogingProviderImpl@mongo' ) provider_impl = config . get_value_by_parameter ( parameter_id...
def check_extensions ( module_name , module_path ) : """This function checks for extensions to boto modules . It should be called in the _ _ init _ _ . py file of all boto modules . See : http : / / code . google . com / p / boto / wiki / ExtendModules for details ."""
option_name = '%s_extend' % module_name version = config . get ( 'Boto' , option_name , None ) if version : dirname = module_path [ 0 ] path = os . path . join ( dirname , version ) if os . path . isdir ( path ) : log . info ( 'extending module %s with: %s' % ( module_name , path ) ) module_...
def expand_in_basis ( self , basis_states = None , hermitian = False ) : """Write the operator as an expansion into all : class : ` KetBras < . KetBra > ` spanned by ` basis _ states ` . Args : basis _ states ( list or None ) : List of basis states ( : class : ` . State ` instances ) into which to expand ...
from qnet . algebra . core . state_algebra import KetBra # KetBra is imported locally to avoid circular imports if basis_states is None : basis_states = list ( self . space . basis_states ) else : basis_states = list ( basis_states ) diag_terms = [ ] terms = [ ] for i , ket_i in enumerate ( basis_states ) : ...
def save_site ( self , create = True ) : """Save environment settings in the directory that need to be saved even when creating only a new sub - site env ."""
self . _load_sites ( ) if create : self . sites . append ( self . site_name ) task . save_new_site ( self . site_name , self . sitedir , self . target , self . port , self . address , self . site_url , self . passwords )
def _load_stats ( self ) : """Load the webpack - stats file"""
for attempt in range ( 0 , 3 ) : try : with self . stats_file . open ( ) as f : return json . load ( f ) except ValueError : # If we failed to parse the JSON , it ' s possible that the # webpack process is writing to it concurrently and it ' s in a # bad state . Sleep and retry . ...
def image_import ( infile , force ) : """Import image anchore data from a JSON file ."""
ecode = 0 try : with open ( infile , 'r' ) as FH : savelist = json . loads ( FH . read ( ) ) except Exception as err : anchore_print_err ( "could not load input file: " + str ( err ) ) ecode = 1 if ecode == 0 : for record in savelist : try : imageId = record [ 'image' ] [ 'im...
def apply_T4 ( word ) : '''An agglutination diphthong that ends in / u , y / usually contains a syllable boundary when - C # or - CCV follow , e . g . , [ lau . ka . us ] , [ va . ka . ut . taa ] .'''
WORD = word . split ( '.' ) for i , v in enumerate ( WORD ) : # i % 2 ! = 0 prevents this rule from applying to first , third , etc . # syllables , which receive stress ( WSP ) if is_consonant ( v [ - 1 ] ) and i % 2 != 0 : if i + 1 == len ( WORD ) or is_consonant ( WORD [ i + 1 ] [ 0 ] ) : vv =...
def _create_main_config ( cls , overrides = None ) : """See comment block at top of ' rezconfig ' describing how the main config is assembled ."""
filepaths = [ ] filepaths . append ( get_module_root_config ( ) ) filepath = os . getenv ( "REZ_CONFIG_FILE" ) if filepath : filepaths . extend ( filepath . split ( os . pathsep ) ) filepath = os . path . expanduser ( "~/.rezconfig" ) filepaths . append ( filepath ) return Config ( filepaths , overrides )
def enable_precompute ( panel ) : """Schedule a precompute task for ` panel `"""
use_metis = panel [ 'data_source' ] [ 'source_type' ] == 'querybuilder' if use_metis : query = panel [ 'data_source' ] [ 'query' ] else : query = "u'''%s'''" % panel [ 'data_source' ] [ 'code' ] precompute = panel [ 'data_source' ] [ 'precompute' ] timeframe = panel [ 'data_source' ] [ 'timeframe' ] bucket_widt...
def get_objectives ( self ) : """Gets the objective list resulting from the search . return : ( osid . learning . ObjectiveList ) - the objective list raise : IllegalState - list already retrieved * compliance : mandatory - - This method must be implemented . *"""
if self . retrieved : raise errors . IllegalState ( 'List has already been retrieved.' ) self . retrieved = True return objects . ObjectiveList ( self . _results , runtime = self . _runtime )
def capture_update_records ( records ) : """Writes all updated configuration info to DynamoDB"""
for rec in records : data = cloudwatch . get_historical_base_info ( rec ) group = describe_group ( rec , cloudwatch . get_region ( rec ) ) if len ( group ) > 1 : raise Exception ( f'[X] Multiple groups found. Record: {rec}' ) if not group : LOG . warning ( f'[?] No group information foun...
def read_chip_sn ( self ) : '''Reading Chip S / N Note Bits [ MSB - LSB ] | [ 15 ] | [ 14-6 ] | [ 5-0] Content | reserved | wafer number | chip number'''
commands = [ ] commands . extend ( self . register . get_commands ( "ConfMode" ) ) self . register_utils . send_commands ( commands ) with self . readout ( fill_buffer = True , callback = None , errback = None ) : if self . register . fei4b : commands = [ ] self . register . set_global_register_valu...
def parse_content ( self , text ) : """get Usage section and set to ` raw _ content ` , ` formal _ content ` of no title and empty - line version"""
match = re . search ( self . usage_re_str . format ( self . usage_name ) , text , flags = ( re . DOTALL if self . case_sensitive else ( re . DOTALL | re . IGNORECASE ) ) ) if match is None : return dic = match . groupdict ( ) logger . debug ( dic ) self . raw_content = dic [ 'raw' ] if dic [ 'sep' ] in ( '\n' , '\r...
def fasta_verifier ( entries , ambiguous = False ) : """Raises error if invalid FASTA format detected Args : entries ( list ) : A list of FastaEntry instances ambiguous ( bool ) : Permit ambiguous bases , i . e . permit non - ACGTU bases Raises : FormatError : Error when FASTA format incorrect with descri...
if ambiguous : regex = r'^>.+{0}[ACGTURYKMSWBDHVNX]+{0}$' . format ( os . linesep ) else : regex = r'^>.+{0}[ACGTU]+{0}$' . format ( os . linesep ) delimiter = r'{0}' . format ( os . linesep ) for entry in entries : try : entry_verifier ( [ entry . write ( ) ] , regex , delimiter ) except Format...
def _extract_next_page_link ( self ) : """Try to get next page link ."""
# HEADS UP : we do not abort if next _ page _ link is already set : # we try to find next ( eg . find 3 if already at page 2 ) . for pattern in self . config . next_page_link : items = self . parsed_tree . xpath ( pattern ) if not items : continue if len ( items ) == 1 : item = items [ 0 ] ...
def _generate_report_all ( self ) : '''Generate report for all subfolders contained by self . folder _ id .'''
assert self . workbook is not None count = 0 # Do all subfolders for sid in self . folders . subfolders ( self . folder_id , self . user ) : count += 1 self . _generate_for_subfolder ( sid ) if count == 0 : print ( "I: empty workbook created: no subfolders found" )
def replace_vobject ( self , uid , ical , filename = None ) : """Update the Remind command with the uid in the file with the new iCalendar"""
if not filename : filename = self . _filename elif filename not in self . _reminders : return uid = uid . split ( '@' ) [ 0 ] with self . _lock : rem = open ( filename ) . readlines ( ) for ( index , line ) in enumerate ( rem ) : if uid == md5 ( line [ : - 1 ] . encode ( 'utf-8' ) ) . hexdigest ...
def allow ( self , channel , message ) : """Allow plugins to filter content ."""
return all ( filter ( channel , message ) for filter in _load_filters ( ) )
def _use ( cls , ec ) : """underly implement of use"""
# class ConnectModel ( cls ) : # pass ConnectModel = type ( cls . __name__ , ( cls , ) , { } ) ConnectModel . tablename = cls . tablename ConnectModel . _base_class = cls if isinstance ( ec , ( str , unicode ) ) : ConnectModel . _engine_name = ec elif isinstance ( ec , Session ) : ConnectModel . _engine_name = ...
def nfc ( ctx , enable , disable , enable_all , disable_all , list , lock_code , force ) : """Enable or disable applications over NFC ."""
if not ( list or enable_all or enable or disable_all or disable ) : ctx . fail ( 'No configuration options chosen.' ) if enable_all : enable = APPLICATION . __members__ . keys ( ) if disable_all : disable = APPLICATION . __members__ . keys ( ) _ensure_not_invalid_options ( ctx , enable , disable ) dev = ctx...
def reset ( self , ms = 0 , halt = True ) : """Resets the target . This method resets the target , and by default toggles the RESET and TRST pins . Args : self ( JLink ) : the ` ` JLink ` ` instance ms ( int ) : Amount of milliseconds to delay after reset ( default : 0) halt ( bool ) : if the CPU should...
self . _dll . JLINKARM_SetResetDelay ( ms ) res = self . _dll . JLINKARM_Reset ( ) if res < 0 : raise errors . JLinkException ( res ) elif not halt : self . _dll . JLINKARM_Go ( ) return res
def category_changed_cb ( self , selection , model ) : """enables and disables action buttons depending on selected item"""
( model , iter ) = selection . get_selected ( ) id = 0 if iter is None : self . activity_store . clear ( ) else : self . prev_selected_activity = None id = model [ iter ] [ 0 ] self . activity_store . load ( model [ iter ] [ 0 ] ) # start with nothing self . get_widget ( 'activity_edit' ) . set_sensitiv...
def offset ( self ) : """Return offset to series data in file , if any ."""
if not self . _pages : return None pos = 0 for page in self . _pages : if page is None : return None if not page . is_final : return None if not pos : pos = page . is_contiguous [ 0 ] + page . is_contiguous [ 1 ] continue if pos != page . is_contiguous [ 0 ] : ...
def _build_tags ( self , tag_names : List [ str ] ) -> dict : """Build a list of tag objects ."""
tags = { } for tag_name in tag_names : tag_obj = self . tag ( tag_name ) if tag_obj is None : LOG . debug ( f"create new tag: {tag_name}" ) tag_obj = self . new_tag ( tag_name ) tags [ tag_name ] = tag_obj return tags
def hard_path ( path , prefix_dir ) : """Returns an absolute path to either the relative or absolute file ."""
relative = abspath ( "%s/%s" % ( prefix_dir , path ) ) a_path = abspath ( path ) if os . path . exists ( relative ) : LOG . debug ( "using relative path %s (%s)" , relative , path ) return relative LOG . debug ( "using absolute path %s" , a_path ) return a_path
def _process_rules ( self , rules : dict , system : System ) : """process a set of rules for a target"""
self . _source = None # reset the template source if not self . _shall_proceed ( rules ) : return self . context . update ( rules . get ( 'context' , { } ) ) self . path = rules . get ( 'path' , '' ) self . source = rules . get ( 'source' , None ) self . _process_rule ( rules . get ( 'system' , None ) , { 'system' ...
def set_webhook ( url , certificate = None , max_connections = None , allowed_updates = None , ** kwargs ) : """Use this method to specify a url and receive incoming updates via an outgoing webhook . Whenever there is an update for the bot , we will send an HTTPS POST request to the specified url , containing a ...
# optional args params = _clean_params ( url = url , certificate = certificate , max_connections = max_connections , allowed_updates = allowed_updates ) return TelegramBotRPCRequest ( 'setWebhook' , params = params , on_result = lambda result : result , ** kwargs )
def offset ( self , offset ) : """Offset the date range by the given amount of periods . This differs from : meth : ` ~ spans . types . OffsetableRangeMixin . offset ` on : class : ` spans . types . daterange ` by not accepting a ` ` timedelta ` ` object . Instead it expects an integer to adjust the typed dat...
span = self if offset > 0 : for i in iter_range ( offset ) : span = span . next_period ( ) elif offset < 0 : for i in iter_range ( - offset ) : span = span . prev_period ( ) return span
def reverse_delete_ipv6 ( self , subid , ipaddr , params = None ) : '''/ v1 / server / reverse _ delete _ ipv6 POST - account Remove a reverse DNS entry for an IPv6 address of a virtual machine . Upon success , DNS changes may take 6-12 hours to become active . Link : https : / / www . vultr . com / api / #...
params = update_params ( params , { 'SUBID' : subid , 'ip' : ipaddr } ) return self . request ( '/v1/server/reverse_delete_ipv6' , params , 'POST' )
def get_data ( self , compact = True ) : '''Returns data representing current state of the form . While Form . raw _ data may contain alien fields and invalid data , this method returns only valid fields that belong to this form only . It ' s designed to pass somewhere current state of the form ( as query str...
data = MultiDict ( ) for field in self . fields : raw_value = field . from_python ( self . python_data [ field . name ] ) field . set_raw_value ( data , raw_value ) if compact : data = MultiDict ( [ ( k , v ) for k , v in data . items ( ) if v ] ) return data
def key ( self , id_num ) : """Get the specified deploy key . : param int id _ num : ( required ) , id of the key : returns : : class : ` Key < github3 . users . Key > ` if successful , else None"""
json = None if int ( id_num ) > 0 : url = self . _build_url ( 'keys' , str ( id_num ) , base_url = self . _api ) json = self . _json ( self . _get ( url ) , 200 ) return Key ( json , self ) if json else None
def MatchBuildContext ( self , target_os , target_arch , target_package , context = None ) : """Return true if target _ platforms matches the supplied parameters . Used by buildanddeploy to determine what clients need to be built . Args : target _ os : which os we are building for in this run ( linux , window...
for spec in self . Get ( "ClientBuilder.target_platforms" , context = context ) : spec_os , arch , package_name = spec . split ( "_" ) if ( spec_os == target_os and arch == target_arch and package_name == target_package ) : return True return False
def get_vec_tb ( self ) : """Returns vector from top to bottom"""
return self . height * self . sin_a ( ) , self . height * self . cos_a ( )
def AppendIndexDictionaryToFile ( uniqueWords , ndxFile , ipFile , useShortFileName = 'Y' ) : """Save the list of unique words to the master list"""
if useShortFileName == 'Y' : f = os . path . basename ( ipFile ) else : f = ipFile with open ( ndxFile , "a" , encoding = 'utf-8' , errors = 'replace' ) as ndx : word_keys = uniqueWords . keys ( ) # uniqueWords . sort ( ) for word in sorted ( word_keys ) : if word != '' : line_nu...
def run_ ( self ) : """DEPRECATED"""
all_records = [ ] for k in range ( self . num_classes ) : simulated_records = self . alf_params [ k + 1 ] . run ( ) names = [ 'class{0}_{1:0>{2}}' . format ( k + 1 , i , len ( str ( self . class_list [ k ] ) ) ) for i in range ( 1 , len ( simulated_records ) + 1 ) ] for ( rec , name ) in zip ( simulated_rec...
def isdicom ( fn ) : '''True if the fn points to a DICOM image'''
fn = str ( fn ) if fn . endswith ( '.dcm' ) : return True # Dicom signature from the dicom spec . with open ( fn , 'rb' ) as fh : fh . seek ( 0x80 ) return fh . read ( 4 ) == b'DICM'
def intf_up ( self , interface ) : '''Can be called when an interface is put in service . FIXME : not currently used ; more needs to be done to correctly put a new intf into service .'''
if interface . name not in self . _devinfo : self . _devinfo [ interface . name ] = interface if self . _devupdown_callback : self . _devupdown_callback ( interface , 'up' ) else : raise ValueError ( "Interface already registered" )
def stats ( self , request ) : '''Live stats for the server . Try sending lots of requests'''
# scheme = ' wss ' if request . is _ secure else ' ws ' # host = request . get ( ' HTTP _ HOST ' ) # address = ' % s : / / % s / stats ' % ( scheme , host ) doc = HtmlDocument ( title = 'Live server stats' , media_path = '/assets/' ) # docs . head . scripts return doc . http_response ( request )
def get_previous_request ( rid ) : """Return the last ceph broker request sent on a given relation @ param rid : Relation id to query for request"""
request = None broker_req = relation_get ( attribute = 'broker_req' , rid = rid , unit = local_unit ( ) ) if broker_req : request_data = json . loads ( broker_req ) request = CephBrokerRq ( api_version = request_data [ 'api-version' ] , request_id = request_data [ 'request-id' ] ) request . set_ops ( reques...
def parse_methodcall ( self , tup_tree ) : """< ! ELEMENT METHODCALL ( ( LOCALCLASSPATH | LOCALINSTANCEPATH ) , PARAMVALUE * ) > < ! ATTLIST METHODCALL % CIMName ; >"""
self . check_node ( tup_tree , 'METHODCALL' , ( 'NAME' , ) , ( ) , ( 'LOCALCLASSPATH' , 'LOCALINSTANCEPATH' , 'PARAMVALUE' ) ) path = self . list_of_matching ( tup_tree , ( 'LOCALCLASSPATH' , 'LOCALINSTANCEPATH' ) ) if not path : raise CIMXMLParseError ( _format ( "Element {0!A} missing a required child element " "...
def ListHunts ( context = None ) : """List all GRR hunts ."""
items = context . SendIteratorRequest ( "ListHunts" , hunt_pb2 . ApiListHuntsArgs ( ) ) return utils . MapItemsIterator ( lambda data : Hunt ( data = data , context = context ) , items )
def check_assumptions ( self , training_df , advice = True , show_plots = False , p_value_threshold = 0.01 , plot_n_bootstraps = 10 ) : """Use this function to test the proportional hazards assumption . See usage example at https : / / lifelines . readthedocs . io / en / latest / jupyter _ notebooks / Proportiona...
if not training_df . index . is_unique : raise IndexError ( "`training_df` index should be unique for this exercise. Please make it unique or use `.reset_index(drop=True)` to force a unique index" ) residuals = self . compute_residuals ( training_df , kind = "scaled_schoenfeld" ) test_results = proportional_hazard_...
def list_vms ( search = None , verbose = False ) : '''List all vms search : string filter vms , see the execution module verbose : boolean print additional information about the vm CLI Example : . . code - block : : bash salt - run vmadm . list salt - run vmadm . list search = ' type = KVM ' salt ...
ret = OrderedDict ( ) if verbose else [ ] client = salt . client . get_local_client ( __opts__ [ 'conf_file' ] ) try : vmadm_args = { } vmadm_args [ 'order' ] = 'uuid,alias,hostname,state,type,cpu_cap,vcpus,ram' if search : vmadm_args [ 'search' ] = search for cn in client . cmd_iter ( 'G@virtua...
def get_permissions ( self ) : """Soyut role ait Permission nesnelerini bulur ve code değerlerini döner . Returns : list : Permission code değerleri"""
return [ p . permission . code for p in self . Permissions if p . permission . code ]
def _set_retcode ( ret , highstate = None ) : '''Set the return code based on the data back from the state system'''
# Set default retcode to 0 __context__ [ 'retcode' ] = salt . defaults . exitcodes . EX_OK if isinstance ( ret , list ) : __context__ [ 'retcode' ] = salt . defaults . exitcodes . EX_STATE_COMPILER_ERROR return if not __utils__ [ 'state.check_result' ] ( ret , highstate = highstate ) : __context__ [ 'retcod...
def show ( self , ax : plt . Axes = None , figsize : tuple = ( 3 , 3 ) , title : Optional [ str ] = None , hide_axis : bool = True , cmap : str = None , y : Any = None , ** kwargs ) : "Show image on ` ax ` with ` title ` , using ` cmap ` if single - channel , overlaid with optional ` y `"
cmap = ifnone ( cmap , defaults . cmap ) ax = show_image ( self , ax = ax , hide_axis = hide_axis , cmap = cmap , figsize = figsize ) if y is not None : y . show ( ax = ax , ** kwargs ) if title is not None : ax . set_title ( title )
def match ( self , item ) : """Return True if filter matches item ."""
if getattr ( item , self . _name ) is None : # Never match " N / A " items , except when " - 0 " was specified return False if self . _value else self . _cmp ( - 1 , 0 ) else : return super ( DurationFilter , self ) . match ( item )
def convert ( kml_path , output_dir , separate_folders = False , style_type = None , style_filename = 'style.json' ) : """Given a path to a KML file , convert it to one or several GeoJSON FeatureCollection files and save the result ( s ) to the given output directory . If not ` ` separate _ folders ` ` ( the defa...
# Create absolute paths kml_path = Path ( kml_path ) . resolve ( ) output_dir = Path ( output_dir ) if not output_dir . exists ( ) : output_dir . mkdir ( ) output_dir = output_dir . resolve ( ) # Parse KML with kml_path . open ( encoding = 'utf-8' , errors = 'ignore' ) as src : kml_str = src . read ( ) root = m...
def listdir ( self , match = None ) : """D . listdir ( ) - > List of items in this directory . Use : meth : ` files ` or : meth : ` dirs ` instead if you want a listing of just files or just subdirectories . The elements of the list are Path objects . With the optional ` match ` argument , a callable , on...
match = matchers . load ( match ) return list ( filter ( match , ( self / child for child in os . listdir ( self ) ) ) )
def from_mat_file ( cls , matfilename ) : """Load gyro data from . mat file The MAT file should contain the following two arrays gyro : ( 3 , N ) float ndarray The angular velocity measurements . timestamps : ( N , ) float ndarray Timestamps of the measurements . Parameters matfilename : string Name...
M = scipy . io . loadmat ( matfilename ) instance = cls ( ) instance . gyro_data = M [ 'gyro' ] instance . timestamps = M [ 'timestamps' ] return instance
def _to_rule ( self , lark_rule ) : """Converts a lark rule , ( lhs , rhs , callback , options ) , to a Rule ."""
assert isinstance ( lark_rule . origin , NT ) assert all ( isinstance ( x , Symbol ) for x in lark_rule . expansion ) return Rule ( lark_rule . origin , lark_rule . expansion , weight = lark_rule . options . priority if lark_rule . options and lark_rule . options . priority else 0 , alias = lark_rule )
def handle ( self , targetdir , app = None , ** options ) : """command execution"""
translation . activate ( settings . LANGUAGE_CODE ) if app : unpack = app . split ( '.' ) if len ( unpack ) == 2 : models = [ get_model ( unpack [ 0 ] , unpack [ 1 ] ) ] elif len ( unpack ) == 1 : models = get_models ( get_app ( unpack [ 0 ] ) ) else : models = get_models ( ) messagemake...
def sortino_ratio ( rets , rfr_ann = 0 , mar = 0 , full = 0 , expanding = 0 ) : """Compute the sortino ratio as ( Ann Rets - Risk Free Rate ) / Downside Deviation Ann : param rets : period return series : param rfr _ ann : annualized risk free rate : param mar : minimum acceptable rate of return ( MAR ) : p...
annrets = returns_annualized ( rets , expanding = expanding ) - rfr_ann return annrets / downside_deviation ( rets , mar = mar , expanding = expanding , full = full , ann = 1 )
def locked ( self , target ) : """Returns a context manager for a lock on a datastore , where * target * is the name of the configuration datastore to lock , e . g . : : with m . locked ( " running " ) : # do your stuff . . . instead of : : m . lock ( " running " ) try : # do your stuff finally : ...
return operations . LockContext ( self . _session , self . _device_handler , target )
def _m ( self , word , j ) : """m ( ) measures the number of consonant sequences between k0 and j . if c is a consonant sequence and v a vowel sequence , and < . . > indicates arbitrary presence , < c > < v > gives 0 < c > vc < v > gives 1 < c > vcvc < v > gives 2 < c > vcvcvc < v > gives 3"""
n = 0 i = 0 while True : if i > j : return n if not self . _cons ( word , i ) : break i = i + 1 i = i + 1 while True : while True : if i > j : return n if self . _cons ( word , i ) : break i = i + 1 i = i + 1 n = n + 1 while Tru...
def async_call ( self , * args , ** kwargs ) : """Calls a redis command , waits for the reply and call a callback . Following options are available ( not part of the redis command itself ) : - callback Function called ( with the result as argument ) when the result is available . If not set , the reply is s...
def after_autoconnect_callback ( future ) : if self . is_connected ( ) : self . _call ( * args , ** kwargs ) else : # FIXME pass if 'callback' not in kwargs : kwargs [ 'callback' ] = discard_reply_cb if not self . is_connected ( ) : if self . autoconnect : connect_future = self ....
def originate ( self , data = '' , syn = False , ack = False , fin = False , rst = False ) : """Create a packet , enqueue it to be sent , and return it ."""
if self . _ackTimer is not None : self . _ackTimer . cancel ( ) self . _ackTimer = None if syn : # We really should be randomizing the ISN but until we finish the # implementations of the various bits of wraparound logic that were # started with relativeSequence assert self . nextSendSeqNum == 0 , ( "NSSN =...
def run ( self , quil_program , classical_addresses : List [ int ] = None , trials = 1 ) : """Run a Quil program multiple times , accumulating the values deposited in a list of classical addresses . : param Program quil _ program : A Quil program . : param classical _ addresses : The classical memory to retri...
if classical_addresses is None : caddresses = get_classical_addresses_from_program ( quil_program ) else : caddresses = { 'ro' : classical_addresses } buffers = self . _connection . _qvm_run ( quil_program , caddresses , trials , self . measurement_noise , self . gate_noise , self . random_seed ) if len ( buffe...
def gpg_unstash_key ( appname , key_id , config_dir = None , gpghome = None ) : """Remove a public key locally from our local app keyring Return True on success Return False on error"""
assert is_valid_appname ( appname ) if gpghome is None : config_dir = get_config_dir ( config_dir ) keydir = get_gpg_home ( appname , config_dir = config_dir ) else : keydir = gpghome gpg = gnupg . GPG ( homedir = keydir ) res = gpg . delete_keys ( [ key_id ] ) if res . status == 'Must delete secret key fir...
def ekopn ( fname , ifname , ncomch ) : """Open a new E - kernel file and prepare the file for writing . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / ekopn _ c . html : param fname : Name of EK file . : type fname : str : param ifname : Internal file name . : type ifname...
fname = stypes . stringToCharP ( fname ) ifname = stypes . stringToCharP ( ifname ) ncomch = ctypes . c_int ( ncomch ) handle = ctypes . c_int ( ) libspice . ekopn_c ( fname , ifname , ncomch , ctypes . byref ( handle ) ) return handle . value
def to_datetime ( value ) : """Converts a string to a datetime ."""
if value is None : return None if isinstance ( value , six . integer_types ) : return parser . parse ( value ) return parser . isoparse ( value )
def detailed_log_handler ( self , handler ) : """Setter for the detailed log handler function . Args : self ( JLink ) : the ` ` JLink ` ` instance Returns : ` ` None ` `"""
if not self . opened ( ) : handler = handler or util . noop self . _detailed_log_handler = enums . JLinkFunctions . LOG_PROTOTYPE ( handler ) self . _dll . JLINKARM_EnableLogCom ( self . _detailed_log_handler )
def _kw ( keywords ) : """Turn list of keywords into dictionary ."""
r = { } for k , v in keywords : r [ k ] = v return r
def decode_json_body ( ) : """Decode ` ` bottle . request . body ` ` to JSON . Returns : obj : Structure decoded by ` ` json . loads ( ) ` ` . Raises : HTTPError : 400 in case the data was malformed ."""
raw_data = request . body . read ( ) try : return json . loads ( raw_data ) except ValueError as e : raise HTTPError ( 400 , e . __str__ ( ) )
def workers ( cmd ) : """start / stop / restart the workers , or return their status"""
if config . dbserver . multi_user and getpass . getuser ( ) != 'openquake' : sys . exit ( 'oq workers only works in single user mode' ) master = workerpool . WorkerMaster ( config . dbserver . host , ** config . zworkers ) print ( getattr ( master , cmd ) ( ) )
def items ( self ) : """An iterable of all ( anchor - id , Anchor ) mappings in the repository ."""
for anchor_id in self : try : anchor = self [ anchor_id ] except KeyError : assert False , 'Trying to load from missing file or something' yield ( anchor_id , anchor )
def set_max_threads ( self , max_threads ) : """Set the maximum number of concurrent threads . : type max _ threads : int : param max _ threads : The number of threads ."""
if max_threads is None : raise TypeError ( 'max_threads must not be None.' ) self . _check_if_ready ( ) self . collection . set_max_working ( max_threads )
def restart_instance ( self , instance ) : """Restarts a single instance . : param str instance : A Yamcs instance name ."""
params = { 'state' : 'restarted' } url = '/instances/{}' . format ( instance ) self . patch_proto ( url , params = params )
def fetch_user ( query ) : """Get user by ` ` pk ` ` or ` ` username ` ` . Raise error if it doesn ' t exist ."""
user_filter = { 'pk' : query } if query . isdigit ( ) else { 'username' : query } user_model = get_user_model ( ) try : return user_model . objects . get ( ** user_filter ) except user_model . DoesNotExist : raise exceptions . ParseError ( "Unknown user: {}" . format ( query ) )
def release ( self ) : """Get rid of the lock by deleting the lockfile . When working in a ` with ` statement , this gets automatically called at the end ."""
if self . is_locked : os . close ( self . fd ) os . unlink ( self . lockfile ) self . is_locked = False
def push ( self , * items ) : """Prepends the list with @ items - > # int length of list after operation"""
if self . serialized : items = list ( map ( self . _dumps , items ) ) return self . _client . lpush ( self . key_prefix , * items )
def ssl_server_options ( ) : """ssl options for tornado https server these options are defined in each application ' s default . conf file if left empty , use the self generated keys and certificates included in this package . this function is backward compatible with python version lower than 2.7.9 where...
cafile = options . ssl_ca_cert keyfile = options . ssl_key certfile = options . ssl_cert verify_mode = options . ssl_cert_reqs try : context = ssl . create_default_context ( purpose = ssl . Purpose . CLIENT_AUTH , cafile = cafile ) context . load_cert_chain ( certfile = certfile , keyfile = keyfile ) contex...