signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def ne_ ( self , value ) :
'''Creates a query expression where ` ` this field ! = value ` `
. . note : : The prefered usage is via an operator : ` ` User . name ! = value ` `''' | if isinstance ( value , QueryField ) :
return self . __cached_id != value . __cached_id
return self . __comparator ( '$ne' , value ) |
def _getAppStoreResource ( self , ctx , name ) :
"""Customize child lookup such that all installed offerings on the site
store that this page is viewing are given an opportunity to display
their own page .""" | offer = self . frontPageItem . store . findFirst ( offering . InstalledOffering , offering . InstalledOffering . offeringName == unicode ( name , 'ascii' ) )
if offer is not None :
pp = ixmantissa . IPublicPage ( offer . application , None )
if pp is not None :
warn ( "Use the sharing system to provide ... |
def confd_state_snmp_version_v2c ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
confd_state = ET . SubElement ( config , "confd-state" , xmlns = "http://tail-f.com/yang/confd-monitoring" )
snmp = ET . SubElement ( confd_state , "snmp" )
version = ET . SubElement ( snmp , "version" )
v2c = ET . SubElement ( version , "v2c" )
callback = kwargs . pop ( 'callback' , ... |
def _sparse ( self , x , y , sparse ) :
"""Method that removes every non sparse th element .
For example :
if this argument was 5 , This method would plot the 0th , 5th ,
10th . . . elements .
Parameters
x : list
list of x values , of length j .
y : list
list of y values , of length j .
sparse : i... | tmpX = [ ]
tmpY = [ ]
for i in range ( len ( x ) ) :
if sparse == 1 :
return x , y
if ( i % sparse ) == 0 :
tmpX . append ( x [ i ] )
tmpY . append ( y [ i ] )
return tmpX , tmpY |
def command ( state , args ) :
"""Add an anime from an AniDB search .""" | if len ( args ) < 2 :
print ( f'Usage: {args[0]} {{ID|aid:AID}}' )
return
aid = state . results . parse_aid ( args [ 1 ] , default_key = 'anidb' )
anime = request_anime ( aid )
query . update . add ( state . db , anime ) |
def unwrap ( self ) :
'''Returns a nested python sequence .''' | size = self . width , self . height
bits = self . red_bits , self . green_bits , self . blue_bits
return size , bits , self . refresh_rate |
def __set_data ( self , data ) :
"""Sets the given state data on the given entity of the given class .
: param data : State data to set .
: type data : Dictionary mapping attributes to attribute values .
: param entity : Entity to receive the state data .""" | ent = self . __entity_ref ( )
self . set_state_data ( ent , data ) |
def get_result ( self , * , block = False , timeout = None ) :
"""Get the result of this pipeline .
Pipeline results are represented by the result of the last
message in the chain .
Parameters :
block ( bool ) : Whether or not to block until a result is set .
timeout ( int ) : The maximum amount of time ,... | return self . messages [ - 1 ] . get_result ( block = block , timeout = timeout ) |
def disconnect_signals ( self ) :
"""Disable the signals within the ` Flow ` .""" | # Disconnect the signals inside each Work .
for work in self :
work . disconnect_signals ( )
# Disable callbacks .
for cbk in self . _callbacks :
cbk . disable ( ) |
def dict_itemstr_list ( dict_ , ** dictkw ) :
r"""Returns :
list : a list of human - readable dictionary items
Args :
explicit : if True uses dict ( key = val , . . . ) format instead of { key : val , . . . }""" | import utool as ut
explicit = dictkw . get ( 'explicit' , False )
dictkw [ 'explicit' ] = _rectify_countdown_or_bool ( explicit )
dosort = dictkw . get ( 'sorted_' , None )
if dosort is None :
dosort = True
if dosort and not isinstance ( dict_ , collections . OrderedDict ) :
key_order = dictkw . get ( 'key_orde... |
def create_snapshot ( self , volume_id , description = None ) :
"""Create a snapshot of an existing EBS Volume .
: type volume _ id : str
: param volume _ id : The ID of the volume to be snapshot ' ed
: type description : str
: param description : A description of the snapshot .
Limited to 255 characters ... | params = { 'VolumeId' : volume_id }
if description :
params [ 'Description' ] = description [ 0 : 255 ]
snapshot = self . get_object ( 'CreateSnapshot' , params , Snapshot , verb = 'POST' )
volume = self . get_all_volumes ( [ volume_id ] ) [ 0 ]
volume_name = volume . tags . get ( 'Name' )
if volume_name :
snap... |
async def destroy ( self , container = None ) :
"""Destroy the created subqueue to change the behavior back to Lock""" | if container is None :
container = RoutineContainer ( self . scheduler )
if self . queue is not None :
await container . syscall_noreturn ( syscall_removequeue ( self . scheduler . queue , self . queue ) )
self . queue = None |
def hash ( self ) :
"""Hash the file contents .""" | with open ( self . filename , "rb" ) as fp :
for content in iter ( lambda : fp . read ( io . DEFAULT_BUFFER_SIZE ) , b'' ) :
self . _md5_update ( content )
self . _sha2_update ( content )
self . _blake_update ( content ) |
def exit ( self ) :
"""Set exit . When Control - D has been pressed .""" | on_exit = self . application . on_exit
self . _exit_flag = True
self . _redraw ( )
if on_exit == AbortAction . RAISE_EXCEPTION :
def eof_error ( ) :
raise EOFError ( )
self . _set_return_callable ( eof_error )
elif on_exit == AbortAction . RETRY :
self . reset ( )
self . renderer . request_absol... |
def get_params ( mail , failobj = None , header = 'content-type' , unquote = True ) :
'''Get Content - Type parameters as dict .
RFC 2045 specifies that parameter names are case - insensitive , so
we normalize them here .
: param mail : : class : ` email . message . Message `
: param failobj : object to ret... | failobj = failobj or [ ]
return { k . lower ( ) : v for k , v in mail . get_params ( failobj , header , unquote ) } |
def friendship_followings ( self , user_id = None , user_name = None , page = 1 , count = 20 ) :
"""doc : http : / / open . youku . com / docs / doc ? id = 26""" | url = 'https://openapi.youku.com/v2/users/friendship/followings.json'
data = { 'client_id' : self . client_id , 'page' : page , 'count' : count , 'user_id' : user_id , 'user_name' : user_name }
data = remove_none_value ( data )
r = requests . post ( url , data = data )
check_error ( r )
return r . json ( ) |
def _generate_ascii ( self , matrix , foreground , background ) :
"""Generates an identicon " image " in the ASCII format . The image will just
output the matrix used to generate the identicon .
Arguments :
matrix - Matrix describing which blocks in the identicon should be
painted with foreground ( backgrou... | return "\n" . join ( [ "" . join ( [ foreground if cell else background for cell in row ] ) for row in matrix ] ) |
def resource_url ( path ) :
"""Get the a local filesystem url to a given resource .
. . versionadded : : 3.0
Note that in version 3.0 we removed the use of Qt Resource files in
favour of directly accessing on - disk resources .
: param path : Path to resource e . g . / home / timlinux / foo / bar . png
: ... | url = QtCore . QUrl . fromLocalFile ( path )
return str ( url . toString ( ) ) |
def find_editor_tab ( self , file ) :
"""Finds the * * Script _ Editor _ tabWidget * * Widget tab associated to the given file .
: param file : File to search tab for .
: type file : unicode
: return : Tab index .
: rtype : Editor""" | for i in range ( self . Script_Editor_tabWidget . count ( ) ) :
if not self . get_widget ( i ) . file == file :
continue
LOGGER . debug ( "> File '{0}': Tab index '{1}'." . format ( file , i ) )
return i |
def record ( self ) : # type : ( ) - > bytes
'''Generate a string representing the Rock Ridge Child Link record .
Parameters :
None .
Returns :
String containing the Rock Ridge record .''' | if not self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'PL record not yet initialized!' )
return b'PL' + struct . pack ( '=BBLL' , RRPLRecord . length ( ) , SU_ENTRY_VERSION , self . parent_log_block_num , utils . swab_32bit ( self . parent_log_block_num ) ) |
def current_portfolio_weights ( self ) :
"""Compute each asset ' s weight in the portfolio by calculating its held
value divided by the total value of all positions .
Each equity ' s value is its price times the number of shares held . Each
futures contract ' s value is its unit price times number of shares h... | position_values = pd . Series ( { asset : ( position . last_sale_price * position . amount * asset . price_multiplier ) for asset , position in self . positions . items ( ) } )
return position_values / self . portfolio_value |
def fix_e224 ( self , result ) :
"""Remove extraneous whitespace around operator .""" | target = self . source [ result [ 'line' ] - 1 ]
offset = result [ 'column' ] - 1
fixed = target [ : offset ] + target [ offset : ] . replace ( '\t' , ' ' )
self . source [ result [ 'line' ] - 1 ] = fixed |
def update_recent_file_menu ( self ) :
"""Update recent file menu""" | recent_files = [ ]
for fname in self . recent_files :
if self . is_file_opened ( fname ) is None and osp . isfile ( fname ) :
recent_files . append ( fname )
self . recent_file_menu . clear ( )
if recent_files :
for fname in recent_files :
action = create_action ( self , fname , icon = ima . ico... |
def hasFeature ( self , prop , check_softs = False ) :
"""Return if there is a property with that name .""" | return prop in self . props or ( check_softs and any ( [ fs . hasFeature ( prop ) for fs in self . props . get ( SoftFeatures . SOFT , [ ] ) ] ) ) |
def get ( self , path ) :
"""permet de récupérer une config
Args :
path ( String ) : Nom d ' une config
Returns :
type : String
la valeur de la config ou None""" | path = path . upper ( )
if path in self . _configCache :
return self . _configCache [ path ]
else :
return self . _findConfig ( path ) |
def _dbus_get_interface ( bus_name , object_name , interface_name ) :
"""Fetches DBUS interface proxy object given the specified parameters .
` bus _ name `
Name of the bus interface .
` object _ name `
Object path related to the interface .
` interface _ name `
Name of the interface .
Returns object ... | try :
obj = _dbus_get_object ( bus_name , object_name )
if not obj :
raise NameError
return dbus . Interface ( obj , interface_name )
except ( NameError , dbus . exceptions . DBusException ) :
return None |
def _iter_future_contradictions ( entity , key , turns , branch , turn , tick , value ) :
"""If setting ` ` key = value ` ` would result in a contradiction , iterate over contradicted ` ` ( turn , tick ) ` ` s .""" | # assumes that all future entries are in the plan
if not turns :
return
if turn in turns :
future_ticks = turns [ turn ] . future ( tick )
for tck , newval in future_ticks . items ( ) :
if newval != value :
yield turn , tck
future_turns = turns . future ( turn )
elif turns . rev_gett... |
def create_journal_club_meeting ( self , presenters , food_vendor , paper = None ) :
'Presenters can be a comma - separated list of presenters .' | e = self . initialize_tagged_copy ( )
e [ 'extendedProperties' ] [ 'shared' ] [ 'event_type' ] = 'Journal club'
e [ 'extendedProperties' ] [ 'shared' ] [ 'Presenters' ] = presenters
e [ 'extendedProperties' ] [ 'shared' ] [ 'Food vendor' ] = food_vendor
e [ 'extendedProperties' ] [ 'shared' ] [ 'Paper' ] = paper
partic... |
def add_timing_signal_1d_given_position ( x , position , min_timescale = 1.0 , max_timescale = 1.0e4 ) :
"""Adds sinusoids of diff frequencies to a Tensor , with timing position given .
Args :
x : a Tensor with shape [ batch , length , channels ]
position : a Tensor with shape [ batch , length ]
min _ times... | channels = common_layers . shape_list ( x ) [ 2 ]
num_timescales = channels // 2
log_timescale_increment = ( math . log ( float ( max_timescale ) / float ( min_timescale ) ) / ( tf . to_float ( num_timescales ) - 1 ) )
inv_timescales = min_timescale * tf . exp ( tf . to_float ( tf . range ( num_timescales ) ) * - log_t... |
def remove_blanks ( letters : List [ str ] ) :
"""Given a list of letters , remove any empty strings .
: param letters :
: return :
> > > remove _ blanks ( [ ' a ' , ' ' , ' b ' , ' ' , ' c ' ] )
[ ' a ' , ' b ' , ' c ' ]""" | cleaned = [ ]
for letter in letters :
if letter != "" :
cleaned . append ( letter )
return cleaned |
def pdist_sq_periodic ( r , L ) :
"""Return the squared distance between all combinations of
a set of points , in periodic space .
Parameters
r : shape ( n , d ) for n points in d dimensions .
Set of points
L : float array , shape ( d , )
System lengths .
Returns
d _ sq : float array , shape ( n , n... | d = csep_periodic ( r , r , L )
d [ np . identity ( len ( r ) , dtype = np . bool ) ] = np . inf
d_sq = np . sum ( np . square ( d ) , axis = - 1 )
return d_sq |
def read_next_into_buf ( self ) :
"""Read data from the file in self . bufsize chunks until we ' re
certain we have a full line in the buffer .""" | file_pos = self . fileobject . tell ( )
if ( file_pos == 0 ) and ( self . buf == b'' ) :
raise StopIteration
while file_pos and ( self . get_start_of_line ( ) == 0 ) :
bytes_to_read = min ( self . bufsize , file_pos )
file_pos = file_pos - bytes_to_read
self . fileobject . seek ( file_pos )
new_stuf... |
def __criteria ( self , obj , matches = None , mt = None , lt = None , eq = None ) :
'''Returns True if object is aligned to the criteria .
: param obj :
: param matches :
: param mt :
: param lt :
: param eq :
: return : Boolean''' | # Fail matcher if " less than "
for field , value in ( mt or { } ) . items ( ) :
if getattr ( obj , field ) <= value :
return False
# Fail matcher if " more than "
for field , value in ( lt or { } ) . items ( ) :
if getattr ( obj , field ) >= value :
return False
# Fail matcher if " not equal "
... |
def update ( self , role_sid = values . unset , last_consumed_message_index = values . unset ) :
"""Update the MemberInstance
: param unicode role _ sid : The Role assigned to this member .
: param unicode last _ consumed _ message _ index : An Integer representing index of the last Message this Member has read... | data = values . of ( { 'RoleSid' : role_sid , 'LastConsumedMessageIndex' : last_consumed_message_index , } )
payload = self . _version . update ( 'POST' , self . _uri , data = data , )
return MemberInstance ( self . _version , payload , service_sid = self . _solution [ 'service_sid' ] , channel_sid = self . _solution [... |
def app_start_up_time ( self , package : str ) -> str :
'''Get the time it took to launch your application .''' | output , _ = self . _execute ( '-s' , self . device_sn , 'shell' , 'am' , 'start' , '-W' , package )
return re . findall ( 'TotalTime: \d+' , output ) [ 0 ] |
def _reverse_index ( self ) :
"""Move the cursor up one row in the same column . If the cursor is at the
first row , create a new row at the top .""" | if self . y == 0 : # If the cursor is currently at the first row , then scroll the
# screen up .
self . display = [ u" " * self . size [ 1 ] ] + self . display [ : - 1 ]
else : # If the cursor is anywhere other than the first row than just move
# it up by one row .
self . y -= 1 |
def convert_pronouns ( mrf_lines ) :
'''Converts pronouns ( analysis lines with ' _ P _ ' ) from Filosoft ' s mrf to
syntactic analyzer ' s mrf format ;
Uses the set of predefined pronoun conversion rules from _ pronConversions ;
_ pronConversions should be a list of lists , where each outer list stands
for... | i = 0
while ( i < len ( mrf_lines ) ) :
line = mrf_lines [ i ]
if '_P_' in line : # only consider lines containing pronoun analyses
for [ pattern , replacement ] in _pronConversions :
lastline = line
line = re . sub ( pattern , replacement , line )
if lastline != line... |
def connect ( self ) :
"""Connect to host""" | try :
self . client . connect ( self . host , username = self . username , password = self . password , port = self . port , pkey = self . pkey , timeout = self . timeout )
except sock_gaierror , ex :
raise Exception ( "Unknown host '%s'" % self . host )
except sock_error , ex :
raise Exception ( "Error con... |
def check_image_in_spain ( glance_url , id , token ) :
"""It obtain if the image is in Spain
: param glance _ url : the sdc url
: param token : the valid token
: param id : image id""" | url = glance_url + '/images?property-sdc_aware=true'
headers = { 'Accept' : 'application/json' , 'X-Auth-Token' : token }
try :
response = requests . get ( url , headers = headers )
response_json = response . json ( )
for image in response_json [ 'images' ] :
if image [ 'id' ] == id :
re... |
def slice_by_coord ( self , start , end ) :
"""Return the slice of the component corresponding to a coordinate interval .
start and end are relative to the + strand , regardless of the component ' s strand .""" | start_col = self . coord_to_col ( start )
end_col = self . coord_to_col ( end )
if ( self . strand == '-' ) :
( start_col , end_col ) = ( end_col , start_col )
return self . slice ( start_col , end_col ) |
def coinc ( self , s0 , s1 , slide , step ) : # pylint : disable = unused - argument
"""Calculate the coincident detection statistic .
Parameters
s0 : numpy . ndarray
Single detector ranking statistic for the first detector .
s1 : numpy . ndarray
Single detector ranking statistic for the second detector .... | cstat = ( s0 ** 2. + s1 ** 2. ) ** 0.5
cstat [ s0 == - 1 ] = 0
cstat [ s1 == - 1 ] = 0
return cstat |
def adjust_bounding_box ( bbox ) :
"""Adjust the bounding box as specified by user .
Returns the adjusted bounding box .
- bbox : Bounding box computed from the canvas drawings .
It must be a four - tuple of numbers .""" | for i in range ( 0 , 4 ) :
if i in bounding_box :
bbox [ i ] = bounding_box [ i ]
else :
bbox [ i ] += delta_bounding_box [ i ]
return bbox |
def _prompt_choice ( var_name , options ) :
'''Prompt the user to choose between a list of options , index each one by adding an enumerator
based on https : / / github . com / audreyr / cookiecutter / blob / master / cookiecutter / prompt . py # L51
: param var _ name : The question to ask the user
: type var... | choice_map = OrderedDict ( ( '{0}' . format ( i ) , value ) for i , value in enumerate ( options , 1 ) if value [ 0 ] != 'test' )
choices = choice_map . keys ( )
default = '1'
choice_lines = [ '{0} - {1} - {2}' . format ( c [ 0 ] , c [ 1 ] [ 0 ] , c [ 1 ] [ 1 ] ) for c in choice_map . items ( ) ]
prompt = '\n' . join (... |
def create_restore_point ( self , name = None ) :
'''Creating a configuration restore point .
Parameters
name : str
Name of the restore point . If not given , a md5 hash will be generated .''' | if name is None :
for i in iter ( int , 1 ) :
name = datetime . datetime . utcnow ( ) . strftime ( '%Y%m%d%H%M%S%f' ) + '_' + str ( i )
try :
self . config_state [ name ]
except KeyError :
break
else :
pass
if name in self . config_state :
rais... |
def get_objects_without_object ( self , obj_type , * child_types ) :
""": param obj _ type : requested object type .
: param child _ type : unrequested child types .
: return : all children of the requested type that do not have the unrequested child types .""" | return [ o for o in self . get_objects_by_type ( obj_type ) if not o . get_objects_by_type ( * child_types ) ] |
def _set_download ( self , v , load = False ) :
"""Setter method for download , mapped from YANG variable / firmware / download ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ download is considered as a private
method . Backends looking to populate this... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = download . download , is_container = 'container' , presence = False , yang_name = "download" , rest_name = "download" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = Tr... |
def remove_codeblock_syntax_sentinals ( code_text ) :
r"""Removes template comments and vim sentinals
Args :
code _ text ( str ) :
Returns :
str : code _ text _""" | flags = re . MULTILINE | re . DOTALL
code_text_ = code_text
code_text_ = re . sub ( r'^ *# *REM [^\n]*$\n?' , '' , code_text_ , flags = flags )
code_text_ = re . sub ( r'^ *# STARTBLOCK *$\n' , '' , code_text_ , flags = flags )
code_text_ = re . sub ( r'^ *# ENDBLOCK *$\n?' , '' , code_text_ , flags = flags )
code_text... |
def codemirror_instance ( config_name , varname , element_id , assets = True ) :
"""Return HTML to init a CodeMirror instance for an element .
This will output the whole HTML needed to initialize a CodeMirror instance
with needed assets loading . Assets can be omitted with the ` ` assets ` `
option .
Exampl... | output = io . StringIO ( )
manifesto = CodemirrorAssetTagRender ( )
manifesto . register ( config_name )
if assets :
output . write ( manifesto . css_html ( ) )
output . write ( manifesto . js_html ( ) )
html = manifesto . codemirror_html ( config_name , varname , element_id )
output . write ( html )
content = ... |
def _load_cytoBand ( filename ) :
"""Load UCSC cytoBand table .
Parameters
filename : str
path to cytoBand file
Returns
df : pandas . DataFrame
cytoBand table if loading was successful , else None
References
. . [ 1 ] Ryan Dale , GitHub Gist ,
https : / / gist . github . com / daler / c98fc410282d... | try : # adapted from chromosome plotting code ( see [ 1 ] _ )
df = pd . read_table ( filename , names = [ "chrom" , "start" , "end" , "name" , "gie_stain" ] )
df [ "chrom" ] = df [ "chrom" ] . str [ 3 : ]
return df
except Exception as err :
print ( err )
return None |
def handle_msg ( self , body , org_message ) :
"""handle _ msg
: param body : dictionary contents from the message body
: param org _ message : message object can ack , requeue or reject""" | if os . path . exists ( self . stop_for_file ) :
log . info ( ( "Detected stop_file={} " "shutting down" ) . format ( self . stop_for_file ) )
# drop the message back in the queue
# for next time
org_message . requeue ( )
sys . exit ( 1 )
# end of stop file detection
try :
log . debug ( ( "handl... |
def planetType ( temperature , mass , radius ) :
"""Returns the planet type as ' temperatureType massType '""" | if mass is not np . nan :
sizeType = planetMassType ( mass )
elif radius is not np . nan :
sizeType = planetRadiusType ( radius )
else :
return None
return '{0} {1}' . format ( planetTempType ( temperature ) , sizeType ) |
def _tail_file ( self , file , interval ) :
"""Tails a file""" | file . seek ( 0 , 2 )
while True :
where = file . tell ( )
line = file . readline ( )
if not line :
time . sleep ( interval )
file . seek ( where )
else :
yield line |
def env ( self , key , value = None , unset = False , asap = False ) :
"""Processes ( sets / unsets ) environment variable .
If is not given in ` set ` mode value will be taken from current env .
: param str | unicode key :
: param value :
: param bool unset : Whether to unset this variable .
: param bool... | if unset :
self . _set ( 'unenv' , key , multi = True )
else :
if value is None :
value = os . environ . get ( key )
self . _set ( '%senv' % ( 'i' if asap else '' ) , '%s=%s' % ( key , value ) , multi = True )
return self |
def get_func_lno ( self , funcname ) :
"""The first line number of the last defined ' funcname ' function .""" | class FuncLineno ( ast . NodeVisitor ) :
def __init__ ( self ) :
self . clss = [ ]
def generic_visit ( self , node ) :
for child in ast . iter_child_nodes ( node ) :
for item in self . visit ( child ) :
yield item
def visit_ClassDef ( self , node ) :
self ... |
def get_domains ( self ) :
"""Retrieves available domains .
Returns :
: py : obj : ` list ` of : py : class : ` ~ . rest _ primitives . Domain ` : List of available domains""" | # Domains are fixed and actually only one per REST api .
if self . _domains is None :
self . _domains = self . _get_elements ( 'domains' , Domain )
return self . _domains |
def attrs ( self , dynamizer ) :
"""Get the attributes for the update""" | ret = { self . key : { 'Action' : self . action , } }
if not is_null ( self . value ) :
ret [ self . key ] [ 'Value' ] = dynamizer . encode ( self . value )
return ret |
def _sub_keywords ( self , line ) : # this will substitute out any keyword entries on a given line
# try :
if self . kw_count > 0 : # we have obfuscated keywords to work with
for k in self . kw_db . keys ( ) :
if k in line :
line = line . replace ( k , self . _kw2db ( k ) )
... | |
def present ( name , Name , S3BucketName , S3KeyPrefix = None , SnsTopicName = None , IncludeGlobalServiceEvents = True , IsMultiRegionTrail = None , EnableLogFileValidation = False , CloudWatchLogsLogGroupArn = None , CloudWatchLogsRoleArn = None , KmsKeyId = None , LoggingEnabled = True , Tags = None , region = None ... | ret = { 'name' : Name , 'result' : True , 'comment' : '' , 'changes' : { } }
r = __salt__ [ 'boto_cloudtrail.exists' ] ( Name = Name , region = region , key = key , keyid = keyid , profile = profile )
if 'error' in r :
ret [ 'result' ] = False
ret [ 'comment' ] = 'Failed to create trail: {0}.' . format ( r [ 'e... |
def set_processing_message ( self , message , warning = True ) :
"""Sets the processing operation message .
: param message : Operation description .
: type message : unicode
: param warning : Emit warning message .
: type warning : int
: return : Method success .
: rtype : bool""" | if not self . __is_processing :
warning and LOGGER . warning ( "!> {0} | Engine not processing, 'set_processing_message' request has been ignored!" . format ( self . __class__ . __name__ ) )
return False
LOGGER . debug ( "> Setting processing message!" )
self . Application_Progress_Status_processing . Processin... |
def drop_database ( self , name , force = False ) :
"""Drop an Impala database .
Parameters
name : string
Database name
force : bool , default False
If False and there are any tables in this database , raises an
IntegrityError""" | if not force or self . exists_database ( name ) :
tables = self . list_tables ( database = name )
udfs = self . list_udfs ( database = name )
udas = self . list_udas ( database = name )
else :
tables = [ ]
udfs = [ ]
udas = [ ]
if force :
for table in tables :
self . log ( 'Dropping ... |
def hilbert_curve ( precision , bits_per_char = 6 ) :
"""Build the ( geojson ) ` LineString ` of the used hilbert - curve
Builds the ` LineString ` of the used hilbert - curve given the ` precision ` and
the ` bits _ per _ char ` . The number of bits to encode the geohash is equal to
` precision * bits _ per ... | bits = precision * bits_per_char
coords = [ ]
for i in range ( 1 << bits ) :
code = encode_int ( i , bits_per_char ) . rjust ( precision , '0' )
coords += [ decode ( code , bits_per_char ) ]
return { 'type' : 'Feature' , 'properties' : { } , 'geometry' : { 'type' : 'LineString' , 'coordinates' : coords , } , } |
def load_txt_to_sql ( tbl_name , src_file_and_path , src_file , op_folder ) :
"""creates a SQL loader script to load a text file into a database
and then executes it .
Note that src _ file is""" | if op_folder == '' :
pth = ''
else :
pth = op_folder + os . sep
fname_create_script = pth + 'CREATE_' + tbl_name + '.SQL'
fname_backout_file = pth + 'BACKOUT_' + tbl_name + '.SQL'
fname_control_file = pth + tbl_name + '.CTL'
cols = read_csv_cols_to_table_cols ( src_file )
create_script_staging_table ( fname_cre... |
def bulk ( self , body , doc_type = None , params = None ) :
"""` < http : / / www . elastic . co / guide / en / monitoring / current / appendix - api - bulk . html > ` _
: arg body : The operation definition and data ( action - data pairs ) ,
separated by newlines
: arg doc _ type : Default document type for... | if body in SKIP_IN_PATH :
raise ValueError ( "Empty value passed for a required argument 'body'." )
return self . transport . perform_request ( "POST" , _make_path ( "_monitoring" , doc_type , "bulk" ) , params = params , body = self . _bulk_body ( body ) , ) |
def make_full_ivar ( ) :
"""take the scatters and skylines and make final ivars""" | # skylines come as an ivar
# don ' t use them for now , because I don ' t really trust them . . .
# skylines = np . load ( " % s / skylines . npz " % DATA _ DIR ) [ ' arr _ 0 ' ]
ref_flux = np . load ( "%s/ref_flux_all.npz" % DATA_DIR ) [ 'arr_0' ]
ref_scat = np . load ( "%s/ref_spec_scat_all.npz" % DATA_DIR ) [ 'arr_0... |
def unpause_topic ( self , topic ) :
"""Resume message flow to channels of an existing , paused , topic .""" | nsq . assert_valid_topic_name ( topic )
return self . _request ( 'POST' , '/topic/unpause' , fields = { 'topic' : topic } ) |
def similar ( self , word , n = 10 , metric = "cosine" ) :
"""Return similar words based on a metric
Parameters
word : string
n : int ( default 10)
Returns
Tuple of 2 numpy . array :
1 . position in self . vocab
2 . cosine similarity""" | return self . closest ( self [ word ] , n = n , metric = metric ) |
def num2varint ( num ) :
"""Converts a number to a variable length Int . Used for array length header
: param : { number } num - The number
: return : { string } hexstring of the variable Int .""" | # if ( typeof num ! = = ' number ' ) throw new Error ( ' VarInt must be numeric ' )
# if ( num < 0 ) throw new RangeError ( ' VarInts are unsigned ( > 0 ) ' )
# if ( ! Number . isSafeInteger ( num ) ) throw new RangeError ( ' VarInt must be a safe integer ' )
if num < 0xfd :
return num2hexstring ( num )
elif num <=... |
def create_jlink ( self , args ) :
"""Creates an instance of a J - Link from the given arguments .
Args :
self ( Command ) : the ` ` Command ` ` instance
args ( Namespace ) : arguments to construct the ` ` JLink ` ` instance from
Returns :
An instance of a ` ` JLink ` ` .""" | jlink = pylink . JLink ( )
jlink . open ( args . serial_no , args . ip_addr )
if hasattr ( args , 'tif' ) and args . tif is not None :
if args . tif . lower ( ) == 'swd' :
jlink . set_tif ( pylink . JLinkInterfaces . SWD )
else :
jlink . set_tif ( pylink . JLinkInterfaces . JTAG )
if hasattr ( a... |
def category ( self , categories ) :
"""Add categories assigned to this message
: rtype : list ( Category )""" | if isinstance ( categories , list ) :
for c in categories :
self . add_category ( c )
else :
self . add_category ( categories ) |
def snapshots ( self ) :
"""GET / : login / machines / : id / snapshots
: rtype : : py : class : ` list ` of : py : class : ` smartdc . machine . Snapshot `
Lists all snapshots for the Machine .""" | j , _ = self . datacenter . request ( 'GET' , self . path + '/snapshots' )
return [ Snapshot ( machine = self , data = s ) for s in j ] |
def ilxSearches ( self , ilx_ids = None , LIMIT = 25 , _print = True , crawl = False ) :
"""parameters ( data = " list of ilx _ ids " )""" | url_base = self . base_url + "/api/1/ilx/search/identifier/{identifier}?key={APIKEY}"
urls = [ url_base . format ( identifier = ilx_id . replace ( 'ILX:' , 'ilx_' ) , APIKEY = self . api_key ) for ilx_id in ilx_ids ]
return self . get ( urls = urls , LIMIT = LIMIT , action = 'Searching For Terms' , crawl = crawl , _pri... |
def NTU_from_P_J ( P1 , R1 , Ntp ) :
r'''Returns the number of transfer units of a TEMA J type heat exchanger
with a specified ( for side 1 ) thermal effectiveness ` P1 ` , heat capacity
ratio ` R1 ` , and the number of tube passes ` Ntp ` . The supported cases are
as follows :
* One tube pass ( shell fluid... | NTU_min = 1E-11
function = temperature_effectiveness_TEMA_J
if Ntp == 1 : # Very often failes because at NTU = 1000 , there is no variation in P1
# for instance at NTU = 40 , P1 already peaked and does not decline with
# higher NTU
NTU_max = 1E3
# We could fit a curve to determine the NTU where the floating poi... |
def compute_strongly_connected_components ( function ) :
"""Compute strongly connected components
Based on Kosaraju algo
Implem follows wikipedia algo : https : / / en . wikipedia . org / wiki / Kosaraju % 27s _ algorithm # The _ algorithm
Args :
function ( core . declarations . function . Function )
Retu... | visited = { n : False for n in function . nodes }
assigned = { n : False for n in function . nodes }
components = [ ]
l = [ ]
def visit ( node ) :
if not visited [ node ] :
visited [ node ] = True
for son in node . sons :
visit ( son )
l . append ( node )
for n in function . node... |
def compute_histogram ( values , edges , use_orig_distr = False ) :
"""Computes histogram ( density ) for a given vector of values .""" | if use_orig_distr :
return values
# ignoring invalid values : Inf and Nan
values = check_array ( values ) . compressed ( )
hist , bin_edges = np . histogram ( values , bins = edges , density = True )
hist = preprocess_histogram ( hist , values , edges )
return hist |
def get_workflow_config ( runtime , code_dir , project_dir ) :
"""Get a workflow config that corresponds to the runtime provided . This method examines contents of the project
and code directories to determine the most appropriate workflow for the given runtime . Currently the decision is
based on the presence ... | selectors_by_runtime = { "python2.7" : BasicWorkflowSelector ( PYTHON_PIP_CONFIG ) , "python3.6" : BasicWorkflowSelector ( PYTHON_PIP_CONFIG ) , "python3.7" : BasicWorkflowSelector ( PYTHON_PIP_CONFIG ) , "nodejs4.3" : BasicWorkflowSelector ( NODEJS_NPM_CONFIG ) , "nodejs6.10" : BasicWorkflowSelector ( NODEJS_NPM_CONFI... |
def create_trainer ( self , username , team , start_date = None , has_cheated = None , last_cheated = None , currently_cheats = None , statistics = True , daily_goal = None , total_goal = None , prefered = True , account = None , verified = False ) :
"""Add a trainer to the database""" | args = locals ( )
url = api_url + 'trainers/'
payload = { 'username' : username , 'faction' : team , 'statistics' : statistics , 'prefered' : prefered , 'last_modified' : maya . now ( ) . iso8601 ( ) , 'owner' : account , 'verified' : verified }
for i in args :
if args [ i ] is not None and i not in [ 'self' , 'use... |
def items ( self , obj ) :
"""Items are the published entries of the tag .""" | return TaggedItem . objects . get_by_model ( Entry . published . all ( ) , obj ) [ : self . limit ] |
def get_reference_lines ( docbody , ref_sect_start_line , ref_sect_end_line , ref_sect_title , ref_line_marker_ptn , title_marker_same_line ) :
"""After the reference section of a document has been identified , and the
first and last lines of the reference section have been recorded , this
function is called to... | start_idx = ref_sect_start_line
if title_marker_same_line : # Title on same line as 1st ref - take title out !
title_start = docbody [ start_idx ] . find ( ref_sect_title )
if title_start != - 1 : # Set the first line with no title
docbody [ start_idx ] = docbody [ start_idx ] [ title_start + len ( ref_... |
def unwrap_arguments ( xml_response ) :
"""Extract arguments and their values from a SOAP response .
Args :
xml _ response ( str ) : SOAP / xml response text ( unicode ,
not utf - 8 ) .
Returns :
dict : a dict of ` ` { argument _ name : value } ` ` items .""" | # A UPnP SOAP response ( including headers ) looks like this :
# HTTP / 1.1 200 OK
# CONTENT - LENGTH : bytes in body
# CONTENT - TYPE : text / xml ; charset = " utf - 8 " DATE : when response was
# generated
# EXT :
# SERVER : OS / version UPnP / 1.0 product / version
# < ? xml version = " 1.0 " ? >
# < s : Envelope
#... |
def get_string ( self , sigfigs = 8 ) :
"""Generates the string representation of the CTRL file . This is
the mininmal CTRL file necessary to execute lmhart . run .""" | ctrl_dict = self . as_dict ( )
lines = [ ] if "HEADER" not in ctrl_dict else [ "HEADER" . ljust ( 10 ) + self . header ]
if "VERS" in ctrl_dict :
lines . append ( "VERS" . ljust ( 10 ) + self . version )
lines . append ( "STRUC" . ljust ( 10 ) + "ALAT=" + str ( round ( ctrl_dict [ "ALAT" ] , sigfigs ) ) )
for l , l... |
def hquad ( zsrc , zrec , lsrc , lrec , off , factAng , depth , ab , etaH , etaV , zetaH , zetaV , xdirect , quadargs , use_ne_eval , msrc , mrec ) :
r"""Hankel Transform using the ` ` QUADPACK ` ` library .
This routine uses the ` ` scipy . integrate . quad ` ` module , which in turn makes
use of the Fortran l... | # Get quadargs
rtol , atol , limit , a , b , pts_per_dec = quadargs
# Get required lambdas
la = np . log10 ( a )
lb = np . log10 ( b )
ilambd = np . logspace ( la , lb , ( lb - la ) * pts_per_dec + 1 )
# Call the kernel
PJ0 , PJ1 , PJ0b = kernel . wavenumber ( zsrc , zrec , lsrc , lrec , depth , etaH , etaV , zetaH , z... |
def concat ( self , second_iterable ) :
'''Concatenates two sequences .
Note : This method uses deferred execution .
Args :
second _ iterable : The sequence to concatenate on to the sequence .
Returns :
A Queryable over the concatenated sequences .
Raises :
ValueError : If the Queryable is closed ( ) ... | if self . closed ( ) :
raise ValueError ( "Attempt to call concat() on a closed Queryable." )
if not is_iterable ( second_iterable ) :
raise TypeError ( "Cannot compute concat() with second_iterable of " "non-iterable {0}" . format ( str ( type ( second_iterable ) ) [ 7 : - 1 ] ) )
return self . _create ( itert... |
def safe_unichr ( codepoint ) :
"""Safely return a Unicode string of length one ,
containing the Unicode character with given codepoint .
: param int codepoint : the codepoint
: rtype : string""" | if is_py2_narrow_build ( ) :
return ( "\\U%08x" % codepoint ) . decode ( "unicode-escape" )
elif PY2 :
return unichr ( codepoint )
return chr ( codepoint ) |
def parse_v4_unit_placement ( placement_str ) :
"""Return a UnitPlacement for bundles version 4 , given a placement string .
See https : / / github . com / juju / charmstore / blob / v4 / docs / bundles . md
Raise a ValueError if the placement is not valid .""" | placement = placement_str
container = machine = service = unit = ''
if ':' in placement :
try :
container , placement = placement_str . split ( ':' )
except ValueError :
msg = 'placement {} is malformed, too many parts' . format ( placement_str )
raise ValueError ( msg . encode ( 'utf-8'... |
def choose_font ( self , font = None ) :
"""Choose a font for the label through a dialog""" | fmt_widget = self . parent ( )
if font is None :
if self . current_font :
font , ok = QFontDialog . getFont ( self . current_font , fmt_widget , 'Select %s font' % self . fmto_name , QFontDialog . DontUseNativeDialog )
else :
font , ok = QFontDialog . getFont ( fmt_widget )
if not ok :
... |
def _collection_default_options ( self , name , ** kargs ) :
"""Get a Collection instance with the default settings .""" | wc = ( self . write_concern if self . write_concern . acknowledged else WriteConcern ( ) )
return self . get_collection ( name , codec_options = DEFAULT_CODEC_OPTIONS , read_preference = ReadPreference . PRIMARY , write_concern = wc ) |
def constraint_range_dict ( self , * args , ** kwargs ) :
"""Creates a list of dictionaries which each give a constraint for a certain
section of the dimension .
bins arguments overwrites resolution""" | bins = self . bins ( * args , ** kwargs )
return [ { self . name + '__gte' : a , self . name + '__lt' : b } for a , b in zip ( bins [ : - 1 ] , bins [ 1 : ] ) ]
space = self . space ( * args , ** kwargs )
resolution = space [ 1 ] - space [ 0 ]
return [ { self . name + '__gte' : s , self . name + '__lt' : s + resolution... |
def _return_response_and_status_code ( response , json_results = True ) :
"""Output the requests response content or content as json and status code
: rtype : dict
: param response : requests response object
: param json _ results : Should return JSON or raw content
: return : dict containing the response c... | if response . status_code == requests . codes . ok :
return dict ( results = response . json ( ) if json_results else response . content , response_code = response . status_code )
elif response . status_code == 400 :
return dict ( error = 'package sent is either malformed or not within the past 24 hours.' , res... |
def AppendFlagsIntoFile ( self , filename ) :
"""Appends all flags assignments from this FlagInfo object to a file .
Output will be in the format of a flagfile .
NOTE : MUST mirror the behavior of the C + + AppendFlagsIntoFile
from http : / / code . google . com / p / google - gflags
Args :
filename : str... | with open ( filename , 'a' ) as out_file :
out_file . write ( self . FlagsIntoString ( ) ) |
def bin_tree_to_list ( root ) :
"""type root : root class""" | if not root :
return root
root = bin_tree_to_list_util ( root )
while root . left :
root = root . left
return root |
def assertDateTimesFrequencyEqual ( self , sequence , frequency , msg = None ) :
'''Fail if any elements in ` ` sequence ` ` aren ' t separated by
the expected ` ` fequency ` ` .
Parameters
sequence : iterable
frequency : timedelta
msg : str
If not provided , the : mod : ` marbles . mixins ` or
: mod ... | # TODO ( jsa ) : check that elements in sequence are dates or
# datetimes , keeping in mind that sequence may contain null
# values
if not isinstance ( sequence , collections . Iterable ) :
raise TypeError ( 'First argument is not iterable' )
if not isinstance ( frequency , timedelta ) :
raise TypeError ( 'Seco... |
def _InnerAppendData ( self , prev_col_values , data , col_index ) :
"""Inner function to assist LoadData .""" | # We first check that col _ index has not exceeded the columns size
if col_index >= len ( self . __columns ) :
raise DataTableException ( "The data does not match description, too deep" )
# Dealing with the scalar case , the data is the last value .
if self . __columns [ col_index ] [ "container" ] == "scalar" :
... |
def unique ( list1 , list2 ) :
"""Get unique items in list1 that are not in list2
: return : Unique items only in list 1""" | set2 = set ( list2 )
list1_unique = [ x for x in tqdm ( list1 , desc = 'Unique' , total = len ( list1 ) ) if x not in set2 ]
return list1_unique |
def handleNotification ( self , req ) :
"""handles a notification request by calling the appropriete method the service exposes""" | name = req [ "method" ]
params = req [ "params" ]
try : # to get a callable obj
obj = getMethodByName ( self . service , name )
rslt = obj ( * params )
except :
pass |
def exif_name ( self ) :
'''Name of file in the form { lat } _ { lon } _ { ca } _ { datetime } _ { filename } _ { hash }''' | mapillary_description = json . loads ( self . extract_image_description ( ) )
lat = None
lon = None
ca = None
date_time = None
if "MAPLatitude" in mapillary_description :
lat = mapillary_description [ "MAPLatitude" ]
if "MAPLongitude" in mapillary_description :
lon = mapillary_description [ "MAPLongitude" ]
if ... |
def _parse_type_rule ( ctype , typespec ) :
"""Parse a content type rule . Unlike the other rules , content type
rules are more complex , since both selected content type and API
version must be expressed by one rule . The rule is split on
whitespace , then the components beginning with " type : " and
" ver... | params = { 'param' : { } }
for token in quoted_split ( typespec , ' ' , quotes = '"\'' ) :
if not token :
continue
tok_type , _sep , tok_val = token . partition ( ':' )
# Validate the token type
if not tok_val :
LOG . warn ( "%s: Invalid type token %r" % ( ctype , token ) )
conti... |
def smoothpolygon ( document , coords ) :
"smoothed filled polygon" | element = document . createElement ( 'path' )
path = [ ]
points = [ ( coords [ i ] , coords [ i + 1 ] ) for i in range ( 0 , len ( coords ) , 2 ) ]
def pt ( points ) :
p = points
n = len ( points )
for i in range ( 0 , len ( points ) ) :
a = p [ ( i - 1 ) % n ]
b = p [ i ]
c = p [ ( ... |
def default_child_path ( path ) :
"""Return the default child of the parent path , if it exists , else path .
As an example , if the path ` parent ` show show the page ` parent / child ` by
default , this method will return ` parent / child ` given ` parent ` .
If ` parent / child ` should show ` parent / chi... | try : # Recurse until we find a path with no default child
child_path = default_child_path ( current_app . config [ 'DEFAULT_CHILDREN' ] [ path ] )
except KeyError :
child_path = path
return child_path |
def md5sum ( self ) :
"""Check to see if the file exists on the device
: return :""" | cmd = 'show file {dir}:{bin} md5sum' . format ( dir = self . DESTDIR , bin = self . image )
run = self . device . api . exec_opcmd
try :
got = run ( cmd )
return got . get ( 'file_content_md5sum' ) . strip ( )
except : # NOQA
return None |
def clusterStatus ( self ) :
"""Returns a dict of cluster nodes and their status information""" | servers = yield self . client . keys ( 'rhumba.server.*.heartbeat' )
d = { }
now = time . time ( )
for s in servers :
sname = s . split ( '.' , 2 ) [ - 1 ] . rsplit ( '.' , 1 ) [ 0 ]
last = yield self . client . get ( 'rhumba.server.%s.heartbeat' % sname )
if not last :
last = 0
status = yield s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.