signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def set_sub_stream_format ( self , format , callback = None ) :
'''Set the stream fromat of sub stream ? ? ? ?''' | params = { 'format' : format }
return self . execute_command ( 'setSubStreamFormat' , params , callback = callback ) |
def delete_subscription ( self , subscription_id ) :
"""Unsubscribe , delete the relationship of the customer with the plan .
Args :
subscription _ id : Identification of the subscription .
Returns :""" | return self . client . _delete ( self . url + 'subscriptions/{}' . format ( subscription_id ) , headers = self . get_headers ( ) ) |
def comment_unvote ( self , comment_id ) :
"""Lets you unvote a specific comment ( Requires login ) .
Parameters :
comment _ id ( int ) :""" | return self . _get ( 'posts/{0}/unvote.json' . format ( comment_id ) , method = 'POST' , auth = True ) |
def read_hlet_wcs ( filename , ext ) :
"""Insure ` stwcs . wcsutil . HSTWCS ` includes all attributes of a full image WCS .
For headerlets , the WCS does not contain information about the size of the
image , as the image array is not present in the headerlet .""" | hstwcs = wcsutil . HSTWCS ( filename , ext = ext )
if hstwcs . naxis1 is None :
hstwcs . naxis1 = int ( hstwcs . wcs . crpix [ 0 ] * 2. )
# Assume crpix is center of chip
hstwcs . naxis2 = int ( hstwcs . wcs . crpix [ 1 ] * 2. )
return hstwcs |
def set_group_type ( self , group , bulb_type ) :
"""Set bulb type for specified group .
Group must be int between 1 and 4.
Type must be " rgbw " or " white " .
Alternatively , use constructor keywords group _ 1 , group _ 2 etc . to set bulb types .""" | if bulb_type not in ( "rgbw" , "white" ) :
raise AttributeError ( "Bulb type must be either rgbw or white" )
self . group [ group ] = bulb_type
self . has_white = "white" in self . group . values ( )
self . has_rgbw = "rgbw" in self . group . values ( ) |
def dirname ( self , path ) :
"""Returns the full path to the parent directory of the specified
file path .""" | if self . is_ssh ( path ) :
remotepath = self . _get_remote ( path )
remotedir = os . path . dirname ( remotepath )
return self . _get_tramp_path ( remotedir )
else :
return os . path . dirname ( path ) |
def get_queryset ( self ) :
"""Get the queryset for the action .
If action is read action , return a CachedQueryset
Otherwise , return a Django queryset""" | queryset = super ( CachedViewMixin , self ) . get_queryset ( )
if self . action in ( 'list' , 'retrieve' ) :
return CachedQueryset ( self . get_queryset_cache ( ) , queryset = queryset )
else :
return queryset |
def _read_data ( path ) :
"""Read Rdump output and transform to Python dictionary .
Parameters
path : str
Returns
Dict
key , values pairs from Rdump formatted data .""" | data = { }
with open ( path , "r" ) as f_obj :
var = ""
for line in f_obj :
if "<-" in line :
if len ( var ) :
key , var = _process_data_var ( var )
data [ key ] = var
var = ""
var += " " + line . strip ( )
if len ( var ) :
key ... |
def match_class_glob ( _class , saltclass_path ) :
'''Takes a class name possibly including ` * ` or ` ? ` wildcards ( or any other wildcards supportet by ` glob . glob ` ) and
returns a list of expanded class names without wildcards .
. . code - block : : python
classes = match _ class _ glob ( ' services . ... | straight , sub_init , sub_straight = get_class_paths ( _class , saltclass_path )
classes = [ ]
matches = [ ]
matches . extend ( glob . glob ( straight ) )
matches . extend ( glob . glob ( sub_straight ) )
matches . extend ( glob . glob ( sub_init ) )
if not matches :
log . warning ( '%s: Class globbing did not yiel... |
def _process_data ( self , src_key , limit = None ) :
"""This function will process the data files from Coriell .
We make the assumption that any alleles listed are variants
( alternates to w . t . )
Triples : ( examples )
: NIGMSrepository a CLO _ 000008 # repository
label : NIGMS Human Genetic Cell Repo... | raw = '/' . join ( ( self . rawdir , self . files [ src_key ] [ 'file' ] ) )
LOG . info ( "Processing Data from %s" , raw )
if self . test_mode : # set the graph to build
graph = self . testgraph
else :
graph = self . graph
family = Family ( graph )
model = Model ( graph )
line_counter = 1
geno = Genotype ( gra... |
def do_enable ( ) :
"""Uncomment any lines that start with # import in the . pth file""" | try :
_lines = [ ]
with open ( vext_pth , mode = 'r' ) as f :
for line in f . readlines ( ) :
if line . startswith ( '#' ) and line [ 1 : ] . lstrip ( ) . startswith ( 'import ' ) :
_lines . append ( line [ 1 : ] . lstrip ( ) )
else :
_lines . appe... |
def _render_picking ( self , ** kwargs ) :
"""Render the scene in picking mode , returning a 2D array of visual
IDs .""" | try :
self . _scene . picking = True
img = self . render ( bgcolor = ( 0 , 0 , 0 , 0 ) , ** kwargs )
finally :
self . _scene . picking = False
img = img . astype ( 'int32' ) * [ 2 ** 0 , 2 ** 8 , 2 ** 16 , 2 ** 24 ]
id_ = img . sum ( axis = 2 ) . astype ( 'int32' )
return id_ |
def _get_tcpip_interface_info ( interface ) :
'''return details about given tcpip interface''' | base_information = _get_base_interface_info ( interface )
if base_information [ 'ipv4' ] [ 'requestmode' ] == 'static' :
settings = _load_config ( interface . name , [ 'IP_Address' , 'Subnet_Mask' , 'Gateway' , 'DNS_Address' ] )
base_information [ 'ipv4' ] [ 'address' ] = settings [ 'IP_Address' ]
base_info... |
def rez_bin_path ( self ) :
"""Get path containing rez binaries , or None if no binaries are
available , or Rez is not a production install .""" | binpath = None
if sys . argv and sys . argv [ 0 ] :
executable = sys . argv [ 0 ]
path = which ( "rezolve" , env = { "PATH" : os . path . dirname ( executable ) , "PATHEXT" : os . environ . get ( "PATHEXT" , "" ) } )
binpath = os . path . dirname ( path ) if path else None
# TODO : improve this , could stil... |
def flatten ( dictionary , separator = '.' , prefix = '' ) :
"""Flatten the dictionary keys are separated by separator
Arguments :
dictionary { dict } - - The dictionary to be flattened .
Keyword Arguments :
separator { str } - - The separator to use ( default is ' . ' ) . It will
crush items with key con... | new_dict = { }
for key , value in dictionary . items ( ) :
new_key = prefix + separator + key if prefix else key
if isinstance ( value , collections . MutableMapping ) :
new_dict . update ( flatten ( value , separator , new_key ) )
elif isinstance ( value , list ) :
new_value = [ ]
f... |
def get_audits ( ) :
"""Get OS hardening sysctl audits .
: returns : dictionary of audits""" | audits = [ ]
settings = utils . get_settings ( 'os' )
# Apply the sysctl settings which are configured to be applied .
audits . append ( SysctlConf ( ) )
# Make sure that only root has access to the sysctl . conf file , and
# that it is read - only .
audits . append ( FilePermissionAudit ( '/etc/sysctl.conf' , user = '... |
def stop_event ( self ) :
"""Called by the event loop when it is stopped .
Calls : py : meth : ` on _ stop ` , then sends : py : data : ` None ` to each
output to shut down the rest of the processing pipeline .""" | self . logger . debug ( 'stopping' )
try :
self . on_stop ( )
except Exception as ex :
self . logger . exception ( ex )
for name in self . outputs :
self . send ( name , None ) |
def _handle_config ( self , data ) :
"""Handles received configuration data .
: param data : Configuration string to parse
: type data : string""" | _ , config_string = data . split ( '>' )
for setting in config_string . split ( '&' ) :
key , val = setting . split ( '=' )
if key == 'ADDRESS' :
self . address = int ( val )
elif key == 'CONFIGBITS' :
self . configbits = int ( val , 16 )
elif key == 'MASK' :
self . address_mask ... |
def get_ao_chans ( dev ) :
"""Discover and return a list of the names of all analog output channels for the given device
: param dev : the device name
: type dev : str""" | buf = create_string_buffer ( 256 )
buflen = c_uint32 ( sizeof ( buf ) )
DAQmxGetDevAOPhysicalChans ( dev . encode ( ) , buf , buflen )
pybuf = buf . value
chans = pybuf . decode ( u'utf-8' ) . split ( u"," )
return chans |
def process_item_nodes ( app , doctree , fromdocname ) :
"""This function should be triggered upon ` ` doctree - resolved event ` `
Replace all item _ list nodes with a list of the collected items .
Augment each item with a backlink to the original location .""" | env = app . builder . env
all_items = sorted ( env . traceability_all_items , key = naturalsortkey )
# Item matrix :
# Create table with related items , printing their target references .
# Only source and target items matching respective regexp shall be included
for node in doctree . traverse ( item_matrix ) :
tab... |
def ensure_security_header ( envelope , queue ) :
"""Insert a security XML node if it doesn ' t exist otherwise update it .""" | ( header , ) = HEADER_XPATH ( envelope )
security = SECURITY_XPATH ( header )
if security :
for timestamp in TIMESTAMP_XPATH ( security [ 0 ] ) :
queue . push_and_mark ( timestamp )
return security [ 0 ]
else :
nsmap = { 'wsu' : ns . wsuns [ 1 ] , 'wsse' : ns . wssens [ 1 ] , }
return _create_el... |
def execute ( self , input_data ) :
'''Execute the Unzip worker''' | raw_bytes = input_data [ 'sample' ] [ 'raw_bytes' ]
zipfile_output = zipfile . ZipFile ( StringIO ( raw_bytes ) )
payload_md5s = [ ]
for name in zipfile_output . namelist ( ) :
filename = os . path . basename ( name )
payload_md5s . append ( self . workbench . store_sample ( zipfile_output . read ( name ) , nam... |
def entry_index ( request , limit = 0 , template = 'djournal/entry_index.html' ) :
'''Returns a reponse of a fixed number of entries ; all of them , by default .''' | entries = Entry . public . all ( )
if limit > 0 :
entries = entries [ : limit ]
context = { 'entries' : entries , }
return render_to_response ( template , context , context_instance = RequestContext ( request ) , ) |
def peak_interval ( data , alpha = _alpha , npoints = _npoints ) :
"""Identify interval using Gaussian kernel density estimator .""" | peak = kde_peak ( data , npoints )
x = np . sort ( data . flat ) ;
n = len ( x )
# The number of entries in the interval
window = int ( np . rint ( ( 1.0 - alpha ) * n ) )
# The start , stop , and width of all possible intervals
starts = x [ : n - window ] ;
ends = x [ window : ]
widths = ends - starts
# Just the inter... |
def color_hex_to_dec_tuple ( color ) :
"""Converts a color from hexadecimal to decimal tuple , color can be in
the following formats : 3 - digit RGB , 4 - digit ARGB , 6 - digit RGB and
8 - digit ARGB .""" | assert len ( color ) in [ 3 , 4 , 6 , 8 ]
if len ( color ) in [ 3 , 4 ] :
color = "" . join ( [ c * 2 for c in color ] )
n = int ( color , 16 )
t = ( ( n >> 16 ) & 255 , ( n >> 8 ) & 255 , n & 255 )
if len ( color ) == 8 :
t = t + ( ( n >> 24 ) & 255 , )
return t |
def putlogo ( figure = None ) :
"""Puts the CREDO logo at the bottom right of the current figure ( or
the figure given by the ` ` figure ` ` argument if supplied ) .""" | ip = get_ipython ( )
if figure is None :
figure = plt . gcf ( )
curraxis = figure . gca ( )
logoaxis = figure . add_axes ( [ 0.89 , 0.01 , 0.1 , 0.1 ] , anchor = 'NW' )
logoaxis . set_axis_off ( )
logoaxis . xaxis . set_visible ( False )
logoaxis . yaxis . set_visible ( False )
logoaxis . imshow ( credo_logo )
figu... |
def _evaluate ( self , R , z , phi = 0. , t = 0. ) :
"""NAME :
_ evaluate
PURPOSE :
evaluate the potential at ( R , z )
INPUT :
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT :
potential at ( R , z )
HISTORY :
2016-05-09 - Written - Aladdin""" | return - self . _denom ( R , z ) ** - 0.5 |
def fill_key_info ( self , key_info , signature_method ) :
"""Fills the KeyInfo node
: param key _ info : KeyInfo node
: type key _ info : lxml . etree . Element
: param signature _ method : Signature node to use
: type signature _ method : str
: return : None""" | x509_data = key_info . find ( 'ds:X509Data' , namespaces = constants . NS_MAP )
if x509_data is not None :
self . fill_x509_data ( x509_data )
key_name = key_info . find ( 'ds:KeyName' , namespaces = constants . NS_MAP )
if key_name is not None and self . key_name is not None :
key_name . text = self . key_name... |
def parse_delay_import_directory ( self , rva , size ) :
"""Walk and parse the delay import directory .""" | import_descs = [ ]
error_count = 0
while True :
try : # If the RVA is invalid all would blow up . Some PEs seem to be
# specially nasty and have an invalid RVA .
data = self . get_data ( rva , Structure ( self . __IMAGE_DELAY_IMPORT_DESCRIPTOR_format__ ) . sizeof ( ) )
except PEFormatError as e :
... |
def process_route_spec_config ( con , vpc_info , route_spec , failed_ips , questionable_ips ) :
"""Look through the route spec and update routes accordingly .
Idea : Make sure we have a route for each CIDR .
If we have a route to any of the IP addresses for a given CIDR then we are
good . Otherwise , pick one... | if CURRENT_STATE . _stop_all :
logging . debug ( "Routespec processing. Stop requested, abort operation" )
return
if failed_ips :
logging . debug ( "Route spec processing. Failed IPs: %s" % "," . join ( failed_ips ) )
else :
logging . debug ( "Route spec processing. No failed IPs." )
# Iterate over all ... |
def linkcode_resolve ( domain , info ) :
"""Determine the URL corresponding to Python object on GitHub
This code is derived from the version used by ` Numpy
< https : / / github . com / numpy / numpy / blob / v1.9.2 / doc / source / conf . py # L286 > ` _ .""" | # Only link to Python source
if domain != 'py' :
return None
# Get a reference to the object in question
modname = info [ 'module' ]
fullname = info [ 'fullname' ]
submod = sys . modules . get ( modname )
if submod is None :
return None
obj = submod
for part in fullname . split ( '.' ) :
try :
obj =... |
def add_string_widget ( self , ref , text = "Text" , x = 1 , y = 1 ) :
"""Add String Widget""" | if ref not in self . widgets :
widget = widgets . StringWidget ( screen = self , ref = ref , text = text , x = x , y = y )
self . widgets [ ref ] = widget
return self . widgets [ ref ] |
async def delete ( self , key , namespace = None , _conn = None ) :
"""Deletes the given key .
: param key : Key to be deleted
: param namespace : str alternative namespace to use
: param timeout : int or float in seconds specifying maximum timeout
for the operations to last
: returns : int number of dele... | start = time . monotonic ( )
ns_key = self . build_key ( key , namespace = namespace )
ret = await self . _delete ( ns_key , _conn = _conn )
logger . debug ( "DELETE %s %d (%.4f)s" , ns_key , ret , time . monotonic ( ) - start )
return ret |
def _match_objects_against_atlas_footprint ( self , orbfitEph , ra , dec ) :
"""* match the orbfit generated object positions against atlas exposure footprint *
* * Key Arguments : * *
- ` ` orbfitEph ` ` - - the orbfit ephemerides
- ` ` ra ` ` - - the ATLAS exposure RA ( degrees )
- ` ` dec ` ` - - the ATL... | self . log . info ( 'starting the ``_match_objects_against_atlas_footprint`` method' )
# GET THE ORBFIT MAG LIMIT
magLimit = float ( self . settings [ "orbfit" ] [ "magnitude limit" ] )
tileSide = float ( self . settings [ "orbfit" ] [ "atlas exposure match side" ] )
pi = ( 4 * math . atan ( 1.0 ) )
DEG_TO_RAD_FACTOR =... |
def isValidFeatureWriter ( klass ) :
"""Return True if ' klass ' is a valid feature writer class .
A valid feature writer class is a class ( of type ' type ' ) , that has
two required attributes :
1 ) ' tableTag ' ( str ) , which can be " GSUB " , " GPOS " , or other similar tags .
2 ) ' write ' ( bound met... | if not isclass ( klass ) :
logger . error ( "%r is not a class" , klass )
return False
if not hasattr ( klass , "tableTag" ) :
logger . error ( "%r does not have required 'tableTag' attribute" , klass )
return False
if not hasattr ( klass , "write" ) :
logger . error ( "%r does not have a required '... |
def download_to_stream_by_name ( self , filename , destination , revision = - 1 , session = None ) :
"""Write the contents of ` filename ` ( with optional ` revision ` ) to
` destination ` .
For example : :
my _ db = MongoClient ( ) . test
fs = GridFSBucket ( my _ db )
# Get file to write to
file = open... | with self . open_download_stream_by_name ( filename , revision , session = session ) as gout :
for chunk in gout :
destination . write ( chunk ) |
def has_c_library ( library , extension = ".c" ) :
"""Check whether a C / C + + library is available on the system to the compiler .
Parameters
library : str
The library we want to check for e . g . if we are interested in FFTW3 , we
want to check for ` fftw3 . h ` , so this parameter will be ` fftw3 ` .
... | with tempfile . TemporaryDirectory ( dir = "." ) as directory :
name = join ( directory , "%s%s" % ( library , extension ) )
with open ( name , "w" ) as f :
f . write ( "#include <%s.h>\n" % library )
f . write ( "int main() {}\n" )
# Get a compiler instance
compiler = ccompiler . new_co... |
def split_on ( s , sep = " " ) :
"""Split s by sep , unless it ' s inside a quote .""" | pattern = '''((?:[^%s"']|"[^"]*"|'[^']*')+)''' % sep
return [ _strip_speechmarks ( t ) for t in re . split ( pattern , s ) [ 1 : : 2 ] ] |
def from_string ( cls , s ) :
"""Decode from the YY token lattice format .""" | def _qstrip ( s ) :
return s [ 1 : - 1 ]
# remove assumed quote characters
tokens = [ ]
for match in _yy_re . finditer ( s ) :
d = match . groupdict ( )
lnk , pos = None , [ ]
if d [ 'lnkfrom' ] is not None :
lnk = Lnk . charspan ( d [ 'lnkfrom' ] , d [ 'lnkto' ] )
if d [ 'pos' ] is not ... |
def restrict_dates ( feed : "Feed" , dates : List [ str ] ) -> List [ str ] :
"""Given a " Feed " and a date ( YYYYMMDD string ) or list of dates ,
coerce the date / dates into a list and drop the dates not in
` ` feed . get _ dates ( ) ` ` , preserving the original order of ` ` dates ` ` .
Intended as a help... | # Coerce string to set
if isinstance ( dates , str ) :
dates = [ dates ]
# Restrict
return [ d for d in dates if d in feed . get_dates ( ) ] |
def get_maxdays ( name ) :
'''Get the maximum age of the password
: param str name : The username of the account
: return : The maximum age of the password in days
: rtype : int
: raises : CommandExecutionError on user not found or any other unknown error
CLI Example :
. . code - block : : bash
salt '... | policies = _get_account_policy ( name )
if 'maxMinutesUntilChangePassword' in policies :
max_minutes = policies [ 'maxMinutesUntilChangePassword' ]
return int ( max_minutes ) / 24 / 60
return 0 |
def get_stp_mst_detail_output_msti_port_internal_path_cost ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_stp_mst_detail = ET . Element ( "get_stp_mst_detail" )
config = get_stp_mst_detail
output = ET . SubElement ( get_stp_mst_detail , "output" )
msti = ET . SubElement ( output , "msti" )
instance_id_key = ET . SubElement ( msti , "instance-id" )
instance_id_key . text = kwargs . pop... |
def _request ( self , path , method , body = None ) :
"Base request function" | h = httplib2 . Http ( )
resp , content = h . request ( self . base_url + path , method , body = json . dumps ( body ) , )
if resp [ 'status' ] == "200" :
return json . loads ( content )
else :
raise IOError ( "Got %s reponse from server (%s)" % ( resp [ 'status' ] , content , ) ) |
def delete_by_id ( self , del_id ) :
'''Delete a link by id .''' | if self . check_post_role ( ) [ 'DELETE' ] :
pass
else :
return False
if self . is_p :
if MLink . delete ( del_id ) :
output = { 'del_link' : 1 }
else :
output = { 'del_link' : 0 }
return json . dump ( output , self )
else :
is_deleted = MLink . delete ( del_id )
if is_delete... |
def updatePSL ( psl_file = PSLFILE ) :
"""Updates a local copy of PSL file
: param psl _ file : path for the file to store the list . Default : PSLFILE""" | if requests is None :
raise Exception ( "Please install python-requests http(s) library. $ sudo pip install requests" )
r = requests . get ( PSLURL )
if r . status_code != requests . codes . ok or len ( r . content ) == 0 :
raise Exception ( "Could not download PSL from " + PSLURL )
lastmod = r . headers . get ... |
def _snippet_ranges ( cls , num_src_lines , violation_lines ) :
"""Given the number of source file lines and list of
violation line numbers , return a list of snippet
ranges of the form ` ( start _ line , end _ line ) ` .
Each snippet contains a few extra lines of context
before / after the first / last vio... | current_range = ( None , None )
lines_since_last_violation = 0
snippet_ranges = [ ]
for line_num in range ( 1 , num_src_lines + 1 ) : # If we have not yet started a snippet ,
# check if we can ( is this line a violation ? )
if current_range [ 0 ] is None :
if line_num in violation_lines : # Expand to includ... |
def fillna ( self , ** kwargs ) :
"""Replaces NaN values with the method provided .
Returns :
A new QueryCompiler with null values filled .""" | axis = kwargs . get ( "axis" , 0 )
value = kwargs . get ( "value" )
if isinstance ( value , dict ) :
value = kwargs . pop ( "value" )
if axis == 0 :
index = self . columns
else :
index = self . index
value = { idx : value [ key ] for key in value for idx in index . get_indexer_for ( [ ke... |
def mean_absolute_deviation ( df , col_true , col_pred = None ) :
"""Compute mean absolute deviation ( MAD ) of a predicted DataFrame .
Note that this method will trigger the defined flow to execute .
: param df : predicted data frame
: type df : DataFrame
: param col _ true : column name of true value
: ... | if not col_pred :
col_pred = get_field_name_by_role ( df , FieldRole . PREDICTED_VALUE )
return _run_evaluation_node ( df , col_true , col_pred ) [ 'mad' ] |
def fetchmany ( self , size = None ) :
"""Fetch several rows""" | self . _check_executed ( )
if self . _rows is None :
return ( )
end = self . rownumber + ( size or self . arraysize )
result = self . _rows [ self . rownumber : end ]
self . rownumber = min ( end , len ( self . _rows ) )
return result |
def get_stream ( data = None ) :
"""Get a MemoryStream instance .
Args :
data ( bytes , bytearray , BytesIO ) : ( Optional ) data to create the stream from .
Returns :
MemoryStream : instance .""" | if len ( __mstreams_available__ ) == 0 :
if data :
mstream = MemoryStream ( data )
mstream . seek ( 0 )
else :
mstream = MemoryStream ( )
__mstreams__ . append ( mstream )
return mstream
mstream = __mstreams_available__ . pop ( )
if data is not None and len ( data ) :
mstream... |
def from_triples ( cls , triples , remap_nodeids = True ) :
"""Decode triples , as from : meth : ` to _ triples ` , into a Dmrs object .""" | top_nid = str ( LTOP_NODEID )
top = lnk = surface = identifier = None
nids , nd , edges = [ ] , { } , [ ]
for src , rel , tgt in triples :
src , tgt = str ( src ) , str ( tgt )
# hack for int - converted src / tgt
if src == top_nid and rel == 'top' :
top = tgt
continue
elif src not in nd... |
def file_sizes ( self ) :
"""Returns total filesize ( in MB )""" | size = sum ( map ( os . path . getsize , self . file_list ) )
return size / 1024 / 1024 |
def rest_action ( self , func , url , ** kwargs ) :
"""Routine to do low - level REST operation , with retry .
Args :
func ( callable ) : API function to call
url ( str ) : service URL endpoint
kwargs ( dict ) : addition parameters
Raises :
requests . RequestException : Exception connection error
Valu... | try :
response = func ( url , timeout = self . TIMEOUT , ** kwargs )
except requests . RequestException , err :
log . exception ( "[PyLmod] Error - connection error in " "rest_action, err=%s" , err )
raise err
try :
return response . json ( )
except ValueError , err :
log . exception ( 'Unable to de... |
def get_capacity ( self , legacy = None ) :
"""Get capacity of all facilities .
: param legacy : Indicate set of server types to include in response
Validation of ` legacy ` is left to the packet api to avoid going out of date if any new value is introduced .
The currently known values are :
- only ( curren... | params = None
if legacy :
params = { 'legacy' : legacy }
return self . call_api ( '/capacity' , params = params ) [ 'capacity' ] |
def _compat_inet_pton ( family , addr ) :
"""socket . inet _ pton for platforms that don ' t have it""" | if family == socket . AF_INET : # inet _ aton accepts some strange forms , so we use our own
res = _compat_bytes ( '' )
parts = addr . split ( '.' )
if len ( parts ) != 4 :
raise ValueError ( 'Expected 4 dot-separated numbers' )
for part in parts :
intval = int ( part , 10 )
if i... |
def base0_interval_for_variant_fields ( base1_location , ref , alt ) :
"""Inteval of interbase offsets of the affected reference positions for a
particular variant ' s primary fields ( pos , ref , alt ) .
Parameters
base1 _ location : int
First reference nucleotide of variant or , for insertions , the base ... | if len ( ref ) == 0 : # in interbase coordinates , the insertion happens
# at the same start / end offsets , since those are already between
# reference bases . Furthermore , since the convention for base - 1
# coordinates is to locate the insertion * after * the position ,
# in this case the interbase and base - 1 pos... |
def analysisJWT ( self , token ) :
"""解析token , 返回解码后的header 、 payload 、 signature等""" | _header , _payload , _signature = token . split ( "." )
data = { "header" : json . loads ( base64 . urlsafe_b64decode ( str ( _header ) ) ) , "payload" : json . loads ( base64 . urlsafe_b64decode ( str ( _payload ) ) ) , "signature" : base64 . urlsafe_b64decode ( str ( _signature ) ) }
logging . debug ( "analysis token... |
def set_naming_params ( self , autonaming = None , prefix = None , suffix = None , name = None ) :
"""Setups processes naming parameters .
: param bool autonaming : Automatically set process name to something meaningful .
Generated process names may be ' uWSGI Master ' , ' uWSGI Worker # ' , etc .
: param str... | self . _set ( 'auto-procname' , autonaming , cast = bool )
self . _set ( 'procname-prefix%s' % ( '-spaced' if prefix and prefix . endswith ( ' ' ) else '' ) , prefix )
self . _set ( 'procname-append' , suffix )
self . _set ( 'procname' , name )
return self . _section |
def download ( tickers , start = None , end = None , actions = False , threads = False , group_by = 'column' , auto_adjust = False , progress = True , period = "max" , interval = "1d" , prepost = False , ** kwargs ) :
"""Download yahoo tickers
: Parameters :
tickers : str , list
List of tickers to download
... | global _PROGRESS_BAR , _DFS
# create ticker list
tickers = tickers if isinstance ( tickers , list ) else tickers . split ( )
if progress :
_PROGRESS_BAR = _ProgressBar ( len ( tickers ) , 'downloaded' )
# reset _ DFS
_DFS = { }
# set thread count if True
if threads is True :
threads = min ( [ len ( tickers ) , ... |
def create_content ( self , cli , width , height ) :
"""Create a UIContent object for this control .""" | complete_state = cli . current_buffer . complete_state
if complete_state :
completions = complete_state . current_completions
index = complete_state . complete_index
# Can be None !
# Calculate width of completions menu .
menu_width = self . _get_menu_width ( width , complete_state )
menu_meta_w... |
def _get_envelopes_centroid ( envelopes ) :
"""Returns the centroid of an inputted geometry column . Not currently in use , as this is now handled by this
library ' s CRS wrapper directly . Light wrapper over ` ` _ get _ envelopes _ min _ maxes ` ` .
Parameters
envelopes : GeoSeries
The envelopes of the giv... | xmin , xmax , ymin , ymax = _get_envelopes_min_maxes ( envelopes )
return np . mean ( xmin , xmax ) , np . mean ( ymin , ymax ) |
def deleteMask ( self , signature ) :
"""Delete just the mask that matches the signature given .""" | if signature in self . masklist :
self . masklist [ signature ] = None
else :
log . warning ( "No matching mask" ) |
def get_parameter_dict ( self , include_frozen = False ) :
"""Get an ordered dictionary of the parameters
Args :
include _ frozen ( Optional [ bool ] ) : Should the frozen parameters be
included in the returned value ? ( default : ` ` False ` ` )""" | return OrderedDict ( zip ( self . get_parameter_names ( include_frozen = include_frozen ) , self . get_parameter_vector ( include_frozen = include_frozen ) , ) ) |
def show_input ( self , template_helper , language , seed ) :
"""Show MatchProblem""" | header = ParsableText ( self . gettext ( language , self . _header ) , "rst" , translation = self . _translations . get ( language , gettext . NullTranslations ( ) ) )
return str ( DisplayableMatchProblem . get_renderer ( template_helper ) . tasks . match ( self . get_id ( ) , header ) ) |
def mfe ( self , strand , degenerate = False , temp = 37.0 , pseudo = False , material = None , dangles = 'some' , sodium = 1.0 , magnesium = 0.0 ) :
'''Compute the MFE for an ordered complex of strands . Runs the \' mfe \'
command .
: param strand : Strand on which to run mfe . Strands must be either
coral .... | # Set the material ( will be used to set command material flag )
material = self . _set_material ( strand , material )
# Set up command flags
cmd_args = self . _prep_cmd_args ( temp , dangles , material , pseudo , sodium , magnesium , multi = False )
if degenerate :
cmd_args . append ( '-degenerate' )
# Set up the ... |
def __parse_drac ( output ) :
'''Parse Dell DRAC output''' | drac = { }
section = ''
for i in output . splitlines ( ) :
if i . strip ( ) . endswith ( ':' ) and '=' not in i :
section = i [ 0 : - 1 ]
drac [ section ] = { }
if i . rstrip ( ) and '=' in i :
if section in drac :
drac [ section ] . update ( dict ( [ [ prop . strip ( ) for p... |
def create_fw ( self , tenant_id , data ) :
"""Top level routine called when a FW is created .""" | try :
return self . _create_fw ( tenant_id , data )
except Exception as exc :
LOG . error ( "Failed to create FW for device native, tenant " "%(tenant)s data %(data)s Exc %(exc)s" , { 'tenant' : tenant_id , 'data' : data , 'exc' : exc } )
return False |
def generate_csr ( private_key_bytes , subject_name , fqdn_list ) :
"""Generate a Certificate Signing Request ( CSR ) .
Args :
private _ key _ bytes : bytes
Private key with which the CSR will be signed .
subject _ name : str
Certificate Subject Name
fqdn _ list :
List of Fully Qualified Domain Names ... | return ( cryptography . x509 . CertificateSigningRequestBuilder ( ) . subject_name ( subject_name ) . add_extension ( extension = cryptography . x509 . SubjectAlternativeName ( [ cryptography . x509 . DNSName ( v ) for v in fqdn_list ] ) , critical = False , ) . sign ( private_key = private_key_bytes , algorithm = cryp... |
def wrap_json ( cls , json ) :
"""Create a User instance for the given json
: param json : the dict with the information of the user
: type json : : class : ` dict ` | None
: returns : the new user instance
: rtype : : class : ` User `
: raises : None""" | u = User ( usertype = json [ 'type' ] , name = json [ 'name' ] , logo = json [ 'logo' ] , twitchid = json [ '_id' ] , displayname = json [ 'display_name' ] , bio = json [ 'bio' ] )
return u |
def _play_sound ( self , filename ) :
"""Shells player with the provided filename .
` filename `
Filename for sound file .""" | command = self . _get_external_player ( )
if not command :
return
# no player found
if common . IS_MACOSX :
command += ' "{0}"' . format ( filename )
else : # append quiet flag and filename
is_play = ( command == 'play' )
command += ' -q "{0}"' . format ( filename )
# HACK : play can default to usin... |
def _generate_security_groups ( config_key ) :
"""Read config file and generate security group dict by environment .
Args :
config _ key ( str ) : Configuration file key
Returns :
dict : of environments in { ' env1 ' : [ ' group1 ' , ' group2 ' ] } format""" | raw_default_groups = validate_key_values ( CONFIG , 'base' , config_key , default = '' )
default_groups = _convert_string_to_native ( raw_default_groups )
LOG . debug ( 'Default security group for %s is %s' , config_key , default_groups )
entries = { }
for env in ENVS :
entries [ env ] = [ ]
if isinstance ( default... |
def selection_strategy ( oasis_obj , strategy = 'spectral-oasis' , nsel = 1 , neig = None ) :
"""Factory for selection strategy object
Returns
selstr : SelectionStrategy
Selection strategy object""" | strategy = strategy . lower ( )
if strategy == 'random' :
return SelectionStrategyRandom ( oasis_obj , strategy , nsel = nsel , neig = neig )
elif strategy == 'oasis' :
return SelectionStrategyOasis ( oasis_obj , strategy , nsel = nsel , neig = neig )
elif strategy == 'spectral-oasis' :
return SelectionStra... |
def run ( ** options ) :
"""_ run _
Run the dockerstache process to render templates
based on the options provided
If extend _ context is passed as options it will be used to
extend the context with the contents of the dictionary provided
via context . update ( extend _ context )""" | with Dotfile ( options ) as conf :
if conf [ 'context' ] is None :
msg = "No context file has been provided"
LOGGER . error ( msg )
raise RuntimeError ( msg )
if not os . path . exists ( conf [ 'context_path' ] ) :
msg = "Context file {} not found" . format ( conf [ 'context_path... |
def timezone ( value , allow_empty = False , positive = True , ** kwargs ) :
"""Validate that ` ` value ` ` is a valid : class : ` tzinfo < python : datetime . tzinfo > ` .
. . caution : :
This does * * not * * verify whether the value is a timezone that actually
exists , nor can it resolve timezone names ( e... | # pylint : disable = too - many - branches
original_value = value
if not value and not allow_empty :
raise errors . EmptyValueError ( 'value (%s) was empty' % value )
elif not value :
return None
if not isinstance ( value , tzinfo_types ) :
raise errors . CannotCoerceError ( 'value (%s) must be a tzinfo, ' ... |
def get_field_label_css_class ( self , bound_field ) :
"""Returns the optional label CSS class to use when rendering a field template .
By default , returns the Form class property ` field _ label _ css _ class ` . If the
field has errors and the Form class property ` field _ label _ invalid _ css _ class `
i... | class_name = self . field_label_css_class
if bound_field . errors and self . field_label_invalid_css_class :
class_name = join_css_class ( class_name , self . field_label_invalid_css_class )
return class_name or None |
def get ( self , what ) :
""": param what : what to extract
: returns : an ArrayWrapper instance""" | url = '%s/v1/calc/%d/extract/%s' % ( self . server , self . calc_id , what )
logging . info ( 'GET %s' , url )
resp = self . sess . get ( url )
if resp . status_code != 200 :
raise WebAPIError ( resp . text )
npz = numpy . load ( io . BytesIO ( resp . content ) )
attrs = { k : npz [ k ] for k in npz if k != 'array'... |
def chunk_sequence ( sequence , chunk_length = 200 , padding_value = 0 ) :
"""Split a nested dict of sequence tensors into a batch of chunks .
This function does not expect a batch of sequences , but a single sequence . A
` length ` key is added if it did not exist already .
Args :
sequence : Nested dict of... | if 'length' in sequence :
length = sequence . pop ( 'length' )
else :
length = tf . shape ( tools . nested . flatten ( sequence ) [ 0 ] ) [ 0 ]
num_chunks = ( length - 1 ) // chunk_length + 1
padding_length = chunk_length * num_chunks - length
padded = tools . nested . map ( # pylint : disable = g - long - lamb... |
def inject_request_ids_into_environment ( func ) :
"""Decorator for the Lambda handler to inject request IDs for logging .""" | @ wraps ( func )
def wrapper ( event , context ) : # This might not always be an API Gateway event , so only log the
# request ID , if it looks like to be coming from there .
if 'requestContext' in event :
os . environ [ ENV_APIG_REQUEST_ID ] = event [ 'requestContext' ] . get ( 'requestId' , 'N/A' )
os... |
def set_option ( section = 'main' , cfg_file = cfg_file , ** kwargs ) :
"""Change an option in our configuration file""" | parser = get_parser ( cfg_file = cfg_file )
if section not in parser . sections ( ) :
parser . add_section ( section )
for k , v in kwargs . items ( ) :
parser . set ( section = section , option = k , value = v )
with open ( cfg_file , 'w' ) as f :
parser . write ( f )
return "Done" |
def get_providing_power_source_type ( self ) :
"""Looks through all power supplies in POWER _ SUPPLY _ PATH .
If there is an AC adapter online returns POWER _ TYPE _ AC .
If there is a discharging battery , returns POWER _ TYPE _ BATTERY .
Since the order of supplies is arbitrary , whatever found first is ret... | type = self . power_source_type ( )
if type == common . POWER_TYPE_AC :
if self . is_ac_online ( ) :
return common . POWER_TYPE_AC
elif type == common . POWER_TYPE_BATTERY :
if self . is_battery_present ( ) and self . is_battery_discharging ( ) :
return common . POWER_TYPE_BATTERY
... |
def process_posts_response ( self , response , path , params , max_pages ) :
"""Insert / update all posts in a posts list response , in batches .
: param response : a response that contains a list of posts from the WP API
: param path : the path we ' re using to get the list of posts ( for subsquent pages )
:... | page = 1
num_processed_posts = 0
api_posts_found = None
while response . ok and response . text and page < max_pages :
logger . info ( " - page: %d" , page )
posts = [ ]
post_categories = { }
post_tags = { }
post_media_attachments = { }
api_json = response . json ( )
api_posts = api_json . g... |
def object_links ( self , multihash , ** kwargs ) :
"""Returns the links pointed to by the specified object .
. . code - block : : python
> > > c . object _ links ( ' QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDx . . . ca7D ' )
{ ' Hash ' : ' QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D ' ,
' Links ' : [
{ ' H... | args = ( multihash , )
return self . _client . request ( '/object/links' , args , decoder = 'json' , ** kwargs ) |
def init_editing_mode ( self , e ) : # ( C - e )
u'''When in vi command mode , this causes a switch to emacs editing
mode .''' | self . _bind_exit_key ( u'Control-d' )
self . _bind_exit_key ( u'Control-z' )
# I often accidentally hold the shift or control while typing space
self . _bind_key ( u'space' , self . self_insert )
self . _bind_key ( u'Shift-space' , self . self_insert )
self . _bind_key ( u'Control-space' , self . self_insert )
self . ... |
def select_highest_ranked ( elements , ranks ) :
"""Returns all of ' elements ' for which corresponding element in parallel
list ' rank ' is equal to the maximum value in ' rank ' .""" | assert is_iterable ( elements )
assert is_iterable ( ranks )
if not elements :
return [ ]
max_rank = max_element ( ranks )
result = [ ]
while elements :
if ranks [ 0 ] == max_rank :
result . append ( elements [ 0 ] )
elements = elements [ 1 : ]
ranks = ranks [ 1 : ]
return result |
def _get_first_64k_content ( file_path ) :
"""Returns the first 65536 ( or the file size , whichever is smaller ) bytes of the file at the
specified file path , as a bytearray .""" | if not isfile ( file_path ) :
raise PathDoesNotExistException ( file_path )
file_size = getsize ( file_path )
content_size = min ( file_size , 0x10000 )
content = bytearray ( content_size )
with open ( file_path , "rb" ) as file_object :
content_read = file_object . readinto ( content )
if content_read is N... |
def set_maintext ( self , index ) :
"""Set the maintext _ lb to display text information about the given reftrack
: param index : the index
: type index : : class : ` QtGui . QModelIndex `
: returns : None
: rtype : None
: raises : None""" | dr = QtCore . Qt . DisplayRole
text = ""
model = index . model ( )
for i in ( 1 , 2 , 3 , 5 , 6 ) :
new = model . index ( index . row ( ) , i , index . parent ( ) ) . data ( dr )
if new is not None :
text = " | " . join ( ( text , new ) ) if text else new
self . maintext_lb . setText ( text ) |
def set_base_prompt ( self , pri_prompt_terminator = ":" , alt_prompt_terminator = "#" , delay_factor = 2 ) :
"""Sets self . base _ prompt : used as delimiter for stripping of trailing prompt in output .""" | super ( AccedianSSH , self ) . set_base_prompt ( pri_prompt_terminator = pri_prompt_terminator , alt_prompt_terminator = alt_prompt_terminator , delay_factor = delay_factor , )
return self . base_prompt |
def edit ( self , billing_email = github . GithubObject . NotSet , blog = github . GithubObject . NotSet , company = github . GithubObject . NotSet , description = github . GithubObject . NotSet , email = github . GithubObject . NotSet , location = github . GithubObject . NotSet , name = github . GithubObject . NotSet ... | assert billing_email is github . GithubObject . NotSet or isinstance ( billing_email , ( str , unicode ) ) , billing_email
assert blog is github . GithubObject . NotSet or isinstance ( blog , ( str , unicode ) ) , blog
assert company is github . GithubObject . NotSet or isinstance ( company , ( str , unicode ) ) , comp... |
def wrap_connection_loader__get ( name , * args , ** kwargs ) :
"""While the strategy is active , rewrite connection _ loader . get ( ) calls for
some transports into requests for a compatible Mitogen transport .""" | if name in ( 'docker' , 'kubectl' , 'jail' , 'local' , 'lxc' , 'lxd' , 'machinectl' , 'setns' , 'ssh' ) :
name = 'mitogen_' + name
return connection_loader__get ( name , * args , ** kwargs ) |
def get_command_completers ( self , namespace , command ) : # type : ( str , str ) - > CompletionInfo
"""Returns the completer method associated to the given command , or None
: param namespace : The command name space .
: param command : The shell name of the command
: return : A CompletionConfiguration obje... | # Find the method ( can raise a KeyError )
method = self . _commands [ namespace ] [ command ]
# Return the completer , if any
return getattr ( method , ATTR_COMPLETERS , None ) |
def get_stat ( self , obj_name , stat_name ) :
""": param obj _ name : requested object name .
: param stat _ name : requested statistics name .
: return : str , the value of the requested statics for the requested object .""" | return self . statistics [ obj_name ] [ self . captions . index ( stat_name ) ] |
def select_month ( self , month ) :
"""选择月份
@2018/06/03 pandas 的索引问题导致
https : / / github . com / pandas - dev / pandas / issues / 21299
因此先用set _ index去重做一次index
影响的有selects , select _ time , select _ month , get _ bar
@2018/06/04
当选择的时间越界 / 股票不存在 , raise ValueError
@2018/06/04 pandas索引问题已经解决
全部恢复"... | def _select_month ( month ) :
return self . data . loc [ month , slice ( None ) ]
try :
return self . new ( _select_month ( month ) , self . type , self . if_fq )
except :
raise ValueError ( 'QA CANNOT GET THIS Month {} ' . format ( month ) ) |
def from_str ( date ) :
"""Given a date in the format : Jan , 21st . 2015
will return a datetime of it .""" | month = date [ : 3 ] [ 0 ] + date [ : 3 ] [ - 2 : ] . lower ( )
if month not in NAMED_MONTHS :
raise CanNotFormatError ( 'Month not recognized' )
date = date . replace ( ',' , '' ) . replace ( ' ' , '' ) . replace ( '.' , '' )
try :
day_unit = [ x for x in [ 'st' , 'rd' , 'nd' , 'th' ] if x in date ] [ 0 ]
... |
def max ( cls , x : 'TensorFluent' , y : 'TensorFluent' ) -> 'TensorFluent' :
'''Returns a TensorFluent for the maximum function . TensorFluent
Args :
x : The first operand .
y : The second operand .
Returns :
A TensorFluent wrapping the maximum function .''' | return cls . _binary_op ( x , y , tf . maximum , tf . float32 ) |
def voxelize_ray ( mesh , pitch , per_cell = [ 2 , 2 ] , ** kwargs ) :
"""Voxelize a mesh using ray queries .
Parameters
mesh : Trimesh object
Mesh to be voxelized
pitch : float
Length of voxel cube
per _ cell : ( 2 , ) int
How many ray queries to make per cell
Returns
voxels : ( n , 3 ) int
Vox... | # how many rays per cell
per_cell = np . array ( per_cell ) . astype ( np . int ) . reshape ( 2 )
# edge length of cube voxels
pitch = float ( pitch )
# create the ray origins in a grid
bounds = mesh . bounds [ : , : 2 ] . copy ( )
# offset start so we get the requested number per cell
bounds [ 0 ] += pitch / ( 1.0 + p... |
def _compile_schema ( self , schema ) :
"""Compile another schema""" | assert self . matcher == schema . matcher
self . name = schema . name
self . compiled_type = schema . compiled_type
return schema . compiled |
def name ( self , name ) :
"""Set the enum name .""" | success = idaapi . set_enum_name ( self . eid , name )
if not success :
raise exceptions . CantRenameEnum ( "Cant rename enum {!r} to {!r}." . format ( self . name , name ) ) |
def index ( self , value : Any ) -> int :
"""Returns the index in the handlers list
that matches the given value .
If no condition matches , ValueError is raised .""" | for i , cond in ( ( j [ 0 ] , j [ 1 ] [ 0 ] ) for j in enumerate ( self . handlers ) ) :
try :
match = cond ( value )
except :
if self . raiseconditionerrors :
raise
match = False
if match :
return i
raise TypedloadValueError ( 'Unable to dump %s' % value , value ... |
def _deploy_tripleo_heat_templates ( self , stack , parsed_args ) :
"""Deploy the fixed templates in TripleO Heat Templates""" | clients = self . app . client_manager
network_client = clients . network
parameters = self . _update_paramaters ( parsed_args , network_client , stack )
utils . check_nodes_count ( self . app . client_manager . rdomanager_oscplugin . baremetal ( ) , stack , parameters , { 'ControllerCount' : 1 , 'ComputeCount' : 1 , 'O... |
def _objective_function_subject ( self , data_align , data_sup , labels , w , s , theta , bias ) :
"""Compute the objective function for one subject .
. . math : : ( 1 - C ) * Loss _ { SRM } _ i ( W _ i , S ; X _ i )
. . math : : + C / \\ gamma * Loss _ { MLR _ i } ( \\ theta , bias ; { ( W _ i ^ T * Z _ i , y ... | # Compute the SRM loss
f_val = 0.0
samples = data_align . shape [ 1 ]
f_val += ( 1 - self . alpha ) * ( 0.5 / samples ) * np . linalg . norm ( data_align - w . dot ( s ) , 'fro' ) ** 2
# Compute the MLR loss
f_val += self . _loss_lr_subject ( data_sup , labels , w , theta , bias )
return f_val |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.