signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_order_by_id ( cls , order_id , ** kwargs ) : """Find Order Return single instance of Order by its ID . This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . get _ order _ by _ id ( order _ id , async = True ) ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _get_order_by_id_with_http_info ( order_id , ** kwargs ) else : ( data ) = cls . _get_order_by_id_with_http_info ( order_id , ** kwargs ) return data
def for_entity ( obj , check_commentable = False ) : """Return comments on an entity ."""
if check_commentable and not is_commentable ( obj ) : return [ ] return getattr ( obj , ATTRIBUTE )
def ip_access_control_lists ( self ) : """Access the ip _ access _ control _ lists : returns : twilio . rest . trunking . v1 . trunk . ip _ access _ control _ list . IpAccessControlListList : rtype : twilio . rest . trunking . v1 . trunk . ip _ access _ control _ list . IpAccessControlListList"""
if self . _ip_access_control_lists is None : self . _ip_access_control_lists = IpAccessControlListList ( self . _version , trunk_sid = self . _solution [ 'sid' ] , ) return self . _ip_access_control_lists
def _http_get ( self , url ) : """Make an HTTP GET request to the specified URL and return the response . Retries The constructor of this class takes an argument specifying the number of times to retry a GET . The statuses which are retried on are : 408, 500 , 502 , 503 , and 504. Returns An HTTP respon...
for try_number in range ( self . _http_retries + 1 ) : response = requests . get ( url , timeout = self . _http_timeout ) if response . status_code == 200 : return response if ( try_number >= self . _http_retries or response . status_code not in ( 408 , 500 , 502 , 503 , 504 ) ) : if respons...
def change_username_view ( self ) : """Prompt for new username and old password and change the user ' s username ."""
# Initialize form form = self . ChangeUsernameFormClass ( request . form ) # Process valid POST if request . method == 'POST' and form . validate ( ) : # Change username new_username = form . new_username . data current_user . username = new_username self . db_manager . save_object ( current_user ) self...
def send_message ( registration_ids , data , cloud_type , application_id = None , ** kwargs ) : """Sends a FCM ( or GCM ) notification to one or more registration _ ids . The registration _ ids can be a list or a single string . This will send the notification as json data . A reference of extra keyword argumen...
if cloud_type in ( "FCM" , "GCM" ) : max_recipients = get_manager ( ) . get_max_recipients ( cloud_type , application_id ) else : raise ImproperlyConfigured ( "cloud_type must be FCM or GCM not %s" % str ( cloud_type ) ) # Checks for valid recipient if registration_ids is None and "/topics/" not in kwargs . get...
def shutdown ( self ) : """Shutdown the client , shutdown the sub clients and stop the health checker : return : None"""
self . _run_health_checker = False if self . publisher is not None : self . publisher . shutdown ( ) if self . subscriber is not None : self . subscriber . shutdown ( )
def getObject ( ID , date , pos ) : """Returns an ephemeris object ."""
obj = eph . getObject ( ID , date . jd , pos . lat , pos . lon ) return Object . fromDict ( obj )
def validate ( self , uri ) : """Check an URI for compatibility with this specification . Return True if the URI is compatible . : param uri : an URI to check : return : bool"""
requirement = self . requirement ( ) uri_component = uri . component ( self . component ( ) ) if uri_component is None : return requirement != WURIComponentVerifier . Requirement . required if requirement == WURIComponentVerifier . Requirement . unsupported : return False re_obj = self . re_obj ( ) if re_obj is...
def _get_y_scores ( self , X ) : """The ` ` roc _ curve ` ` metric requires target scores that can either be the probability estimates of the positive class , confidence values or non - thresholded measure of decisions ( as returned by " decision _ function " ) . This method computes the scores by resolving t...
# The resolution order of scoring functions attrs = ( 'predict_proba' , 'decision_function' , ) # Return the first resolved function for attr in attrs : try : method = getattr ( self . estimator , attr , None ) if method : return method ( X ) except AttributeError : # Some Scikit - L...
def query ( args ) : """% prog query frgscf . sorted scfID : start - end Query certain region to get frg placement , using random access . Build index if not present ."""
p = OptionParser ( query . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( p . print_help ( ) ) frgscffile , region = args gzfile = frgscffile + ".gz" tbifile = gzfile + ".tbi" outfile = region + ".posmap" if not ( op . exists ( gzfile ) and op . exists ( tbifile ) ) : index ...
def _get_wrapper ( ) : """Get a socket wrapper based on SSL config ."""
if not pmxbot . config . get ( 'use_ssl' , False ) : return lambda x : x return importlib . import_module ( 'ssl' ) . wrap_socket
def set_all_neighbors_data ( self , data , done , key ) : """Given they ' key ' tile ' s data , assigns this information to all neighboring tiles"""
# The order of this for loop is important because the topleft gets # it ' s data from the left neighbor , which should have already been # updated . . . for side in [ 'left' , 'right' , 'top' , 'bottom' , 'topleft' , 'topright' , 'bottomleft' , 'bottomright' ] : self . set_neighbor_data ( side , data , key , 'data'...
def render ( template_name , extra_environments = None , ** kwargs ) : """주어진 템플릿을 jinja로 렌더링합니다 : param template _ name : : return :"""
if extra_environments is None : extra_environments = { } default_loader = PackageLoader ( 'dodotable' , 'templates' ) loader = extra_environments . get ( 'template_loader' , default_loader ) if not loader : loader = default_loader get_translations = extra_environments . get ( 'get_translations' ) env = Environm...
def _get_expiry_timestamp ( cls , session_server ) : """: type session _ server : core . SessionServer : rtype : datetime . datetime"""
timeout_seconds = cls . _get_session_timeout_seconds ( session_server ) time_now = datetime . datetime . now ( ) return time_now + datetime . timedelta ( seconds = timeout_seconds )
def to_aperture ( self ) : """Return a ` ~ photutils . aperture . RectangularAperture ` that represents the bounding box ."""
from . rectangle import RectangularAperture xpos = ( self . extent [ 1 ] + self . extent [ 0 ] ) / 2. ypos = ( self . extent [ 3 ] + self . extent [ 2 ] ) / 2. xypos = ( xpos , ypos ) h , w = self . shape return RectangularAperture ( xypos , w = w , h = h , theta = 0. )
def get_kwargs ( self ) : """Return kwargs dict for text"""
kwargs = { } if self . font_face : kwargs [ "fontname" ] = repr ( self . font_face ) if self . font_size : kwargs [ "fontsize" ] = repr ( self . font_size ) if self . font_style in self . style_wx2mpl : kwargs [ "fontstyle" ] = repr ( self . style_wx2mpl [ self . font_style ] ) if self . font_weight in self...
def deprecated ( since , message = '' , name = '' , alternative = '' , pending = False , addendum = '' , removal = '' ) : """Decorator to mark a function or a class as deprecated . Parameters since : str The release at which this API became deprecated . This is required . message : str , optional Overri...
def deprecate ( obj , message = message , name = name , alternative = alternative , pending = pending , addendum = addendum ) : if not name : name = obj . __name__ if isinstance ( obj , type ) : obj_type = "class" old_doc = obj . __doc__ func = obj . __init__ def finalize...
def pv_present ( name , ** kwargs ) : '''Set a Physical Device to be used as an LVM Physical Volume name The device name to initialize . kwargs Any supported options to pvcreate . See : mod : ` linux _ lvm < salt . modules . linux _ lvm > ` for more details .'''
ret = { 'changes' : { } , 'comment' : '' , 'name' : name , 'result' : True } if __salt__ [ 'lvm.pvdisplay' ] ( name , quiet = True ) : ret [ 'comment' ] = 'Physical Volume {0} already present' . format ( name ) elif __opts__ [ 'test' ] : ret [ 'comment' ] = 'Physical Volume {0} is set to be created' . format ( ...
def _uniquely_named_callbacks ( self ) : """Make sure that the returned dict of named callbacks is unique w . r . t . to the callback name . User - defined names will not be renamed on conflict , instead an exception will be raised . The same goes for the event where renaming leads to a conflict ."""
grouped_cbs , names_set_by_user = self . _callbacks_grouped_by_name ( ) for name , cbs in grouped_cbs . items ( ) : if len ( cbs ) > 1 and name in names_set_by_user : raise ValueError ( "Found duplicate user-set callback name " "'{}'. Use unique names to correct this." . format ( name ) ) for i , cb in ...
def parse_dataset_key ( dataset_key ) : """Parse a dataset URL or path and return the owner and the dataset id : param dataset _ key : Dataset key ( in the form of owner / id ) or dataset URL : type dataset _ key : str : returns : User name of the dataset owner and ID of the dataset : rtype : dataset _ owne...
match = re . match ( DATASET_KEY_PATTERN , dataset_key ) if not match : raise ValueError ( 'Invalid dataset key. Key must include user and ' 'dataset names, separated by (i.e. user/dataset).' ) return match . groups ( )
def lastz_to_blast ( row ) : """Convert the lastz tabular to the blast tabular , see headers above Obsolete after LASTZ version 1.02.40"""
atoms = row . strip ( ) . split ( "\t" ) name1 , name2 , coverage , identity , nmismatch , ngap , start1 , end1 , strand1 , start2 , end2 , strand2 , score = atoms identity = identity . replace ( "%" , "" ) hitlen = coverage . split ( "/" ) [ 1 ] score = float ( score ) same_strand = ( strand1 == strand2 ) if not same_...
def delete_multi ( self , keys ) : """Delete multiple keys from server in one command . : param keys : A list of keys to be deleted : type keys : list : return : True in case of success and False in case of failure . : rtype : bool"""
logger . debug ( 'Deleting keys %r' , keys ) if six . PY2 : msg = '' else : msg = b'' for key in keys : msg += struct . pack ( self . HEADER_STRUCT + self . COMMANDS [ 'delete' ] [ 'struct' ] % len ( key ) , self . MAGIC [ 'request' ] , self . COMMANDS [ 'delete' ] [ 'command' ] , len ( key ) , 0 , 0 , 0 , ...
def set_ylimits_for_all ( self , row_column_list = None , min = None , max = None ) : """Set y - axis limits of specified subplots . : param row _ column _ list : a list containing ( row , column ) tuples to specify the subplots , or None to indicate * all * subplots . : type row _ column _ list : list or Non...
if row_column_list is None : self . limits [ 'ymin' ] = min self . limits [ 'ymax' ] = max else : for row , column in row_column_list : self . set_ylimits ( row , column , min , max )
def add_script ( self , key : str , value : str , lineno : Optional [ int ] = None ) -> None : '''script starts with key : value'''
# we need a fake directive here because the : directive can be multi - line and # we need to borrow the syntax checking of directives here . self . statements . append ( [ ':' , '__script__' , '' ] ) self . values = [ value ] self . _action = key self . _action_options = value if lineno : self . lineno = lineno
def clear ( self ) : """Clears the text from the edit ."""
super ( XLineEdit , self ) . clear ( ) self . textEntered . emit ( '' ) self . textChanged . emit ( '' ) self . textEdited . emit ( '' )
def items ( self ) : """Returns a list of all the items associated with this panel . : return [ < XViewPanelItem > , . . ]"""
output = [ ] for i in xrange ( self . layout ( ) . count ( ) ) : item = self . layout ( ) . itemAt ( i ) try : widget = item . widget ( ) except AttributeError : break if isinstance ( widget , XViewPanelItem ) : output . append ( widget ) else : break return output
def print_summary ( self , w = 0 , objs = ( ) , ** print3opts ) : '''Print the summary statistics . * w = 0 * - - indentation for each line * objs = ( ) * - - optional , list of objects * print3options * - - print options , as in Python 3.0'''
self . _printf ( '%*d bytes%s%s' , w , self . _total , _SI ( self . _total ) , self . _incl , ** print3opts ) if self . _mask : self . _printf ( '%*d byte aligned' , w , self . _mask + 1 , ** print3opts ) self . _printf ( '%*d byte sizeof(void*)' , w , _sizeof_Cvoidp , ** print3opts ) n = len ( objs or ( ) ) if n >...
def len ( iterable ) : """Redefining len here so it will be able to work with non - ASCII characters"""
if isinstance ( iterable , bytes_type ) or isinstance ( iterable , unicode_type ) : return sum ( [ uchar_width ( c ) for c in obj2unicode ( iterable ) ] ) else : return iterable . __len__ ( )
def available_endpoint_services ( self ) : """Instance depends on the API version : * 2017-06-01 : : class : ` AvailableEndpointServicesOperations < azure . mgmt . network . v2017_06_01 . operations . AvailableEndpointServicesOperations > ` * 2017-08-01 : : class : ` AvailableEndpointServicesOperations < azure ...
api_version = self . _get_api_version ( 'available_endpoint_services' ) if api_version == '2017-06-01' : from . v2017_06_01 . operations import AvailableEndpointServicesOperations as OperationClass elif api_version == '2017-08-01' : from . v2017_08_01 . operations import AvailableEndpointServicesOperations as O...
def iter_encoded ( self ) : """Iter the response encoded with the encoding of the response . If the response object is invoked as WSGI application the return value of this method is used as application iterator unless : attr : ` direct _ passthrough ` was activated ."""
charset = self . charset if __debug__ : _warn_if_string ( self . response ) # Encode in a separate function so that self . response is fetched # early . This allows us to wrap the response with the return # value from get _ app _ iter or iter _ encoded . return _iter_encoded ( self . response , self . charset )
async def ctcp_reply ( self , target , query , response ) : """Send a CTCP reply to a target ."""
if self . is_channel ( target ) and not self . in_channel ( target ) : raise client . NotInChannel ( target ) await self . notice ( target , construct_ctcp ( query , response ) )
def add_link ( self , targets , weight ) : """Add link ( s ) pointing to ` ` targets ` ` . If a link already exists pointing to a target , just add ` ` weight ` ` to that link ' s weight Args : targets ( Node or list [ Node ] ) : node or nodes to link to weight ( int or float ) : weight for the new link (...
# Generalize targets to a list to simplify code if not isinstance ( targets , list ) : target_list = [ targets ] else : target_list = targets for target in target_list : # Check to see if self already has a link to target for existing_link in self . link_list : if existing_link . target == target : ...
def add_table_ends ( para , oformat = 'latex' , caption = "caption-text" , label = "table" ) : """Adds the latex table ends : param para : : param oformat : : param caption : : param label : : return :"""
fpara = "" if oformat == 'latex' : fpara += "\\begin{table}[H]\n" fpara += "\\centering\n" fpara += "\\begin{tabular}{cc}\n" fpara += "\\toprule\n" fpara += "Parameter & Value \\\\\n" fpara += "\\midrule\n" fpara += para fpara += "\\bottomrule\n" fpara += "\\end{tabular}\n" fpara...
def describe ( table_name , region = None , key = None , keyid = None , profile = None ) : '''Describe a DynamoDB table . CLI example : : salt myminion boto _ dynamodb . describe table _ name region = us - east - 1'''
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) table = Table ( table_name , connection = conn ) return table . describe ( )
def add_user ( self , user , first_name , last_name , email , password , url_prefix , auth , session , send_opts ) : """Add a new user . Args : user ( string ) : User name . first _ name ( string ) : User ' s first name . last _ name ( string ) : User ' s last name . email : ( string ) : User ' s email ad...
req = self . get_user_request ( 'POST' , 'application/json' , url_prefix , auth , user , first_name , last_name , email , password ) prep = session . prepare_request ( req ) resp = session . send ( prep , ** send_opts ) if resp . status_code == 201 : return msg = ( 'Failed adding user: {}, got HTTP response: ({}) -...
def set_lb_listener_SSL_certificate ( self , lb_name , lb_port , ssl_certificate_id ) : """Sets the certificate that terminates the specified listener ' s SSL connections . The specified certificate replaces any prior certificate that was used on the same LoadBalancer and port ."""
params = { 'LoadBalancerName' : lb_name , 'LoadBalancerPort' : lb_port , 'SSLCertificateId' : ssl_certificate_id , } return self . get_status ( 'SetLoadBalancerListenerSSLCertificate' , params )
def _cursorUp ( self ) : """Handles " cursor up " events"""
if self . historyPos > 0 : self . historyPos -= 1 clearLen = len ( self . inputBuffer ) self . inputBuffer = list ( self . history [ self . historyPos ] ) self . cursorPos = len ( self . inputBuffer ) self . _refreshInputPrompt ( clearLen )
def _mouse_handler ( self , cli , mouse_event ) : "Click callback ."
if mouse_event . event_type == MouseEventType . MOUSE_UP : self . on_click ( cli ) else : return NotImplemented
def run_opt ( self , popsize , numgen , processors , plot = False , log = False , ** kwargs ) : """Runs the optimizer . : param popsize : : param numgen : : param processors : : param plot : : param log : : param kwargs : : return :"""
self . _params [ 'popsize' ] = popsize self . _params [ 'numgen' ] = numgen self . _params [ 'processors' ] = processors self . _params [ 'plot' ] = plot self . _params [ 'log' ] = log # allows us to pass in additional arguments e . g . neighbours self . _params . update ( ** kwargs ) self . halloffame = tools . HallOf...
def slot_add_binding ( self , slot_number , adapter ) : """Adds a slot binding ( a module into a slot ) . : param slot _ number : slot number : param adapter : device to add in the corresponding slot"""
try : slot = self . _slots [ slot_number ] except IndexError : raise DynamipsError ( 'Slot {slot_number} does not exist on router "{name}"' . format ( name = self . _name , slot_number = slot_number ) ) if slot is not None : current_adapter = slot raise DynamipsError ( 'Slot {slot_number} is already occ...
def simple_tokenize ( name ) : """Simple tokenizer function to be used with the normalizers ."""
last_names , first_names = name . split ( ',' ) last_names = _RE_NAME_TOKEN_SEPARATOR . split ( last_names ) first_names = _RE_NAME_TOKEN_SEPARATOR . split ( first_names ) first_names = [ NameToken ( n ) if len ( n ) > 1 else NameInitial ( n ) for n in first_names if n ] last_names = [ NameToken ( n ) if len ( n ) > 1 ...
def _id_handler ( self , f ) : """Given a Feature from self . iterator , figure out what the ID should be . This uses ` self . id _ spec ` identify the ID ."""
# If id _ spec is a string , convert to iterable for later if isinstance ( self . id_spec , six . string_types ) : id_key = [ self . id_spec ] elif hasattr ( self . id_spec , '__call__' ) : id_key = [ self . id_spec ] # If dict , then assume it ' s a feature - > attribute mapping , e . g . , # { ' gene ' : ' ge...
def folderitem ( self , obj , item , index ) : """Service triggered each time an item is iterated in folderitems . The use of this service prevents the extra - loops in child objects . : obj : the instance of the class to be foldered : item : dict containing the properties of the object to be used by the te...
title = obj . Title ( ) description = obj . Description ( ) url = obj . absolute_url ( ) item [ "Description" ] = description item [ "replace" ] [ "Title" ] = get_link ( url , value = title ) retention_period = obj . getRetentionPeriod ( ) if retention_period : hours = retention_period [ "hours" ] minutes = ret...
def msg_err ( message ) : """Log an error message : param message : the message to be logged"""
to_stdout ( " !!! {message}" . format ( message = message ) , colorf = red , bold = True ) if _logger : _logger . error ( message )
def _GetOutputModulesInformation ( self ) : """Retrieves the output modules information . Returns : list [ tuple [ str , str ] ] : pairs of output module names and descriptions ."""
output_modules_information = [ ] for name , output_class in output_manager . OutputManager . GetOutputClasses ( ) : output_modules_information . append ( ( name , output_class . DESCRIPTION ) ) return output_modules_information
def internal_only ( view_func ) : """A view decorator which blocks access for requests coming through the load balancer ."""
@ functools . wraps ( view_func ) def wrapper ( request , * args , ** kwargs ) : forwards = request . META . get ( "HTTP_X_FORWARDED_FOR" , "" ) . split ( "," ) # The nginx in the docker container adds the loadbalancer IP to the list inside # X - Forwarded - For , so if the list contains more than a single ...
def run_analysis ( self , argv ) : """Run this analysis"""
args = self . _parser . parse_args ( argv ) if is_null ( args . config ) : raise ValueError ( "Config yaml file must be specified" ) if is_null ( args . rand_config ) : raise ValueError ( "Random direction config yaml file must be specified" ) config = load_yaml ( args . config ) rand_config = load_yaml ( args ...
def get_lines_without_comments ( filename : str ) -> List [ str ] : """Reads a file , and returns all lines as a list , left - and right - stripping the lines and removing everything on a line after the first ` ` # ` ` . NOTE : does not cope well with quoted ` ` # ` ` symbols !"""
lines = [ ] with open ( filename ) as f : for line in f : line = line . partition ( '#' ) [ 0 ] # the part before the first # line = line . rstrip ( ) line = line . lstrip ( ) if line : lines . append ( line ) return lines
def determine_final_freq ( base , direction , modifier ) : """Return integer for frequency ."""
result = 0 if direction == "+" : result = base + modifier elif direction == "-" : result = base - modifier return ( result )
def parse_declaration_expressn_fncall_SUBparams ( self , params ) : """Needs rearrangement : 0 1 2 WDL native params : sub ( input , pattern , replace ) 1 2 0 Python ' s re . sub ( ) params : sub ( pattern , replace , input ) : param params : : param es : : return :"""
# arguments passed to the function if isinstance ( params , wdl_parser . Terminal ) : raise NotImplementedError elif isinstance ( params , wdl_parser . Ast ) : raise NotImplementedError elif isinstance ( params , wdl_parser . AstList ) : assert len ( params ) == 3 , ( 'sub() function requires exactly 3 argu...
def decode_aes256_cbc_base64 ( data , encryption_key ) : """Decrypts base64 encoded AES - 256 CBC bytes ."""
if not data : return b'' else : # LastPass AES - 256 / CBC / base64 encryted string starts with an " ! " . # Next 24 bytes are the base64 encoded IV for the cipher . # Then comes the " | " . # And the rest is the base64 encoded encrypted payload . return decode_aes256 ( 'cbc' , decode_base64 ( data [ 1 : 25 ] )...
def crosscheck_query_vsiid_mac ( self , reply , vsiid , mac ) : """Cross Check the reply against the input vsiid , mac for get query ."""
vsiid_reply = reply . partition ( "uuid" ) [ 2 ] . split ( ) [ 0 ] [ 4 : ] if vsiid != vsiid_reply : fail_reason = vdp_const . vsi_mismatch_failure_reason % ( vsiid , vsiid_reply ) LOG . error ( "%s" , fail_reason ) return False , fail_reason mac_reply = reply . partition ( "filter" ) [ 2 ] . split ( '-' ) ...
def components ( self ) : """Return a dataframe of the components ( days , hours , minutes , seconds , milliseconds , microseconds , nanoseconds ) of the Timedeltas . Returns a DataFrame"""
from pandas import DataFrame columns = [ 'days' , 'hours' , 'minutes' , 'seconds' , 'milliseconds' , 'microseconds' , 'nanoseconds' ] hasnans = self . _hasnans if hasnans : def f ( x ) : if isna ( x ) : return [ np . nan ] * len ( columns ) return x . components else : def f ( x ) : ...
def s_info ( self , server = None ) : """Runs the INFO command on a server . Optional arguments : * server = None - Get INFO for server instead of the current server ."""
with self . lock : if not server : self . send ( 'INFO' ) else : self . send ( 'INFO %s' % server ) sinfo = [ ] while self . readable ( ) : msg = self . _recv ( expected_replies = ( '371' , '374' ) ) if msg [ 0 ] == '371' : sinfo . append ( ' ' . join ( msg [ ...
def leaveEvent ( self , event ) : """Reimplemented to start the hide timer ."""
super ( CallTipWidget , self ) . leaveEvent ( event ) self . _leave_event_hide ( )
def _get_hashed_params ( self , page_text ) : """Get hashed params which will be used when you login , see issue # 10"""
soup = BeautifulSoup ( page_text , 'html.parser' ) return [ tag [ 'name' ] for tag in soup . find_all ( 'input' , class_ = 'sl' ) ]
def create ( self , msgtype , * args , ** kwargs ) : '''Create a new Message instance for the given type . Args : msgtype ( str ) :'''
if msgtype not in self . _messages : raise ProtocolError ( "Unknown message type %r for protocol version %s" % ( msgtype , self . _version ) ) return self . _messages [ msgtype ] . create ( * args , ** kwargs )
def generate_setup_py ( target , source , env ) : """Generate the setup . py file for this distribution ."""
tile = env [ 'TILE' ] data = { } entry_points = { } for _mod , import_string , entry_point in iter_python_modules ( tile ) : if entry_point not in entry_points : entry_points [ entry_point ] = [ ] entry_points [ entry_point ] . append ( import_string ) data [ 'name' ] = tile . support_distribution data ...
def close_connection ( self , host ) : """close connection ( s ) to < host > host is the host : port spec , as in ' www . cnn . com : 8080 ' as passed in . no error occurs if there is no connection to that host ."""
for h in self . _cm . get_all ( host ) : self . _cm . remove ( h ) h . close ( )
def fetch_public_key ( repo ) : """Download RSA public key Travis will use for this repo . Travis API docs : http : / / docs . travis - ci . com / api / # repository - keys"""
keyurl = 'https://api.travis-ci.org/repos/{0}/key' . format ( repo ) data = json . loads ( urlopen ( keyurl ) . read ( ) ) if 'key' not in data : errmsg = "Could not find public key for repo: {}.\n" . format ( repo ) errmsg += "Have you already added your GitHub repo to Travis?" raise ValueError ( errmsg ) ...
def prox_l1 ( v , alpha ) : r"""Compute the proximal operator of the : math : ` \ ell _ 1 ` norm ( scalar shrinkage / soft thresholding ) . . math : : \ mathrm { prox } _ { \ alpha f } ( \ mathbf { v } ) = \ mathcal { S } _ { 1 , \ alpha } ( \ mathbf { v } ) = \ mathrm { sign } ( \ mathbf { v } ) \ odot \...
if have_numexpr : return ne . evaluate ( 'where(abs(v)-alpha > 0, where(v >= 0, 1, -1) * (abs(v)-alpha), 0)' ) else : return np . sign ( v ) * ( np . clip ( np . abs ( v ) - alpha , 0 , float ( 'Inf' ) ) )
def histogram ( self , buckets ) : """Compute a histogram using the provided buckets . The buckets are all open to the right except for the last which is closed . e . g . [ 1,10,20,50 ] means the buckets are [ 1,10 ) [ 10,20 ) [ 20,50 ] , which means 1 < = x < 10 , 10 < = x < 20 , 20 < = x < = 50 . And on the...
if isinstance ( buckets , int ) : if buckets < 1 : raise ValueError ( "number of buckets must be >= 1" ) # filter out non - comparable elements def comparable ( x ) : if x is None : return False if type ( x ) is float and isnan ( x ) : return False ret...
def object ( self , * args , ** kwargs ) : """Registers a class based router to this API"""
kwargs [ 'api' ] = self . api return Object ( * args , ** kwargs )
def dImage_wrt_2dVerts_bnd ( observed , visible , visibility , barycentric , image_width , image_height , num_verts , f , bnd_bool ) : """Construct a sparse jacobian that relates 2D projected vertex positions ( in the columns ) to pixel values ( in the rows ) . This can be done in two steps ."""
n_channels = np . atleast_3d ( observed ) . shape [ 2 ] shape = visibility . shape # Step 1 : get the structure ready , ie the IS and the JS IS = np . tile ( col ( visible ) , ( 1 , 2 * f . shape [ 1 ] ) ) . ravel ( ) JS = col ( f [ visibility . ravel ( ) [ visible ] ] . ravel ( ) ) JS = np . hstack ( ( JS * 2 , JS * 2...
def name ( self ) -> Optional [ str ] : """Returns name specified in Content - Disposition header or None if missed or header is malformed ."""
_ , params = parse_content_disposition ( self . headers . get ( CONTENT_DISPOSITION ) ) return content_disposition_filename ( params , 'name' )
def superReadCSV ( filepath , first_codec = 'UTF_8' , usecols = None , low_memory = False , dtype = None , parse_dates = True , sep = ',' , chunksize = None , verbose = False , ** kwargs ) : """A wrap to pandas read _ csv with mods to accept a dataframe or filepath . returns dataframe untouched , reads filepath a...
if isinstance ( filepath , pd . DataFrame ) : return filepath assert isinstance ( first_codec , str ) , "first_codec must be a string" codecs = [ 'UTF_8' , 'ISO-8859-1' , 'ASCII' , 'UTF_16' , 'UTF_32' ] try : codecs . remove ( first_codec ) except ValueError as not_in_list : pass codecs . insert ( 0 , first...
def Click ( cls ) : '''左键 点击 1次'''
element = cls . _element ( ) action = ActionChains ( Web . driver ) action . click ( element ) action . perform ( )
def diff ( compiled_requirements , installed_dists ) : """Calculate which packages should be installed or uninstalled , given a set of compiled requirements and a list of currently installed modules ."""
requirements_lut = { r . link or key_from_req ( r . req ) : r for r in compiled_requirements } satisfied = set ( ) # holds keys to_install = set ( ) # holds InstallRequirement objects to_uninstall = set ( ) # holds keys pkgs_to_ignore = get_dists_to_ignore ( installed_dists ) for dist in installed_dists : key = key...
def rotateTo ( self , angle ) : """rotates the image to a given angle Parameters : | angle - the angle that you want the image rotated to . | Positive numbers are clockwise , negative numbers are counter - clockwise"""
self . _transmogrophy ( angle , self . percent , self . scaleFromCenter , self . flipH , self . flipV )
def to_bytes ( self ) : '''Create bytes from properties'''
# Verify that the properties make sense self . sanitize ( ) # Write the next header type bitstream = BitStream ( 'uint:8=%d' % self . next_header ) # Write the header length header_length_unpadded = len ( self . data ) + 4 header_length = math . ceil ( header_length_unpadded / 8.0 ) bitstream += BitStream ( 'uint:8=%d'...
def image ( filename : str , width : int = None , height : int = None , justify : str = 'left' ) : """Adds an image to the display . The image must be located within the assets directory of the Cauldron notebook ' s folder . : param filename : Name of the file within the assets directory , : param width : ...
r = _get_report ( ) path = '/' . join ( [ 'reports' , r . project . uuid , 'latest' , 'assets' , filename ] ) r . append_body ( render . image ( path , width , height , justify ) ) r . stdout_interceptor . write_source ( '[ADDED] Image\n' )
def encode_to_json ( history_list ) : """Encodes this MarketHistoryList instance to a JSON string . : param MarketHistoryList history _ list : The history instance to serialize . : rtype : str"""
rowsets = [ ] for items_in_region_list in history_list . _history . values ( ) : region_id = items_in_region_list . region_id type_id = items_in_region_list . type_id generated_at = gen_iso_datetime_str ( items_in_region_list . generated_at ) rows = [ ] for entry in items_in_region_list . entries : ...
def value_predicate_to_type ( self , value_pred : str ) -> URIRef : """Convert a predicate in the form of " fhir : [ . . . ] . value [ type ] to fhir : type , covering the downshift on the first character if necessary : param value _ pred : Predicate associated with the value : return : corresponding type or ...
if value_pred . startswith ( 'value' ) : vp_datatype = value_pred . replace ( 'value' , '' ) if vp_datatype : if self . has_type ( FHIR [ vp_datatype ] ) : return FHIR [ vp_datatype ] else : vp_datatype = vp_datatype [ 0 ] . lower ( ) + vp_datatype [ 1 : ] if ...
def conj ( self , out = None ) : """Return the complex conjugate of ` ` self ` ` . Parameters out : ` NumpyTensor ` , optional Element to which the complex conjugate is written . Must be an element of ` ` self . space ` ` . Returns out : ` NumpyTensor ` The complex conjugate element . If ` ` out ` ` w...
if self . space . is_real : if out is None : return self else : out [ : ] = self return out if not is_numeric_dtype ( self . space . dtype ) : raise NotImplementedError ( '`conj` not defined for non-numeric ' 'dtype {}' . format ( self . dtype ) ) if out is None : return self . s...
def open_with_external_spyder ( self , text ) : """Load file in external Spyder ' s editor , if available This method is used only for embedded consoles ( could also be useful if we ever implement the magic % edit command )"""
match = get_error_match ( to_text_string ( text ) ) if match : fname , lnb = match . groups ( ) builtins . open_in_spyder ( fname , int ( lnb ) )
def set_options ( self , ** options ) : """Set options and handle deprecation ."""
ignore_etag = options . pop ( 'ignore_etag' , False ) disable = options . pop ( 'disable_collectfast' , False ) if ignore_etag : warnings . warn ( "--ignore-etag is deprecated since 0.5.0, use " "--disable-collectfast instead." ) if ignore_etag or disable : self . collectfast_enabled = False super ( Command , s...
def get_events ( self , service_location_id , appliance_id , start , end , max_number = None ) : """Request events for a given appliance Parameters service _ location _ id : int appliance _ id : int start : int | dt . datetime | pd . Timestamp end : int | dt . datetime | pd . Timestamp start and end sup...
start = self . _to_milliseconds ( start ) end = self . _to_milliseconds ( end ) url = urljoin ( URLS [ 'servicelocation' ] , service_location_id , "events" ) headers = { "Authorization" : "Bearer {}" . format ( self . access_token ) } params = { "from" : start , "to" : end , "applianceId" : appliance_id , "maxNumber" :...
def server_info ( self , verbose = False ) : '''Get information about the Opsview monitoring servers http : / / docs . opsview . com / doku . php ? id = opsview4.6 : restapi # server _ information'''
url = '{}/{}' . format ( self . rest_url , 'serverinfo' ) return self . __auth_req_get ( url , verbose = verbose )
def get_buildfile_path ( settings ) : """Path to which a build tarball should be downloaded ."""
base = os . path . basename ( settings . build_url ) return os . path . join ( BUILDS_ROOT , base )
def get_next_version ( self , increment = None ) : """Return the next version based on prior tagged releases ."""
increment = increment or self . increment return self . infer_next_version ( self . get_latest_version ( ) , increment )
def beacon ( config ) : '''Poll vmadm for changes'''
ret = [ ] # NOTE : lookup current images current_vms = __salt__ [ 'vmadm.list' ] ( keyed = True , order = 'uuid,state,alias,hostname,dns_domain' , ) # NOTE : apply configuration if VMADM_STATE [ 'first_run' ] : log . info ( 'Applying configuration for vmadm beacon' ) _config = { } list ( map ( _config . upd...
def convert_merge ( builder , layer , input_names , output_names , keras_layer ) : """Convert concat layer from keras to coreml . Parameters keras _ layer : layer A keras layer object . builder : NeuralNetworkBuilder A neural network builder object ."""
# Get input and output names output_name = output_names [ 0 ] mode = _get_elementwise_name_from_keras_layer ( keras_layer ) builder . add_elementwise ( name = layer , input_names = input_names , output_name = output_name , mode = mode )
def _using_stdout ( self ) : """Return whether the handler is using sys . stdout ."""
if WINDOWS and colorama : # Then self . stream is an AnsiToWin32 object . return self . stream . wrapped is sys . stdout return self . stream is sys . stdout
async def close ( self ) -> None : """Explicit exit . Close wallet ( and delete if so configured ) ."""
LOGGER . debug ( 'Wallet.close >>>' ) if not self . handle : LOGGER . warning ( 'Abstaining from closing wallet %s: already closed' , self . name ) else : LOGGER . debug ( 'Closing wallet %s' , self . name ) await wallet . close_wallet ( self . handle ) self . _handle = None if self . auto_remove : ...
def place_left_top ( window , width = None , height = None ) : """Places window in top left corner of screen . Arguments : window - - a QWidget width = None - - window width , in case you want to change it ( if not passed , not changed ) height = None - - window height , in case you want to change it ( if n...
if width is None : width = window . width ( ) if height is None : height = window . height ( ) window . setGeometry ( _DESKTOP_OFFSET_LEFT , _DESKTOP_OFFSET_TOP , width , height )
def get_template ( self ) : """Get the : attr : ` template < Page . template > ` of this page if defined or the closer parent ' s one if defined or : attr : ` pages . settings . PAGE _ DEFAULT _ TEMPLATE ` otherwise ."""
if self . template : return self . template template = None for p in self . get_ancestors ( ascending = True ) : if p . template : template = p . template break if not template : template = settings . PAGE_DEFAULT_TEMPLATE return template
def conform ( self , frame , axis = 'items' ) : """Conform input DataFrame to align with chosen axis pair . Parameters frame : DataFrame axis : { ' items ' , ' major ' , ' minor ' } Axis the input corresponds to . E . g . , if axis = ' major ' , then the frame ' s columns would be items , and the index wo...
axes = self . _get_plane_axes ( axis ) return frame . reindex ( ** self . _extract_axes_for_slice ( self , axes ) )
def _get_linear_lookup_table_and_weight ( nbits , wp ) : """Generate a linear lookup table . : param nbits : int Number of bits to represent a quantized weight value : param wp : numpy . array Weight blob to be quantized Returns lookup _ table : numpy . array Lookup table of shape ( 2 ^ nbits , ) qw...
w = wp . reshape ( 1 , - 1 ) qw , scales , biases = _quantize_channelwise_linear ( w , nbits , axis = 0 ) indices = _np . array ( range ( 0 , 2 ** nbits ) ) lookup_table = indices * scales [ 0 ] + biases [ 0 ] return lookup_table , qw
def getNextTimeout ( self ) : """Returns the next internal timeout that libusb needs to handle , in seconds , or None if no timeout is needed . You should not have to call this method , unless you are integrating this class with a polling mechanism ."""
timeval = libusb1 . timeval ( ) result = libusb1 . libusb_get_next_timeout ( self . __context_p , byref ( timeval ) ) if result == 0 : return None elif result == 1 : return timeval . tv_sec + ( timeval . tv_usec * 0.000001 ) raiseUSBError ( result )
def create_pairwise_bilateral ( sdims , schan , img , chdim = - 1 ) : """Util function that create pairwise bilateral potentials . This works for all image dimensions . For the 2D case does the same as ` DenseCRF2D . addPairwiseBilateral ` . Parameters sdims : list or tuple The scaling factors per dimensi...
# Put channel dim in right position if chdim == - 1 : # We don ' t have a channel , add a new axis im_feat = img [ np . newaxis ] . astype ( np . float32 ) else : # Put the channel dim as axis 0 , all others stay relatively the same im_feat = np . rollaxis ( img , chdim ) . astype ( np . float32 ) # scale image...
def load_from_stream ( self , var ) : """Populate the Variable from an NCStream object ."""
dims = [ ] for d in var . shape : dim = Dimension ( None , d . name ) dim . load_from_stream ( d ) dims . append ( dim ) self . dimensions = tuple ( dim . name for dim in dims ) self . shape = tuple ( dim . size for dim in dims ) self . ndim = len ( var . shape ) self . _unpack_attrs ( var . atts ) data , d...
def config ( self ) -> dict : """Get the scheduling object config ."""
# Check that the key exists self . _check_object_exists ( ) config_dict = DB . get_hash_dict ( self . key ) for _ , value in config_dict . items ( ) : for char in [ '[' , '{' ] : if char in value : value = ast . literal_eval ( value ) return config_dict
def count_end ( teststr , testchar ) : """Count instances of testchar at end of teststr ."""
count = 0 x = len ( teststr ) - 1 while x >= 0 and teststr [ x ] == testchar : count += 1 x -= 1 return count
def threshold ( self , data , recall_weight = 1.5 ) : # pragma : no cover """Returns the threshold that maximizes the expected F score , a weighted average of precision and recall for a sample of data . Arguments : data - - Dictionary of records , where the keys are record _ ids and the values are diction...
blocked_pairs = self . _blockData ( data ) return self . thresholdBlocks ( blocked_pairs , recall_weight )
def objects ( self ) : """Returns a list of objects with this Tag . This list may contain any taggable object type ."""
data = self . _get_raw_objects ( ) return PaginatedList . make_paginated_list ( data , self . _client , TaggedObjectProxy , page_url = type ( self ) . api_endpoint . format ( ** vars ( self ) ) )
def do_define ( self , t ) : """Default handling of a # define line ."""
_ , name , args , expansion = t try : expansion = int ( expansion ) except ( TypeError , ValueError ) : pass if args : evaluator = FunctionEvaluator ( name , args [ 1 : - 1 ] , expansion ) self . cpp_namespace [ name ] = evaluator else : self . cpp_namespace [ name ] = expansion
def split ( self , frac ) : """Split the DataFrame into two DataFrames with certain ratio . : param frac : Split ratio : type frac : float : return : two split DataFrame objects : rtype : list [ DataFrame ]"""
from . . import preprocess split_obj = getattr ( preprocess , '_Split' ) ( fraction = frac ) return split_obj . transform ( self )
def check_outdated ( package , version ) : """Given the name of a package on PyPI and a version ( both strings ) , checks if the given version is the latest version of the package available . Returns a 2 - tuple ( is _ outdated , latest _ version ) where is _ outdated is a boolean which is True if the given v...
from pkg_resources import parse_version parsed_version = parse_version ( version ) latest = None with utils . cache_file ( package , 'r' ) as f : content = f . read ( ) if content : # in case cache _ file fails and so f is a dummy file latest , cache_dt = json . loads ( content ) if not utils . ...
def get_table ( name , table , table_file , ** kwargs ) : '''Retrieve data from a Junos device using Tables / Views name ( required ) task definition table ( required ) Name of PyEZ Table file YAML file that has the table specified in table parameter path : Path of location of the YAML file . defa...
ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' } ret [ 'changes' ] = __salt__ [ 'junos.get_table' ] ( table , table_file , ** kwargs ) return ret