signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def find ( self , resource , req , sub_resource_lookup ) : """Find documents for resource ."""
args = getattr ( req , 'args' , request . args if request else { } ) or { } source_config = config . SOURCES [ resource ] if args . get ( 'source' ) : query = json . loads ( args . get ( 'source' ) ) if 'filtered' not in query . get ( 'query' , { } ) : _query = query . get ( 'query' ) query [ 'q...
def _start_redis_instance ( executable , modules , port = None , redis_max_clients = None , num_retries = 20 , stdout_file = None , stderr_file = None , password = None , redis_max_memory = None ) : """Start a single Redis server . Notes : If " port " is not None , then we will only use this port and try only...
assert os . path . isfile ( executable ) for module in modules : assert os . path . isfile ( module ) counter = 0 if port is not None : # If a port is specified , then try only once to connect . # This ensures that we will use the given port . num_retries = 1 else : port = new_port ( ) load_module_args = [ ...
def convert_to_int ( x : Any , default : int = None ) -> int : """Transforms its input into an integer , or returns ` ` default ` ` ."""
try : return int ( x ) except ( TypeError , ValueError ) : return default
def run_script_with_context ( script_path , cwd , context ) : """Execute a script after rendering it with Jinja . : param script _ path : Absolute path to the script to run . : param cwd : The directory to run the script from . : param context : Cookiecutter project template context ."""
_ , extension = os . path . splitext ( script_path ) contents = io . open ( script_path , 'r' , encoding = 'utf-8' ) . read ( ) with tempfile . NamedTemporaryFile ( delete = False , mode = 'wb' , suffix = extension ) as temp : env = StrictEnvironment ( context = context , keep_trailing_newline = True , ) templa...
def rasterize ( self , dest_resolution , * , polygonize_width = 0 , crs = WEB_MERCATOR_CRS , fill_value = None , bounds = None , dtype = None , ** polygonize_kwargs ) : """Binarize a FeatureCollection and produce a raster with the target resolution . Parameters dest _ resolution : float Resolution in units of...
# Avoid circular imports from telluric . georaster import merge_all , MergeStrategy from telluric . rasterization import rasterize , NODATA_DEPRECATION_WARNING # Compute the size in real units and polygonize the features if not isinstance ( polygonize_width , int ) : raise TypeError ( "The width in pixels must be a...
def put_coord_inside ( lattice , cart_coordinate ) : """converts a cartesian coordinate such that it is inside the unit cell ."""
fc = lattice . get_fractional_coords ( cart_coordinate ) return lattice . get_cartesian_coords ( [ c - np . floor ( c ) for c in fc ] )
def xfr ( where , zone , rdtype = dns . rdatatype . AXFR , rdclass = dns . rdataclass . IN , timeout = None , port = 53 , keyring = None , keyname = None , relativize = True , af = None , lifetime = None , source = None , source_port = 0 , serial = 0 , use_udp = False , keyalgorithm = dns . tsig . default_algorithm ) :...
if isinstance ( zone , ( str , unicode ) ) : zone = dns . name . from_text ( zone ) if isinstance ( rdtype , ( str , unicode ) ) : rdtype = dns . rdatatype . from_text ( rdtype ) q = dns . message . make_query ( zone , rdtype , rdclass ) if rdtype == dns . rdatatype . IXFR : rrset = dns . rrset . from_text ...
def create_n_connect ( self , socket_type , address : str , bind = False , on_error = 'log' , socket_name = '' ) : """Creates and connects or binds the sockets on _ error : ' log ' : will log error ' exit ' : will exit the program socket _ name : used for troubleshooting / logging"""
self . logger . debug ( 'create and connect: %s %s %s' , socket_type , socket_name , address ) socket = self . context . socket ( socket_type ) if self . using_auth : self . _create_using_auth ( socket , address , bind , on_error , socket_name ) else : self . _create_no_auth ( socket , address , bind , on_error...
def inserted ( self , word , hyphen = '-' ) : """Returns the word as a string with all the possible hyphens inserted . E . g . for the dutch word ' lettergrepen ' this method returns the string ' let - ter - gre - pen ' . The hyphen string to use can be given as the second parameter , that defaults to ' - ' ....
l = list ( word ) for p in reversed ( self . positions ( word ) ) : if p . data : # get the nonstandard hyphenation data change , index , cut = p . data if word . isupper ( ) : change = change . upper ( ) l [ p + index : p + index + cut ] = change . replace ( '=' , hyphen ) e...
def slice_repr ( slice_instance ) : """Turn things like ` slice ( None , 2 , - 1 ) ` into ` : 2 : - 1 ` ."""
if not isinstance ( slice_instance , slice ) : raise TypeError ( 'Unhandled type {}' . format ( type ( slice_instance ) ) ) start = slice_instance . start or '' stop = slice_instance . stop or '' step = slice_instance . step or '' msg = '{}:' . format ( start ) if stop : msg += '{}' . format ( stop ) if ste...
def db ( self , request ) : '''Single Database Query'''
with self . mapper . begin ( ) as session : world = session . query ( World ) . get ( randint ( 1 , 10000 ) ) return Json ( self . get_json ( world ) ) . http_response ( request )
def state_by_state2state_by_node ( tpm ) : """Convert a state - by - state TPM to a state - by - node TPM . . . danger : : Many nondeterministic state - by - state TPMs can be represented by a single a state - by - state TPM . However , the mapping can be made to be one - to - one if we assume the state - b...
# Cast to np . array . tpm = np . array ( tpm ) # Get the number of states from the length of one side of the TPM . S = tpm . shape [ - 1 ] # Get the number of nodes from the number of states . N = int ( log2 ( S ) ) # Initialize the new state - by node TPM . sbn_tpm = np . zeros ( ( [ 2 ] * N + [ N ] ) ) # Map indices...
def sort_dict_values ( input_dict ) : """Sorts the values ( which are lists ) within a dictionary . Examples : sort _ dict _ values ( { ' n1 ' : [ 2 , 3 , 1 ] , ' n2 ' : [ 5 , 1 , 2 ] , ' n3 ' : [ 3 , 2 , 4 ] } ) Returns : { ' n1 ' : [ 1 , 2 , 3 ] , ' n2 ' : [ 1 , 2 , 5 ] , ' n3 ' : [ 2 , 3 , 4 ] } sort _...
dict_with_sorted_values = { key : sorted ( values ) for ( key , values ) in input_dict . items ( ) } return dict_with_sorted_values
def get_assets_by_genus_type ( self , asset_genus_type = None ) : """Gets an ` ` AssetList ` ` corresponding to the given asset genus ` ` Type ` ` which does not include assets of types derived from the specified ` ` Type ` ` . In plenary mode , the returned list contains all known assets or an error results ...
return AssetList ( self . _provider_session . get_assets_by_genus_type ( asset_genus_type ) , self . _config_map )
def getsz ( self , addr ) : """Get zero - terminated bytes string from given address . Will raise NotEnoughDataError exception if a hole is encountered before a 0."""
i = 0 try : while True : if self . _buf [ addr + i ] == 0 : break i += 1 except KeyError : raise NotEnoughDataError ( msg = ( 'Bad access at 0x%X: ' 'not enough data to read zero-terminated string' ) % addr ) return self . gets ( addr , i )
def allowed_variable_usage ( schema : GraphQLSchema , var_type : GraphQLType , var_default_value : Optional [ ValueNode ] , location_type : GraphQLType , location_default_value : Any , ) -> bool : """Check for allowed variable usage . Returns True if the variable is allowed in the location it was found , which in...
if is_non_null_type ( location_type ) and not is_non_null_type ( var_type ) : has_non_null_variable_default_value = var_default_value and not isinstance ( var_default_value , NullValueNode ) has_location_default_value = location_default_value is not INVALID if not has_non_null_variable_default_value and not...
def update_frame ( self , key , ranges = None ) : """Update the internal state of the Plot to represent the given key tuple ( where integers represent frames ) . Returns this state ."""
ranges = self . compute_ranges ( self . layout , key , ranges ) for r , c in self . coords : subplot = self . subplots . get ( ( r , c ) , None ) if subplot is not None : subplot . update_frame ( key , ranges ) title = self . _get_title_div ( key ) if title : self . handles [ 'title' ] = title
def summary ( self , campaign_id = None ) : """Returns the campaign summary"""
resource_cls = CampaignSummary single_resource = False if not campaign_id : resource_cls = CampaignSummaries single_resource = True return super ( API , self ) . get ( resource_id = campaign_id , resource_action = 'summary' , resource_cls = resource_cls , single_resource = single_resource )
def describe_log_stream ( awsclient , log_group_name , log_stream_name ) : """Get info on the specified log stream : param log _ group _ name : log group name : param log _ stream _ name : log stream : return :"""
client_logs = awsclient . get_client ( 'logs' ) response = client_logs . describe_log_streams ( logGroupName = log_group_name , logStreamNamePrefix = log_stream_name , limit = 1 ) if response [ 'logStreams' ] : return response [ 'logStreams' ] [ 0 ] else : return
def do_conneg ( accept , supported ) : """Parse accept header and look for preferred type in supported list . Arguments : accept - HTTP Accept header supported - list of MIME type supported by the server Returns : supported MIME type with highest q value in request , else None . FIXME - Should replace t...
for result in parse_accept_header ( accept ) : mime_type = result [ 0 ] if ( mime_type in supported ) : return mime_type return None
def dedup ( args ) : """% prog dedup assembly . assembly . blast assembly . fasta Remove duplicate contigs within assembly ."""
from jcvi . formats . blast import BlastLine p = OptionParser ( dedup . __doc__ ) p . set_align ( pctid = 0 , pctcov = 98 ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) blastfile , fastafile = args cov = opts . pctcov / 100. sizes = Sizes ( fastafile ) . mapping...
def _validate ( self ) : """Assure this is a valid VLAN header instance ."""
if self . tpid . value not in ( EtherType . VLAN , EtherType . VLAN_QINQ ) : raise UnpackException return
def get_video_transcript_url ( video_id , language_code ) : """Returns course video transcript url or None if no transcript Arguments : video _ id : it can be an edx _ video _ id or an external _ id extracted from external sources in a video component . language _ code : language code of a video transcript"""
video_transcript = VideoTranscript . get_or_none ( video_id , language_code ) if video_transcript : return video_transcript . url ( )
def unblockall ( self ) : '''Remove all blocks from the queue and all sub - queues'''
for q in self . queues . values ( ) : q . unblockall ( ) self . blockEvents . clear ( )
def read_array ( self , infile , var_name ) : """Directly return a numpy array for a given variable name"""
file_handle = self . read_cdf ( infile ) try : # return the data array return file_handle . variables [ var_name ] [ : ] except KeyError : print ( "Cannot find variable: {0}" . format ( var_name ) ) raise KeyError
def _aix_cpudata ( ) : '''Return CPU information for AIX systems'''
# Provides : # cpuarch # num _ cpus # cpu _ model # cpu _ flags grains = { } cmd = salt . utils . path . which ( 'prtconf' ) if cmd : data = __salt__ [ 'cmd.run' ] ( '{0}' . format ( cmd ) ) + os . linesep for dest , regstring in ( ( 'cpuarch' , r'(?im)^\s*Processor\s+Type:\s+(\S+)' ) , ( 'cpu_flags' , r'(?im)^...
def get_interface_detail_output_interface_ifHCInBroadcastPkts ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_interface_detail = ET . Element ( "get_interface_detail" ) config = get_interface_detail output = ET . SubElement ( get_interface_detail , "output" ) interface = ET . SubElement ( output , "interface" ) interface_type_key = ET . SubElement ( interface , "interface-type" ) interfac...
def get_publisher ( self , publisher_id ) : """GetPublisher . Get a specific service hooks publisher . : param str publisher _ id : ID for a publisher . : rtype : : class : ` < Publisher > < azure . devops . v5_0 . service _ hooks . models . Publisher > `"""
route_values = { } if publisher_id is not None : route_values [ 'publisherId' ] = self . _serialize . url ( 'publisher_id' , publisher_id , 'str' ) response = self . _send ( http_method = 'GET' , location_id = '1e83a210-5b53-43bc-90f0-d476a4e5d731' , version = '5.0' , route_values = route_values ) return self . _de...
def retrain ( self , name , ids , labels ) : """Reentrenar parcialmente un clasificador SVM . Args : name ( str ) : Nombre para el clasidicador . ids ( list ) : Se espera una lista de N ids de textos ya almacenados en el TextClassifier . labels ( list ) : Se espera una lista de N etiquetas . Una por cada ...
if not all ( np . in1d ( ids , self . ids ) ) : raise ValueError ( "Hay ids de textos que no se encuentran \ almacenados." ) try : classifier = getattr ( self , name ) except AttributeError : raise AttributeError ( "No hay ningun clasificador con ese nombre." ) indices = np . i...
def send_message ( self , app_mxit_id , target_user_ids , message = '' , contains_markup = True , spool = None , spool_timeout = None , links = None , scope = 'message/send' ) : """Send a message ( from a Mxit app ) to a list of Mxit users"""
data = { 'From' : app_mxit_id , 'To' : "," . join ( target_user_ids ) , 'Body' : message , 'ContainsMarkup' : contains_markup } if spool : data [ 'Spool' ] = spool if spool_timeout : data [ 'SpoolTimeOut' ] = spool_timeout if links : data [ 'Links' ] = links return _post ( token = self . oauth . get_app_tok...
def connect ( self , topic , cb ) : """Registers a callback for an event topic . Valid topics and their associated values : started - utterance : name = < str > started - word : name = < str > , location = < int > , length = < int > finished - utterance : name = < str > , completed = < bool > error : name...
arr = self . _connects . setdefault ( topic , [ ] ) arr . append ( cb ) return { 'topic' : topic , 'cb' : cb }
def main ( args ) : """invoke wptools and exit safely"""
start = time . time ( ) output = get ( args ) _safe_exit ( start , output )
def create_object ( self , name , url ) : """CREATES a single object in Vingd Object registry . : type name : ` ` string ` ` : param name : Object ' s name . : type url : ` ` string ` ` : param url : Callback URL ( object ' s resource location - on your server ) . : rtype : ` bigint ` : returns : Ob...
r = self . request ( 'post' , 'registry/objects/' , json . dumps ( { 'description' : { 'name' : name , 'url' : url } } ) ) return self . _extract_id_from_batch_response ( r , 'oid' )
def is_iterable_of_int ( l ) : r"""Checks if l is iterable and contains only integral types"""
if not is_iterable ( l ) : return False return all ( is_int ( value ) for value in l )
def getMessage ( self ) : """Returns a colorized log message based on the log level . If the platform is windows the original message will be returned without colorization windows escape codes are crazy . : returns : ` ` str ` `"""
msg = str ( self . msg ) if self . args : msg = msg % self . args if platform . system ( ) . lower ( ) == 'windows' or self . levelno < 10 : return msg elif self . levelno >= 50 : return utils . return_colorized ( msg , 'critical' ) elif self . levelno >= 40 : return utils . return_colorized ( msg , 'er...
def unlike ( self , id , reblog_key ) : """Unlike the post of the given blog : param id : an int , the id of the post you want to like : param reblog _ key : a string , the reblog key of the post : returns : a dict created from the JSON response"""
url = "/v2/user/unlike" params = { 'id' : id , 'reblog_key' : reblog_key } return self . send_api_request ( "post" , url , params , [ 'id' , 'reblog_key' ] )
def train ( self , true_sampler , generative_model , discriminative_model , iter_n = 100 , k_step = 10 ) : '''Train . Args : true _ sampler : Sampler which draws samples from the ` true ` distribution . generative _ model : Generator which draws samples from the ` fake ` distribution . discriminative _ mode...
if isinstance ( true_sampler , TrueSampler ) is False : raise TypeError ( "The type of `true_sampler` must be `TrueSampler`." ) if isinstance ( generative_model , AutoEncoderModel ) is False : raise TypeError ( "The type of `generative_model` must be `AutoEncoderModel`." ) if isinstance ( discriminative_model ,...
def _get_simple_uploaded_file ( self , image , file_name ) : """: param image : a python PIL ` ` Image ` ` instance . : param file _ name : The file name of the image . : returns : A django ` ` SimpleUploadedFile ` ` instance ready to be saved ."""
extension = os . path . splitext ( file_name ) [ 1 ] mimetype , encoding = mimetypes . guess_type ( file_name ) content_type = mimetype or 'image/png' temp_handle = BytesIO ( ) image . save ( temp_handle , self . _get_pil_format ( extension ) ) temp_handle . seek ( 0 ) # rewind the file suf = SimpleUploadedFile ( file_...
def cli ( command = None , ** kwargs ) : '''Executes the CLI commands and returns the output in specified format . ( default is text ) The output can also be stored in a file . command ( required ) The command to execute on the Junos CLI format : text Format in which to get the CLI output ( either ` ` text ...
conn = __proxy__ [ 'junos.conn' ] ( ) format_ = kwargs . pop ( 'format' , 'text' ) if not format_ : format_ = 'text' ret = { } if command is None : ret [ 'message' ] = 'Please provide the CLI command to be executed.' ret [ 'out' ] = False return ret op = dict ( ) if '__pub_arg' in kwargs : if kwargs...
def derivatives ( self , x , y , coeffs , beta , center_x = 0 , center_y = 0 ) : """returns df / dx and df / dy of the function"""
shapelets = self . _createShapelet ( coeffs ) n_order = self . _get_num_n ( len ( coeffs ) ) dx_shapelets = self . _dx_shapelets ( shapelets , beta ) dy_shapelets = self . _dy_shapelets ( shapelets , beta ) n = len ( np . atleast_1d ( x ) ) if n <= 1 : f_x = self . _shapeletOutput ( x , y , beta , dx_shapelets , pr...
def prep_nova_creds ( nova_env , nova_creds ) : """Finds relevant config options in the supernova config and cleans them up for novaclient ."""
try : raw_creds = dict ( nova_creds . get ( 'DEFAULT' , { } ) , ** nova_creds [ nova_env ] ) except KeyError : msg = "{0} was not found in your supernova configuration " "file" . format ( nova_env ) raise KeyError ( msg ) proxy_re = re . compile ( r"(^http_proxy|^https_proxy)" ) creds = [ ] for param , valu...
def do_tables ( self , line ) : "List tables"
self . tables = self . conn . list_tables ( ) . get ( 'TableNames' ) print "\nAvailable tables:" self . pprint ( self . tables )
def draw ( self ) : """Draws the alphas values against their associated error in a similar fashion to the AlphaSelection visualizer ."""
# Plot the alpha against the error self . ax . plot ( self . alphas , self . errors , label = self . name . lower ( ) ) # Draw a dashed vline at the alpha with maximal error alpha = self . alphas [ np . where ( self . errors == self . errors . max ( ) ) ] [ 0 ] label = "$\\alpha_{{max}}={:0.3f}$" . format ( alpha ) sel...
def get_mean_and_stddevs ( self , sites , rup , dists , imt , stddev_types ) : """Implements equation 3.5.1-1 page 148 for mean value and equation 3.5.5-1 page 151 for total standard deviation . See : meth : ` superclass method < . base . GroundShakingIntensityModel . get _ mean _ and _ stddevs > ` for spec...
mean , stddevs = super ( ) . get_mean_and_stddevs ( sites , rup , dists , imt , stddev_types ) x_tr = _get_min_distance_to_sub_trench ( sites . lon , sites . lat ) mean = _apply_subduction_trench_correction ( mean , x_tr , rup . hypo_depth , dists . rrup , imt ) return mean , stddevs
def load_finger_tapping_mpower_data ( filename , button_left_rect , button_right_rect , convert_times = 1000.0 ) : """This method loads data in the ` mpower < https : / / www . synapse . org / # ! Synapse : syn4993293 / wiki / 247859 > ` _ format"""
raw_data = pd . read_json ( filename ) date_times = pd . to_datetime ( raw_data . TapTimeStamp * convert_times - raw_data . TapTimeStamp [ 0 ] * convert_times ) time_difference = ( raw_data . TapTimeStamp - raw_data . TapTimeStamp [ 0 ] ) time_difference = time_difference . values x = [ ] y = [ ] x_target = [ ] y_targe...
def contains_parent_dir ( fpath , dirs ) : """Returns true if paths in dirs start with fpath . Precondition : dirs and fpath should be normalized before calling this function ."""
# Note : this function is used nowhere in pygccxml but is used # at least by pypluplus ; so it should stay here . return bool ( [ x for x in dirs if _f ( fpath , x ) ] )
def _make_read_func ( file_obj ) : """Return a CFFI callback that reads from a file - like object ."""
@ ffi . callback ( "cairo_read_func_t" , error = constants . STATUS_READ_ERROR ) def read_func ( _closure , data , length ) : string = file_obj . read ( length ) if len ( string ) < length : # EOF too early return constants . STATUS_READ_ERROR ffi . buffer ( data , length ) [ : len ( string ) ] = st...
def StartsWith ( this , that ) : """Checks whether an items of one iterable are a prefix of another . Args : this : An iterable that needs to be checked . that : An iterable of which items must match the prefix of ` this ` . Returns : ` True ` if ` that ` is a prefix of ` this ` , ` False ` otherwise ."""
this_iter = iter ( this ) that_iter = iter ( that ) while True : try : this_value = next ( that_iter ) except StopIteration : return True try : that_value = next ( this_iter ) except StopIteration : return False if this_value != that_value : return False
def worker_reject ( self , chosen_hit , assignment_ids = None ) : '''Reject worker'''
if chosen_hit : workers = self . amt_services . get_workers ( "Submitted" ) assignment_ids = [ worker [ 'assignmentId' ] for worker in workers if worker [ 'hitId' ] == chosen_hit ] print 'rejecting workers for HIT' , chosen_hit for assignment_id in assignment_ids : success = self . amt_services . reject...
def _process_batch_write_response ( request , response , table_crypto_config ) : # type : ( Dict , Dict , Dict [ Text , CryptoConfig ] ) - > Dict """Handle unprocessed items in the response from a transparently encrypted write . : param dict request : The DynamoDB plaintext request dictionary : param dict respo...
try : unprocessed_items = response [ "UnprocessedItems" ] except KeyError : return response # Unprocessed items need to be returned in their original state for table_name , unprocessed in unprocessed_items . items ( ) : original_items = request [ table_name ] crypto_config = table_crypto_config [ table_...
def __valid_on_demand_ext_pillar ( self , opts ) : '''Check to see if the on demand external pillar is allowed'''
if not isinstance ( self . ext , dict ) : log . error ( 'On-demand pillar %s is not formatted as a dictionary' , self . ext ) return False on_demand = opts . get ( 'on_demand_ext_pillar' , [ ] ) try : invalid_on_demand = set ( [ x for x in self . ext if x not in on_demand ] ) except TypeError : # Prevent tr...
def register_menu_item ( self , items ) : """Registers a views menu items into the metadata for the application . Skip if the item is already present Args : items ( ` list ` of ` MenuItem ` ) : A list of ` MenuItem ` s Returns : ` None `"""
for itm in items : if itm . group in self . menu_items : # Only add the menu item if we don ' t already have it registered if itm not in self . menu_items [ itm . group ] [ 'items' ] : self . menu_items [ itm . group ] [ 'items' ] . append ( itm ) else : logger . warning ( 'Tried reg...
def _set_query_data_fast_1 ( self , page ) : """set less expensive action = query response data PART 1"""
self . data [ 'pageid' ] = page . get ( 'pageid' ) assessments = page . get ( 'pageassessments' ) if assessments : self . data [ 'assessments' ] = assessments extract = page . get ( 'extract' ) if extract : self . data [ 'extract' ] = extract extext = html2text . html2text ( extract ) if extext : ...
def uninstall ( self , plugin ) : '''Uninstall plugins . Pass an instance to remove a specific plugin . Pass a type object to remove all plugins that match that type . Subclasses are not removed . Pass a string to remove all plugins with a matching ` ` name ` ` attribute . Pass ` ` True ` ` to remove all plug...
removed , remove = [ ] , plugin for i , plugin in list ( enumerate ( self . plugins ) ) [ : : - 1 ] : if remove is True or remove is plugin or remove is type ( plugin ) or getattr ( plugin , 'name' , True ) == remove : removed . append ( plugin ) del self . plugins [ i ] if hasattr ( plugin ...
def info ( self , node_id = None , metric = None , params = None ) : """The cluster nodes info API allows to retrieve one or more ( or all ) of the cluster nodes information . ` < https : / / www . elastic . co / guide / en / elasticsearch / reference / current / cluster - nodes - info . html > ` _ : arg node...
return self . transport . perform_request ( "GET" , _make_path ( "_nodes" , node_id , metric ) , params = params )
def setBusStop ( self , vehID , stopID , duration = 2 ** 31 - 1 , until = - 1 , flags = tc . STOP_DEFAULT ) : """setBusStop ( string , string , integer , integer , integer ) - > None Adds or modifies a bus stop with the given parameters . The duration and the until attribute are in milliseconds ."""
self . setStop ( vehID , stopID , duration = duration , until = until , flags = flags | tc . STOP_BUS_STOP )
def setup_completer ( cls ) : "Get the dictionary of valid completions"
try : for element in Store . options ( ) . keys ( ) : options = Store . options ( ) [ '.' . join ( element ) ] plotkws = options [ 'plot' ] . allowed_keywords stylekws = options [ 'style' ] . allowed_keywords dotted = '.' . join ( element ) cls . _completions [ dotted ] = ( p...
def updatepLvlGrid ( self ) : '''Update the grid of persistent income levels . Currently only works for infinite horizon models ( cycles = 0 ) and lifecycle models ( cycles = 1 ) . Not clear what to do about cycles > 1 because the distribution of persistent income will be different within a period depending o...
orig_time = self . time_flow self . timeFwd ( ) LivPrbAll = np . array ( self . LivPrb ) # Simulate the distribution of persistent income levels by t _ cycle in a lifecycle model if self . cycles == 1 : pLvlNow = drawLognormal ( self . AgentCount , mu = self . pLvlInitMean , sigma = self . pLvlInitStd , seed = 3138...
def filter_ignoring_case ( self , pattern ) : """Like ` ` filter ` ` but case - insensitive . Expects a regular expression string without the surrounding ` ` / ` ` characters . > > > see ( ) . filter ( ' ^ my ' , ignore _ case = True ) MyClass ( )"""
return self . filter ( re . compile ( pattern , re . I ) )
def replace_cash_on_delivery_payment_by_id ( cls , cash_on_delivery_payment_id , cash_on_delivery_payment , ** kwargs ) : """Replace CashOnDeliveryPayment Replace all attributes of CashOnDeliveryPayment This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pas...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _replace_cash_on_delivery_payment_by_id_with_http_info ( cash_on_delivery_payment_id , cash_on_delivery_payment , ** kwargs ) else : ( data ) = cls . _replace_cash_on_delivery_payment_by_id_with_http_info ( cash_on_delivery_pa...
def p_scalar__indented_flow ( self , p ) : """scalar : INDENT scalar _ group DEDENT"""
scalar_group = '\n' . join ( p [ 2 ] ) folded_scalar = fold ( dedent ( scalar_group ) ) p [ 0 ] = ScalarDispatch ( folded_scalar , cast = 'str' )
def _init_map ( self ) : """stub"""
QuestionTextAndFilesMixin . _init_map ( self ) BaseMultiChoiceTextQuestionFormRecord . _init_map ( self ) super ( MultiChoiceTextAndFilesQuestionFormRecord , self ) . _init_map ( )
def _type_check_pointers ( utype ) : """Checks the user - derived type for non - nullified pointer array declarations in its base definition . Returns ( list of offending members ) ."""
result = [ ] for mname , member in utype . members . items ( ) : if ( "pointer" in member . modifiers and member . D > 0 and ( member . default is None or "null" not in member . default ) ) : result . append ( member ) return result
def validate_to_one ( self , value ) : """Check if the to _ one should exist & casts properly"""
if value . rid and self . typeness is int : validators . validate_int ( value ) if value . rid and not self . skip_exists : if not value . load ( ) : raise ValidationError ( self . messages [ 'exists' ] ) return value
def convert_notebooks ( self ) : """Convert IPython notebooks to Python scripts in editor"""
fnames = self . get_selected_filenames ( ) if not isinstance ( fnames , ( tuple , list ) ) : fnames = [ fnames ] for fname in fnames : self . convert_notebook ( fname )
def get_spaced_plot_colors ( n , start = 45 , saturation_adjustment = 0.7 , saturation = 0.65 , lightness = 1.0 , prefix = '' ) : '''Returns a list of colors with the same distributed spread as used in ggplot2 ( color wheel ) but shaken up a little so that adjacent series have differing hues for larger values of ...
assert ( n > 0 ) if n <= 5 : # For small n , the color wheel will generate colors which naturally differ return ggplot_color_wheel ( n , start = start , saturation_adjustment = saturation_adjustment , saturation = saturation , lightness = lightness , prefix = prefix ) else : # For larger values of n , generate n co...
def set_x10_address ( self , x10address ) : """Set the X10 address for the current group / button ."""
set_cmd = self . _create_set_property_msg ( '_x10_house_code' , 0x04 , x10address ) self . _send_method ( set_cmd , self . _property_set )
def check_config ( ) : """Report if there is an existing config file"""
configfile = ConfigFile ( ) global data if data . keys ( ) > 0 : # FIXME : run a better check of this file print ( "gitberg config file exists" ) print ( "\twould you like to edit your gitberg config file?" ) else : print ( "No config found" ) print ( "\twould you like to create a gitberg config file?" ...
def delete_agents_bulk ( self , payload ) : """Delete a group of agents : param list payload : Contains the informations to delete the agents . It ' s in the form [ { " id " : agent _ id } ] . With id an str containing only characters in " a - zA - Z0-9 _ - " and must be between 1 and 36 characters . : re...
# Check all ids , raise an error if all ids are invalid valid_indices , invalid_indices , invalid_agents = self . _check_agent_id_bulk ( payload ) # Create the json file with the agents with valid id and send it valid_agents = self . _create_and_send_json_bulk ( [ payload [ i ] for i in valid_indices ] , "{}/bulk/agent...
def absent ( name , uninstall = False ) : '''Ensure a zone is absent name : string name of the zone uninstall : boolean when true , uninstall instead of detaching the zone first .'''
ret = { 'name' : name , 'changes' : { } , 'result' : None , 'comment' : '' } zones = __salt__ [ 'zoneadm.list' ] ( installed = True , configured = True ) if name in zones : if __opts__ [ 'test' ] : ret [ 'result' ] = True ret [ 'changes' ] [ name ] = 'removed' ret [ 'comment' ] = 'Zone {0} w...
def lv_connect_generators ( lv_grid_district , graph , debug = False ) : """Connect LV generators to LV grid Args lv _ grid _ district : LVGridDistrictDing0 LVGridDistrictDing0 object for which the connection process has to be done graph : : networkx : ` NetworkX Graph Obj < > ` NetworkX graph object with...
cable_lf = cfg_ding0 . get ( 'assumptions' , 'load_factor_lv_cable_fc_normal' ) cos_phi_gen = cfg_ding0 . get ( 'assumptions' , 'cos_phi_gen' ) # generate random list ( without replacement = > unique elements ) # of loads ( residential ) to connect genos ( P < = 30kW ) to . lv_loads_res = sorted ( lv_grid_district . lv...
def setCustomCompletions ( self , wordSet ) : """Add a set of custom completions to the editors completions . This set is managed independently of the set of keywords and words from the current document , and can thus be changed at any time ."""
if not isinstance ( wordSet , set ) : raise TypeError ( '"wordSet" is not a set: %s' % type ( wordSet ) ) self . _completer . setCustomCompletions ( wordSet )
def arg_to_json ( arg ) : """Perform necessary JSON conversion on the arg ."""
conversion = json_conversions . get ( type ( arg ) ) if conversion : return conversion ( arg ) for type_ in subclass_conversions : if isinstance ( arg , type_ ) : return json_conversions [ type_ ] ( arg ) return json_conversions [ str ] ( arg )
def handle_pingresp ( self ) : """Handle incoming PINGRESP packet ."""
self . logger . debug ( "PINGRESP received" ) self . push_event ( event . EventPingResp ( ) ) return NC . ERR_SUCCESS
async def read_portrait_landscape ( self , callback = None ) : """This function reads the portrait / landscape status register of the MMA8452Q . It will return either PORTRAIT _ U , PORTRAIT _ D , LANDSCAPE _ R , LANDSCAPE _ L , or LOCKOUT . LOCKOUT indicates that the sensor is in neither p or ls . : param ca...
register = self . MMA8452Q_Register [ 'PL_STATUS' ] await self . board . i2c_read_request ( self . address , register , 1 , Constants . I2C_READ | Constants . I2C_END_TX_MASK , self . data_val , Constants . CB_TYPE_ASYNCIO ) pl_status = await self . wait_for_read_result ( ) pl_status = pl_status [ self . data_start ] i...
def create ( provider , count = 1 , name = None , ** kwargs ) : r'''Create one or more cloud servers Args : * provider ( str ) : Cloud provider , e . g . ec2 , digitalocean * count ( int ) = 1 : Number of instances * name ( str ) = None : Name of server ( s ) * \ * * kwargs : Provider - specific flags'''
count = int ( count ) provider = provider_by_name ( provider ) options = provider . create_server_defaults options . update ( kwargs ) names = [ name ] * count provider . validate_create_options ( ** options ) return provider . create_servers ( count , names , ** options )
def _get_atomsection ( mol2_lst ) : """Returns atom section from mol2 provided as list of strings"""
started = False for idx , s in enumerate ( mol2_lst ) : if s . startswith ( '@<TRIPOS>ATOM' ) : first_idx = idx + 1 started = True elif started and s . startswith ( '@<TRIPOS>' ) : last_idx_plus1 = idx break return mol2_lst [ first_idx : last_idx_plus1 ]
def easeInOutExpo ( n ) : """An exponential tween function that accelerates , reaches the midpoint , and then decelerates . Args : n ( float ) : The time progress , starting at 0.0 and ending at 1.0. Returns : ( float ) The line progress , starting at 0.0 and ending at 1.0 . Suitable for passing to getPoint...
_checkRange ( n ) if n == 0 : return 0 elif n == 1 : return 1 else : n = n * 2 if n < 1 : return 0.5 * 2 ** ( 10 * ( n - 1 ) ) else : n -= 1 # 0.5 * ( - ( ) + 2) return 0.5 * ( - 1 * ( 2 ** ( - 10 * n ) ) + 2 )
def setItemData ( self , treeItem , column , value , role = Qt . EditRole ) : """Sets the role data for the item at index to value ."""
if role == Qt . CheckStateRole : if column != self . COL_VALUE : return False else : logger . debug ( "Setting check state (col={}): {!r}" . format ( column , value ) ) treeItem . checkState = value return True elif role == Qt . EditRole : if column != self . COL_VALUE : ...
def make_purge_data ( parser ) : """Purge ( delete , destroy , discard , shred ) any Ceph data from / var / lib / ceph"""
parser . add_argument ( 'host' , metavar = 'HOST' , nargs = '+' , help = 'hosts to purge Ceph data from' , ) parser . set_defaults ( func = purgedata , )
def create_web_forward ( self , zone_name , request_to , redirect_to , forward_type ) : """Create a web forward record . Arguments : zone _ name - - The zone in which the web forward is to be created . request _ to - - The URL to be redirected . You may use http : / / and ftp : / / . forward _ type - - The ...
web_forward = { "requestTo" : request_to , "defaultRedirectTo" : redirect_to , "defaultForwardType" : forward_type } return self . rest_api_connection . post ( "/v1/zones/" + zone_name + "/webforwards" , json . dumps ( web_forward ) )
def glob ( * args ) : """Returns list of paths matching one or more wildcard patterns . Args : include _ dirs : Include directories in the output"""
if len ( args ) is 1 and isinstance ( args [ 0 ] , list ) : args = args [ 0 ] matches = [ ] for pattern in args : for item in glob2 . glob ( pattern ) : if not os . path . isdir ( item ) : matches . append ( item ) return matches
def _add_global_secondary_index ( ret , name , index_name , changes_old , changes_new , comments , gsi_config , region , key , keyid , profile ) : '''Updates ret iff there was a failure or in test mode .'''
if __opts__ [ 'test' ] : ret [ 'result' ] = None ret [ 'comment' ] = 'Dynamo table {0} will have a GSI added: {1}' . format ( name , index_name ) return changes_new . setdefault ( 'global_indexes' , { } ) success = __salt__ [ 'boto_dynamodb.create_global_secondary_index' ] ( name , __salt__ [ 'boto_dynamodb...
def add_auto_increment ( self , table , name ) : """Modify an existing column ."""
# Get current column definition and add auto _ incrementing definition = self . get_column_definition ( table , name ) + ' AUTO_INCREMENT' # Concatenate and execute modify statement self . execute ( "ALTER TABLE {0} MODIFY {1}" . format ( table , definition ) ) self . _printer ( '\tAdded AUTO_INCREMENT to column {0}' ....
def to_struct ( self , value ) : """Cast ` date ` object to string ."""
if self . str_format : return value . strftime ( self . str_format ) return value . strftime ( self . default_format )
def write ( self , text ) : """Write text in the terminal without breaking the spinner ."""
# similar to tqdm . write ( ) # https : / / pypi . python . org / pypi / tqdm # writing - messages sys . stdout . write ( "\r" ) self . _clear_line ( ) _text = to_unicode ( text ) if PY2 : _text = _text . encode ( ENCODING ) # Ensure output is bytes for Py2 and Unicode for Py3 assert isinstance ( _text , builtin_st...
def import_context ( target_zip ) : """Overwrite old context . json , use context . json from target _ zip : param target _ zip : : return :"""
context_path = tasks . get_context_path ( ) with zipfile . ZipFile ( target_zip ) as unzipped_data : with open ( context_path , 'w' ) as context : context . write ( unzipped_data . read ( 'context.json' ) )
def _ipaddress_match ( ipname , host_ip ) : """Exact matching of IP addresses . RFC 6125 explicitly doesn ' t define an algorithm for this ( section 1.7.2 - " Out of Scope " ) ."""
# OpenSSL may add a trailing newline to a subjectAltName ' s IP address ip = ipaddress . ip_address ( six . text_type ( ipname . rstrip ( ) ) ) return ip == host_ip
def parse_html_dict ( dictionary , prefix = '' ) : """Used to support dictionary values in HTML forms . ' profile . username ' : ' example ' , ' profile . email ' : ' example @ example . com ' , ' profile ' : { ' username ' : ' example ' , ' email ' : ' example @ example . com '"""
ret = MultiValueDict ( ) regex = re . compile ( r'^%s\.(.+)$' % re . escape ( prefix ) ) for field , value in dictionary . items ( ) : match = regex . match ( field ) if not match : continue key = match . groups ( ) [ 0 ] ret [ key ] = value return ret
def mcc ( y , z ) : """Matthews correlation coefficient"""
tp , tn , fp , fn = contingency_table ( y , z ) return ( tp * tn - fp * fn ) / K . sqrt ( ( tp + fp ) * ( tp + fn ) * ( tn + fp ) * ( tn + fn ) )
def boxify_points ( geom , rast ) : """Point and MultiPoint don ' t play well with GDALRasterize convert them into box polygons 99 % cellsize , centered on the raster cell"""
if 'Point' not in geom . type : raise ValueError ( "Points or multipoints only" ) buff = - 0.01 * abs ( min ( rast . affine . a , rast . affine . e ) ) if geom . type == 'Point' : pts = [ geom ] elif geom . type == "MultiPoint" : pts = geom . geoms geoms = [ ] for pt in pts : row , col = rast . index ( ...
def get_all_names_page ( offset , count , include_expired = False , hostport = None , proxy = None ) : """get a page of all the names Returns the list of names on success Returns { ' error ' : . . . } on error"""
assert proxy or hostport , 'Need proxy or hostport' if proxy is None : proxy = connect_hostport ( hostport ) page_schema = { 'type' : 'object' , 'properties' : { 'names' : { 'type' : 'array' , 'items' : { 'type' : 'string' , 'uniqueItems' : True } , } , } , 'required' : [ 'names' , ] , } schema = json_response_sche...
def html_override_tool ( ) : '''Bypass the normal handler and serve HTML for all URLs The ` ` app _ path ` ` setting must be non - empty and the request must ask for ` ` text / html ` ` in the ` ` Accept ` ` header .'''
apiopts = cherrypy . config [ 'apiopts' ] request = cherrypy . request url_blacklist = ( apiopts . get ( 'app_path' , '/app' ) , apiopts . get ( 'static_path' , '/static' ) , ) if 'app' not in cherrypy . config [ 'apiopts' ] : return if request . path_info . startswith ( url_blacklist ) : return if request . he...
def unpack_xml ( text ) -> ET . ElementTree : """Unpack an XML string from AniDB API ."""
etree : ET . ElementTree = ET . parse ( io . StringIO ( text ) ) _check_for_errors ( etree ) return etree
def as_dtype ( type_value ) : """Converts the given ` type _ value ` to a ` DType ` . Args : type _ value : A value that can be converted to a ` tf . DType ` object . This may currently be a ` tf . DType ` object , a [ ` DataType ` enum ] ( https : / / www . tensorflow . org / code / tensorflow / core / fra...
if isinstance ( type_value , DType ) : return type_value try : return _INTERN_TABLE [ type_value ] except KeyError : pass try : return _STRING_TO_TF [ type_value ] except KeyError : pass try : return _PYTHON_TO_TF [ type_value ] except KeyError : pass if isinstance ( type_value , np . dtype ...
def generate_license ( args ) : '''Creates a LICENSE or LICENSE . txt file in the current directory . Reads from the ' assets ' folder and looks for placeholders enclosed in curly braces . Arguments : - ( tuple ) Name , email , license , project , ext , year'''
with open ( cwd + licenses_loc + args [ 2 ] ) as f : license = f . read ( ) license = license . format ( name = args [ 0 ] , email = args [ 1 ] , license = args [ 2 ] , project = args [ 3 ] , year = args [ 5 ] ) with open ( 'LICENSE' + args [ 4 ] , 'w' ) as f : f . write ( license ) print ( 'licenser: licen...
def get_buckets ( self , timeout = None ) : """Get the list of buckets under this bucket - type as : class : ` RiakBucket < riak . bucket . RiakBucket > ` instances . . . warning : : Do not use this in production , as it requires traversing through all keys stored in a cluster . . . note : : This request is...
return self . _client . get_buckets ( bucket_type = self , timeout = timeout )
def computeImgSignature ( image_data ) : """Calculate an image signature . This is similar to ahash but uses 3 colors components See : https : / / github . com / JohannesBuchner / imagehash / blob / 4.0 / imagehash / _ _ init _ _ . py # L125"""
parser = PIL . ImageFile . Parser ( ) parser . feed ( image_data ) img = parser . close ( ) target_size = ( __class__ . IMG_SIG_SIZE , __class__ . IMG_SIG_SIZE ) img . thumbnail ( target_size , PIL . Image . BICUBIC ) if img . size != target_size : logging . getLogger ( "Cover" ) . debug ( "Non square thumbnail aft...
def _get_data_path ( data_dir = None ) : """Get data storage directory data _ dir : str Path of the data directory . Used to force data storage in a specified location . : returns : a list of paths where the dataset could be stored , ordered by priority"""
data_dir = data_dir or '' default_dirs = [ Path ( d ) . expanduser ( ) . resolve ( ) for d in os . getenv ( 'CRN_SHARED_DATA' , '' ) . split ( os . pathsep ) if d . strip ( ) ] default_dirs += [ Path ( d ) . expanduser ( ) . resolve ( ) for d in os . getenv ( 'CRN_DATA' , '' ) . split ( os . pathsep ) if d . strip ( ) ...
def fromRoman ( strng ) : """convert Roman numeral to integer"""
if not strng : raise TypeError ( 'Input can not be blank' ) if not romanNumeralPattern . search ( strng ) : raise ValueError ( 'Invalid Roman numeral: %s' , strng ) result = 0 index = 0 for numeral , integer in romanNumeralMap : while strng [ index : index + len ( numeral ) ] == numeral : result += ...