signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def dumps ( o , encoder = None ) :
"""Stringifies input dict as toml
Args :
o : Object to dump into toml
preserve : Boolean parameter . If true , preserve inline tables .
Returns :
String containing the toml corresponding to dict""" | retval = ""
if encoder is None :
encoder = TomlEncoder ( o . __class__ )
addtoretval , sections = encoder . dump_sections ( o , "" )
retval += addtoretval
outer_objs = [ id ( o ) ]
while sections :
section_ids = [ id ( section ) for section in sections ]
for outer_obj in outer_objs :
if outer_obj in... |
def getSynchronizationSources ( self ) :
"""Returns a : class : ` RTCRtpSynchronizationSource ` for each unique SSRC identifier
received in the last 10 seconds .""" | cutoff = clock . current_datetime ( ) - datetime . timedelta ( seconds = 10 )
sources = [ ]
for source , timestamp in self . __active_ssrc . items ( ) :
if timestamp >= cutoff :
sources . append ( RTCRtpSynchronizationSource ( source = source , timestamp = timestamp ) )
return sources |
def _getContextFactory ( path , workbench ) :
"""Get a context factory .
If the client already has a credentials at path , use them .
Otherwise , generate them at path . Notifications are reported to
the given workbench .""" | try :
return succeed ( getContextFactory ( path ) )
except IOError :
d = prompt ( workbench , u"E-mail entry" , u"Enter e-mail:" )
d . addCallback ( _makeCredentials , path , workbench )
d . addCallback ( lambda _result : getContextFactory ( path ) )
return d |
def logpdf ( self , mu ) :
"""Log PDF for Cauchy prior
Parameters
mu : float
Latent variable for which the prior is being formed over
Returns
- log ( p ( mu ) )""" | if self . transform is not None :
mu = self . transform ( mu )
return ss . cauchy . logpdf ( mu , self . loc0 , self . scale0 ) |
def get ( ) :
"""Returns the current version without importing pymds .""" | pkgnames = find_packages ( )
if len ( pkgnames ) == 0 :
raise ValueError ( "Can't find any packages" )
pkgname = pkgnames [ 0 ]
content = open ( join ( pkgname , '__init__.py' ) ) . read ( )
c = re . compile ( r"__version__ *= *('[^']+'|\"[^\"]+\")" )
m = c . search ( content )
if m is None :
raise ValueError (... |
def find ( expression , schema = None ) :
'''Gets an < expression > and optional < schema > .
< expression > should be a string of python code .
< schema > should be a dictionary mapping field names to types .''' | parser = SchemaFreeParser ( ) if schema is None else SchemaAwareParser ( schema )
return parser . parse ( expression ) |
def get_colormap ( name , * args , ** kwargs ) :
"""Obtain a colormap
Some colormaps can have additional configuration parameters . Refer to
their corresponding documentation for more information .
Parameters
name : str | Colormap
Colormap name . Can also be a Colormap for pass - through .
Examples
> ... | if isinstance ( name , BaseColormap ) :
cmap = name
else :
if not isinstance ( name , string_types ) :
raise TypeError ( 'colormap must be a Colormap or string name' )
if name not in _colormaps :
raise KeyError ( 'colormap name %s not found' % name )
cmap = _colormaps [ name ]
if ins... |
def deactivate ( self ) :
"""Stop heating / cooling and turn off the fan""" | if self . _driver and self . _driver . is_connected ( ) :
self . _driver . deactivate ( ) |
def exchange_pin ( self , pin ) :
"""Exchange one - use pin for an access _ token and request _ token .""" | params = { 'client_id' : self . client_id , 'client_secret' : self . client_secret , 'grant_type' : 'pin' , 'pin' : pin }
result = self . _send_request ( EXCHANGE_URL . format ( self . _base_url ) , params = params , method = 'POST' , data_field = None )
self . access_token = result [ 'access_token' ]
self . refresh_to... |
def load_multiple ( paths = None , first_data_line = "auto" , filters = "*.*" , text = "Select some files, FACEHEAD." , default_directory = "default_directory" , quiet = True , header_only = False , transpose = False , ** kwargs ) :
"""Loads a list of data files into a list of databox data objects .
Returns said ... | if paths == None :
paths = _s . dialogs . load_multiple ( filters , text , default_directory )
if paths is None :
return
datas = [ ]
for path in paths :
if _os . path . isfile ( path ) :
datas . append ( load ( path = path , first_data_line = first_data_line , filters = filters , text = text , defau... |
def _compute_magnitude_term ( self , C , rup ) :
"""This computes the term f1 equation 8 Drouet & Cotton ( 2015)""" | return C [ 'c2' ] * ( rup . mag - 8.0 ) + C [ 'c3' ] * ( rup . mag - 8.0 ) ** 2 |
def _init_c2ps ( self , go_sources , traverse_child ) :
"""Traverse up children .""" | if not traverse_child :
return { }
c2ps = defaultdict ( set )
goids_seen = set ( )
go2obj = self . go2obj
for goid_src in go_sources :
goobj_src = go2obj [ goid_src ]
if goid_src not in goids_seen : # # F self . _ traverse _ child _ objs ( c2ps , goobj _ src , go2obj , goids _ seen )
self . _travers... |
def sha256sum ( path , blocksize = 65536 ) :
"""Computes the SHA256 signature of a file to verify that the file has not
been modified in transit and that it is the correct version of the data .""" | sig = hashlib . sha256 ( )
with open ( path , 'rb' ) as f :
buf = f . read ( blocksize )
while len ( buf ) > 0 :
sig . update ( buf )
buf = f . read ( blocksize )
return sig . hexdigest ( ) |
def _propagate_incompatibility ( self , incompatibility ) : # type : ( Incompatibility ) - > Union [ str , _ conflict , None ]
"""If incompatibility is almost satisfied by _ solution , adds the
negation of the unsatisfied term to _ solution .
If incompatibility is satisfied by _ solution , returns _ conflict . ... | # The first entry in incompatibility . terms that ' s not yet satisfied by
# _ solution , if one exists . If we find more than one , _ solution is
# inconclusive for incompatibility and we can ' t deduce anything .
unsatisfied = None
for term in incompatibility . terms :
relation = self . _solution . relation ( ter... |
def _get_all_field_lines ( self ) :
"""Returns all lines that represent the fields of the layer ( both their names and values ) .""" | for field in self . _get_all_fields_with_alternates ( ) : # Change to yield from
for line in self . _get_field_or_layer_repr ( field ) :
yield line |
def do_reference ( self , parent = None , ident = 0 ) :
"""Handles a TC _ REFERENCE opcode
: param parent :
: param ident : Log indentation level
: return : The referenced object""" | ( handle , ) = self . _readStruct ( ">L" )
log_debug ( "## Reference handle: 0x{0:X}" . format ( handle ) , ident )
ref = self . references [ handle - self . BASE_REFERENCE_IDX ]
log_debug ( "###-> Type: {0} - Value: {1}" . format ( type ( ref ) , ref ) , ident )
return ref |
def _xml_namespace_strip ( root ) : # type : ( ET . Element ) - > None
"""Strip the XML namespace prefix from all element tags under the given root Element .""" | if '}' not in root . tag :
return
# Nothing to do , no namespace present
for element in root . iter ( ) :
if '}' in element . tag :
element . tag = element . tag . split ( '}' ) [ 1 ]
else : # pragma : no cover
# We should never get here . If there is a namespace , then the namespace should be
... |
def list_policies ( region = None , key = None , keyid = None , profile = None ) :
'''List policies .
CLI Example :
. . code - block : : bash
salt myminion boto _ iam . list _ policies''' | conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
try :
policies = [ ]
for ret in __utils__ [ 'boto.paged_call' ] ( conn . list_policies ) :
policies . append ( ret . get ( 'list_policies_response' , { } ) . get ( 'list_policies_result' , { } ) . get ( 'policies' ) )
... |
def parse_tag ( template , l_del , r_del ) :
"""Parse a tag from a template""" | global _CURRENT_LINE
global _LAST_TAG_LINE
tag_types = { '!' : 'comment' , '#' : 'section' , '^' : 'inverted section' , '/' : 'end' , '>' : 'partial' , '=' : 'set delimiter?' , '{' : 'no escape?' , '&' : 'no escape' }
# Get the tag
try :
tag , template = template . split ( r_del , 1 )
except ValueError :
raise ... |
def is_entailed_by ( self , other ) :
"""Whether all of self ' s keys ( and values ) are in ( and within ) other ' s""" | for ( s_key , s_val ) in self :
if s_key in other :
if not other [ s_key ] . entails ( s_val ) :
return False
else :
return False
return True |
def do_preferrep ( self , line ) :
"""preferrep < member node > [ member node . . . ] Add one or more preferred Member
Nodes to replication policy .""" | mns = self . _split_args ( line , 1 , - 1 )
self . _command_processor . get_session ( ) . get_replication_policy ( ) . add_preferred ( mns )
self . _print_info_if_verbose ( "Set {} as preferred replication target(s)" . format ( ", " . join ( mns ) ) ) |
def create_rackservers ( self ) :
"""Get an instance of rackservers services facade .""" | return RackServers ( self . networkapi_url , self . user , self . password , self . user_ldap ) |
def _GetDataStreams ( self ) :
"""Retrieves the data streams .
Returns :
list [ DataStream ] : data streams .""" | if self . _data_streams is None :
if self . _directory is None :
self . _directory = self . _GetDirectory ( )
self . _data_streams = [ ]
# It is assumed that directory and link file entries typically
# do not have data streams .
if not self . _directory and not self . link :
data_str... |
def _convert_to_ast ( self , data_e , size_e = None ) :
"""Make an AST out of concrete @ data _ e""" | if type ( data_e ) is bytes : # Convert the string into a BVV , * regardless of endness *
bits = len ( data_e ) * self . state . arch . byte_width
data_e = self . state . solver . BVV ( data_e , bits )
elif type ( data_e ) is int :
data_e = self . state . solver . BVV ( data_e , size_e * self . state . arch... |
def init_config ( config_file = None ) :
"""Initialize the configuration from a config file .
The values in config _ file will override those already loaded from the default
configuration file ( defaults . cfg , in current package ) .
This method does not setup logging .
@ param config _ file : The path to ... | global config
if config_file and os . path . exists ( config_file ) :
read = config . read ( [ config_file ] )
if not read :
raise ValueError ( "Could not read configuration from file: %s" % config_file ) |
def expirePassword ( self , hours = "now" ) :
"""sets a time when a user must reset their password""" | params = { "f" : "json" }
expiration = - 1
if isinstance ( hours , str ) :
if expiration == "now" :
expiration = - 1
elif expiration == "never" :
expiration = 0
else :
expiration = - 1
elif isinstance ( expiration , ( int , long ) ) :
dt = datetime . now ( ) + timedelta ( hours =... |
def handle_container_output_args ( options , parser ) :
"""Handle the options specified by add _ container _ output _ args ( ) .
@ return : a dict that can be used as kwargs for the ContainerExecutor . execute _ run ( )""" | if options . result_files :
result_files_patterns = [ os . path . normpath ( p ) for p in options . result_files if p ]
for pattern in result_files_patterns :
if pattern . startswith ( ".." ) :
parser . error ( "Invalid relative result-files pattern '{}'." . format ( pattern ) )
else :
r... |
def get_formatted_size ( self ) :
"""Obtains the size of the volume in a human - readable format ( i . e . in TiBs , GiBs or MiBs ) .""" | if self . size is not None :
if self . size < 1024 :
return "{0} B" . format ( self . size )
elif self . size < 1024 ** 2 :
return "{0} KiB" . format ( round ( self . size / 1024 , 2 ) )
elif self . size < 1024 ** 3 :
return "{0} MiB" . format ( round ( self . size / 1024 ** 2 , 2 ) ... |
def _compare_rows ( from_recs , to_recs , keys ) :
"Return the set of keys which have changed ." | return set ( k for k in keys if sorted ( from_recs [ k ] . items ( ) ) != sorted ( to_recs [ k ] . items ( ) ) ) |
def find_field ( self , messages ) :
"""Wrapper method selecting the backend to assign the protocol field .
Various strategies are possible e . g . :
1 ) Heuristics e . g . for Preamble
2 ) Scoring based e . g . for Length
3 ) Fulltext search for addresses based on participant subgroups
: param messages :... | try :
if self . backend == self . Backend . python :
self . _py_find_field ( messages )
elif self . backend == self . Backend . cython :
self . _cy_find_field ( messages )
elif self . backend == self . Backend . plainc :
self . _c_find_field ( messages )
else :
raise Valu... |
def asZip ( self ) :
"""Return a serialised zip archive containing :
- callgrind profiling statistics ( cachegrind . out . pprofile )
- any SQL query issued via ZMySQLDA ( query _ * . sql )
- any persistent object load via ZODB . Connection ( ZODB _ setstate . txt )
- any path argument given to unrestricted... | out = BytesIO ( )
with zipfile . ZipFile ( out , mode = 'w' , compression = zipfile . ZIP_DEFLATED , ) as outfile :
for path , data , _ in self . _iterOutFiles ( ) :
outfile . writestr ( path , data )
return out . getvalue ( ) , 'application/zip' |
def writeByteArray ( self , n ) :
"""Writes a L { ByteArray } to the data stream .
@ param n : The L { ByteArray } data to be encoded to the AMF3 data stream .
@ type n : L { ByteArray }""" | self . stream . write ( TYPE_BYTEARRAY )
ref = self . context . getObjectReference ( n )
if ref != - 1 :
self . _writeInteger ( ref << 1 )
return
self . context . addObject ( n )
buf = str ( n )
l = len ( buf )
self . _writeInteger ( l << 1 | REFERENCE_BIT )
self . stream . write ( buf ) |
def string2dt ( self , s , lower_bound = None ) :
"""Return datetime from a given string .""" | original_s = s
result = { }
dt = None
# if s is completely empty , return start or end ,
# depending on what parameter is evaluated
if s == '' :
return self . end if lower_bound else self . start
# first try to match the defined regexes
for idx in self . dtRegexes :
regex = self . dtRegexes [ idx ]
mo = reg... |
def request_get_variable_json ( self , py_db , request , thread_id ) :
''': param VariablesRequest request :''' | py_db . post_method_as_internal_command ( thread_id , internal_get_variable_json , request ) |
def buffer_typechecks_and_display ( self , call_id , payload ) :
"""Adds typecheck events to the buffer , and displays them right away .
This is a workaround for this issue :
https : / / github . com / ensime / ensime - server / issues / 1616""" | self . buffer_typechecks ( call_id , payload )
self . editor . display_notes ( self . buffered_notes ) |
def compile ( self , name , contents , path = None ) :
"""Compile the given Thrift document into a Python module .
The generated module contains ,
. . py : attribute : : _ _ services _ _
A collection of generated classes for all services defined in the
thrift file .
. . versionchanged : : 1.0
Renamed fr... | assert name
if path :
path = os . path . abspath ( path )
if path in self . _module_specs :
return self . _module_specs [ path ]
module_spec = ModuleSpec ( name , self . protocol , path , contents )
if path :
self . _module_specs [ path ] = module_spec
program = self . parser . parse ( contents )
he... |
def remove_prefix ( self , prefix ) :
"""Removes prefix from this set . This is a no - op if the prefix
doesn ' t exist in it .""" | if prefix not in self . __prefix_map :
return
ni = self . __lookup_prefix ( prefix )
ni . prefixes . discard ( prefix )
del self . __prefix_map [ prefix ]
# If we removed the preferred prefix , find a new one .
if ni . preferred_prefix == prefix :
ni . preferred_prefix = next ( iter ( ni . prefixes ) , None ) |
def save ( self , obj ) :
"""Save current instance - as per the gludb spec .""" | cur = self . _conn ( ) . cursor ( )
tabname = obj . __class__ . get_table_name ( )
index_names = obj . __class__ . index_names ( ) or [ ]
col_names = [ 'id' , 'value' ] + index_names
value_holders = [ '%s' ] * len ( col_names )
updates = [ '%s = EXCLUDED.%s' % ( cn , cn ) for cn in col_names [ 1 : ] ]
if not obj . id :... |
def loseConnection ( self ) :
"""Close the connection and terminate the exiftool process .
@ rtype : C { Deferred }
@ return : A deferred whose callback will be invoked when the connection
was closed .""" | if self . _stopped :
result = self . _stopped
elif self . connected :
result = defer . Deferred ( )
self . _stopped = result
self . transport . write ( b'\n' . join ( ( b'-stay_open' , b'False' , b'' ) ) )
else : # Already disconnected .
result = defer . succeed ( self )
return result |
def spec ( self ) :
"""Return a dict with values that can be fed directly into SelectiveRowGenerator""" | return dict ( headers = self . header_lines , start = self . start_line , comments = self . comment_lines , end = self . end_line ) |
def set_label ( self , label ) :
"""Set label of Dataset .
Parameters
label : list , numpy 1 - D array , pandas Series / one - column DataFrame or None
The label information to be set into Dataset .
Returns
self : Dataset
Dataset with set label .""" | self . label = label
if self . handle is not None :
label = list_to_1d_numpy ( _label_from_pandas ( label ) , name = 'label' )
self . set_field ( 'label' , label )
return self |
def create_censor_file ( input_dset , out_prefix = None , fraction = 0.1 , clip_to = 0.1 , max_exclude = 0.3 , motion_file = None , motion_exclude = 1.0 ) :
'''create a binary censor file using 3dToutcount
: input _ dset : the input dataset
: prefix : output 1D file ( default : ` ` prefix ( input _ dset ) ` ` +... | ( outcount , perc_outliers ) = nl . qc . outcount ( input_dset , fraction )
info = nl . dset_info ( input_dset )
binarize = lambda o , f : [ oo < f for oo in o ]
perc_outliers = lambda o : 1. - ( sum ( o ) / float ( info . reps ) )
if motion_file :
with open ( motion_file , 'Ur' ) as f :
motion = [ max ( [ ... |
def note_content_data ( note , role ) :
"""Return the data for content
: param note : the note that holds the data
: type note : : class : ` jukeboxcore . djadapter . models . Note `
: param role : item data role
: type role : QtCore . Qt . ItemDataRole
: returns : data for the created date
: rtype : de... | if role == QtCore . Qt . DisplayRole or role == QtCore . Qt . EditRole :
return note . content |
def rpc_methods_registration ( ) :
"""Look into each module listed in settings . MODERNRPC _ METHODS _ MODULES , import each module and register
functions annotated with @ rpc _ method decorator in the registry""" | # In previous version , django - modern - rpc used the django cache system to store methods registry .
# It is useless now , so clean the cache from old data
clean_old_cache_content ( )
# For security ( and unit tests ) , make sure the registry is empty before registering rpc methods
registry . reset ( )
if not setting... |
def leaveEvent ( self , event ) :
"""Dismisses the hovered item when the tree is exited .
: param event | < QEvent >""" | hitem = self . hoveredItem ( )
hcol = self . hoveredColumn ( )
if ( hitem != None ) :
self . _hoveredItem = None
self . _hoveredColumn = - 1
rect = self . visualItemRect ( hitem )
rect . setWidth ( self . viewport ( ) . width ( ) )
self . viewport ( ) . update ( rect )
super ( XTreeWidget , self ) .... |
def unicode_safe ( s , encoding = i18n . default_encoding , errors = 'replace' ) :
"""Get unicode string without raising encoding errors . Unknown
characters of the given encoding will be ignored .
@ param s : the string to be decoded
@ type s : any object except None
@ return : if s is already unicode , re... | assert s is not None , "argument to unicode_safe was None"
if isinstance ( s , unicode ) : # s is already unicode , nothing to do
return s
return unicode ( str ( s ) , encoding , errors ) |
def _offsetscounts ( self ) :
"""Return simplified offsets and bytecounts .""" | if self . is_contiguous :
offset , bytecount = self . is_contiguous
return [ offset ] , [ bytecount ]
if self . is_tiled :
return self . dataoffsets , self . databytecounts
return clean_offsetscounts ( self . dataoffsets , self . databytecounts ) |
def update_thumbnail ( api_key , api_secret , video_key , position = 7.0 , ** kwargs ) :
"""Function which updates the thumbnail for an EXISTING video utilizing position parameter .
This function is useful for selecting a new thumbnail from with the already existing video content .
Instead of position parameter... | jwplatform_client = jwplatform . Client ( api_key , api_secret )
logging . info ( "Updating video thumbnail." )
try :
response = jwplatform_client . videos . thumbnails . update ( video_key = video_key , position = position , # Parameter which specifies seconds into video to extract thumbnail from .
** kwargs )... |
def update_variable ( self , variable , value ) -> None :
"""Assign the given value ( s ) to the given target or base variable .
If the assignment fails , | ChangeItem . update _ variable | raises an
error like the following :
> > > from hydpy . core . examples import prepare _ full _ example _ 2
> > > hp ,... | try :
variable ( value )
except BaseException :
objecttools . augment_excmessage ( f'When trying to update a target variable of ' f'{objecttools.classname(self)} `{self.name}` ' f'with the value(s) `{value}`' ) |
def _same_day_ids ( self ) :
""": return : ids of occurrences that finish on the same day that they
start , or midnight the next day .""" | # we can pre - filter to return only occurrences that are < = 24h long ,
# but until at least the ` _ _ date ` can be used in F ( ) statements
# we ' ll have to refine manually
qs = self . filter ( end__lte = F ( 'start' ) + timedelta ( days = 1 ) )
# filter occurrences to those sharing the same end date , or
# midnigh... |
def is_point_in_rect ( self , pt_x , pt_y ) :
"""Returns True iif point is inside the rectangle ( border included )
Parameters
* pt _ x : Number
\t x - value of point
* pt _ y : Number
\t y - value of point""" | x_min , x_max , y_min , y_max = self . get_bbox ( )
return x_min <= pt_x <= x_max and y_min <= pt_y <= y_max |
def migrate ( config ) :
"""Perform a migration according to config .
: param config : The configuration to be applied
: type config : Config""" | webapp = WebApp ( config . web_host , config . web_port , custom_maintenance_file = config . web_custom_html )
webserver = WebServer ( webapp )
webserver . daemon = True
webserver . start ( )
migration_parser = YamlParser . parse_from_file ( config . migration_file )
migration = migration_parser . parse ( )
database = ... |
def _exists ( self , path ) :
"""S3 directory is not S3Ojbect .""" | if path . endswith ( '/' ) :
return True
return self . storage . exists ( path ) |
def get_pidfile_path ( working_dir ) :
"""Get the PID file path .""" | pid_filename = virtualchain_hooks . get_virtual_chain_name ( ) + ".pid"
return os . path . join ( working_dir , pid_filename ) |
def get_redirect ( request ) :
"""Create a HTTP redirect response that removes the token from the URL .""" | params = request . GET . copy ( )
params . pop ( TOKEN_NAME )
url = request . path
if params :
url += '?' + urlencode ( params )
return redirect ( url ) |
def _factory ( importname , base_class_type , path = None , * args , ** kargs ) :
'''Load a module of a given base class type
Parameter
importname : string
Name of the module , etc . converter
base _ class _ type : class type
E . g converter
path : Absoulte path of the module
Neede for extensions . If... | def is_base_class ( item ) :
return isclass ( item ) and item . __module__ == importname
if path : # Needed to find the module in forked processes ; if you know a better
# way tell me !
sys . path . append ( path )
# Absolute full path of python module
absolute_path = os . path . join ( path , importnam... |
def remove_input_link ( self , process_code , input_code ) :
"""Remove an input ( technosphere or biosphere exchange ) from a process , resolving all parameter issues""" | # 1 . find correct process
# 2 . find correct exchange
# 3 . remove that exchange
# 4 . check for parameter conflicts ?
# 4 . run parameter scan to rebuild matrices ?
# print ( process _ code , input _ code )
process = self . database [ 'items' ] [ process_code ]
exchanges = process [ 'exchanges' ]
initial_count = len ... |
def dir_import_table ( self ) :
"""import table is terminated by a all - null entry , so we have to
check for that""" | import_header = list ( self . optional_data_directories ) [ 1 ]
import_offset = self . resolve_rva ( import_header . VirtualAddress )
i = 0
while True :
offset = import_offset + i * Import_DirectoryTable . get_size ( )
idt = Import_DirectoryTable ( self . stream , offset , self )
if idt . is_empty ( ) :
... |
def process_amendments ( congress ) :
"""Traverse amendments for a project""" | amend_dir = "{0}/{1}/amendments" . format ( congress [ 'src' ] , congress [ 'congress' ] )
logger . info ( "Processing Amendments for {0}" . format ( congress [ 'congress' ] ) )
amendments = [ ]
for root , dirs , files in os . walk ( amend_dir ) :
if "data.json" in files and "text-versions" not in root :
fi... |
def int32_to_negative ( int32 ) :
"""Checks if a suspicious number ( e . g . ligand position ) is in fact a negative number represented as a
32 bit integer and returns the actual number .""" | dct = { }
if int32 == 4294967295 : # Special case in some structures ( note , this is just a workaround )
return - 1
for i in range ( - 1000 , - 1 ) :
dct [ np . uint32 ( i ) ] = i
if int32 in dct :
return dct [ int32 ]
else :
return int32 |
def _groupby_and_merge ( by , on , left , right , _merge_pieces , check_duplicates = True ) :
"""groupby & merge ; we are always performing a left - by type operation
Parameters
by : field to group
on : duplicates field
left : left frame
right : right frame
_ merge _ pieces : function for merging
chec... | pieces = [ ]
if not isinstance ( by , ( list , tuple ) ) :
by = [ by ]
lby = left . groupby ( by , sort = False )
# if we can groupby the rhs
# then we can get vastly better perf
try : # we will check & remove duplicates if indicated
if check_duplicates :
if on is None :
on = [ ]
eli... |
def find_first_duplicate_character ( input_str : str ) -> str :
"""This function identifies the first duplicate character in a given string .
If there are no repeated characters , it returns ' None ' as default .
Examples :
find _ first _ duplicate _ character ( ' abcabc ' )
find _ first _ duplicate _ chara... | for index , char in enumerate ( input_str ) :
if input_str [ : index + 1 ] . count ( char ) > 1 :
return char
return 'None' |
def get_var ( self , key ) :
'Retrieve one saved variable from the database .' | vt = quote ( self . __vars_table )
data = self . execute ( u'SELECT * FROM %s WHERE `key` = ?' % vt , [ key ] , commit = False )
if data == [ ] :
raise NameError ( u'The DumpTruck variables table doesn\'t have a value for %s.' % key )
else :
tmp = quote ( self . __vars_table_tmp )
row = data [ 0 ]
self ... |
def parameters_as_string ( self ) :
"""Returns a comma - separated list of the parameters in the executable definition .""" | params = ", " . join ( [ p . name for p in self . ordered_parameters ] )
return params |
def _get_rh_methods ( rh ) :
"""Yield all HTTP methods in ` ` rh ` ` that are decorated
with schema . validate""" | for k , v in vars ( rh ) . items ( ) :
if all ( [ k in HTTP_METHODS , is_method ( v ) , hasattr ( v , "input_schema" ) ] ) :
yield ( k , v ) |
def setBuildProperty ( self , bid , name , value , source ) :
"""A kind of create _ or _ update , that ' s between one or two queries per
call""" | def thd ( conn ) :
bp_tbl = self . db . model . build_properties
self . checkLength ( bp_tbl . c . name , name )
self . checkLength ( bp_tbl . c . source , source )
whereclause = sa . and_ ( bp_tbl . c . buildid == bid , bp_tbl . c . name == name )
q = sa . select ( [ bp_tbl . c . value , bp_tbl . c... |
def monthly_wind_conditions ( self ) :
"""A list of 12 monthly wind conditions that are used on the design days .""" | return [ WindCondition ( x , y ) for x , y in zip ( self . _monthly_wind , self . monthly_wind_dirs ) ] |
def on_disconnect ( client ) :
"""Sample on _ disconnect function .
Handles lost connections .""" | print "-- Lost connection to %s" % client . addrport ( )
CLIENT_LIST . remove ( client )
broadcast ( '%s leaves the conversation.\n' % client . addrport ( ) ) |
def with_fakes ( method ) :
"""Decorator that calls : func : ` fudge . clear _ calls ` before method ( ) and : func : ` fudge . verify ` afterwards .""" | @ wraps ( method )
def apply_clear_and_verify ( * args , ** kw ) :
clear_calls ( )
method ( * args , ** kw )
verify ( )
# if no exceptions
return apply_clear_and_verify |
def get_functions ( fname ) :
"""get a list of functions from a Python program""" | txt = ''
with open ( fname , 'r' ) as f :
for line in f :
if line . strip ( ) [ 0 : 4 ] == 'def ' :
txt += '<PRE>' + strip_text_after_string ( strip_text_after_string ( line , '#' ) [ 4 : ] , ':' ) + '</PRE>\n'
if line [ 0 : 5 ] == 'class' :
txt += '<PRE>' + strip_text_after_... |
def selector_default ( output_widget = None ) :
"""Capture selection events from the current figure , and apply the selections to Scatter objects .
Example :
> > > import ipyvolume as ipv
> > > ipv . figure ( )
> > > ipv . examples . gaussian ( )
> > > ipv . selector _ default ( )
> > > ipv . show ( )
... | fig = gcf ( )
if output_widget is None :
output_widget = ipywidgets . Output ( )
display ( output_widget )
def lasso ( data , other = None , fig = fig ) :
with output_widget :
inside = None
if data [ 'device' ] and data [ 'type' ] == 'lasso' :
region = shapely . geometry . Polygo... |
def add ( self ) :
"""Add a prefix .""" | # pass prefix to template - if we have any
if 'prefix' in request . params :
c . prefix = request . params [ 'prefix' ]
else :
c . prefix = ''
c . search_opt_parent = "all"
c . search_opt_child = "none"
return render ( '/prefix_add.html' ) |
def run ( self , cmd , stdin = None , marshal_output = True , ** kwargs ) :
"""Runs a p4 command and returns a list of dictionary objects
: param cmd : Command to run
: type cmd : list
: param stdin : Standard Input to send to the process
: type stdin : str
: param marshal _ output : Whether or not to mar... | records = [ ]
args = [ self . _executable , "-u" , self . _user , "-p" , self . _port ]
if self . _client :
args += [ "-c" , str ( self . _client ) ]
if marshal_output :
args . append ( '-G' )
if isinstance ( cmd , six . string_types ) :
raise ValueError ( 'String commands are not supported, please use a li... |
def fibonacci_approx ( n ) :
r"""approximate value ( due to numerical errors ) of fib ( n ) using closed form
expression
Args :
n ( int ) :
Returns :
int : the n - th fib number
CommandLine :
python - m utool . util _ alg fibonacci _ approx
Example :
> > > # DISABLE _ DOCTEST
> > > from utool . ... | sqrt_5 = math . sqrt ( 5 )
phi = ( 1 + sqrt_5 ) / 2
return ( ( phi ** n ) - ( - phi ) ** ( - n ) ) / sqrt_5 |
def create_unique_id ( prefix , existing_ids ) :
"""Return a unique string ID from the prefix .
First check if the prefix is itself a unique ID in the set - like parameter
existing _ ids . If not , try integers in ascending order appended to the
prefix until a unique ID is found .""" | if prefix in existing_ids :
suffix = 1
while True :
new_id = '{}_{}' . format ( prefix , suffix )
if new_id not in existing_ids :
return new_id
suffix += 1
return prefix |
def _proxy ( self ) :
"""Generate an instance context for the instance , the context is capable of
performing various actions . All instance actions are proxied to the context
: returns : EntityContext for this EntityInstance
: rtype : twilio . rest . authy . v1 . service . entity . EntityContext""" | if self . _context is None :
self . _context = EntityContext ( self . _version , service_sid = self . _solution [ 'service_sid' ] , identity = self . _solution [ 'identity' ] , )
return self . _context |
def poll_ignore_interrupts ( fds , timeout = None ) :
'''Simple wrapper around poll to register file descriptors and
ignore signals .''' | if timeout is not None :
end_time = time . time ( ) + timeout
poller = select . poll ( )
for fd in fds :
poller . register ( fd , select . POLLIN | select . POLLPRI | select . POLLHUP | select . POLLERR )
while True :
try :
timeout_ms = None if timeout is None else timeout * 1000
results = p... |
def merge ( self , carts = None , new_cart_name = None ) :
"""` carts ` - A list of cart names
` new _ cart _ name ` - Resultant cart name
Merge the contents of N carts into a new cart
TODO : Sanity check that each cart in ` carts ` exists . Try
' juicer pull ' ing carts that can ' t be located locally . Th... | if new_cart_name is not None :
cart_name = new_cart_name
else :
cart_name = carts [ 0 ]
result_cart = juicer . common . Cart . Cart ( cart_name )
items_hash = { }
for cart in carts : # 1 . Grab items from each cart and shit them into result _ cart
tmpcart = juicer . common . Cart . Cart ( cart , autoload = ... |
def period ( start , end , absolute = False # type : DateTime # type : DateTime # type : bool
) : # type : ( . . . ) - > Period
"""Create a Period instance .""" | return Period ( start , end , absolute = absolute ) |
def export ( self , out_filename ) :
"""Export desired threads as a zipfile to out _ filename .""" | with zipfile . ZipFile ( out_filename , 'w' , zipfile . ZIP_DEFLATED ) as arc :
id_list = list ( self . get_thread_info ( ) )
for num , my_info in enumerate ( id_list ) :
logging . info ( 'Working on item %i : %s' , num , my_info [ 'number' ] )
my_thread = GitHubCommentThread ( self . gh_info . ... |
def get_distributions ( self ) :
"""Retrives the distributions installed on the library path of the environment
: return : A set of distributions found on the library path
: rtype : iterator""" | pkg_resources = self . safe_import ( "pkg_resources" )
libdirs = self . base_paths [ "libdirs" ] . split ( os . pathsep )
dists = ( pkg_resources . find_distributions ( libdir ) for libdir in libdirs )
for dist in itertools . chain . from_iterable ( dists ) :
yield dist |
def expectation ( pyquil_prog : Program , pauli_sum : Union [ PauliSum , PauliTerm , np . ndarray ] , samples : int , qc : QuantumComputer ) -> float :
"""Compute the expectation value of pauli _ sum over the distribution generated from pyquil _ prog .
: param pyquil _ prog : The state preparation Program to calc... | if isinstance ( pauli_sum , np . ndarray ) : # debug mode by passing an array
wf = WavefunctionSimulator ( ) . wavefunction ( pyquil_prog )
wf = np . reshape ( wf . amplitudes , ( - 1 , 1 ) )
average_exp = np . conj ( wf ) . T . dot ( pauli_sum . dot ( wf ) ) . real
return average_exp
else :
if not ... |
def reindex ( self ) :
'''reindex waypoints''' | for i in range ( self . count ( ) ) :
w = self . wpoints [ i ]
w . seq = i
self . last_change = time . time ( ) |
def _draw_multiclass ( self ) :
"""Draw the precision - recall curves in the multiclass case""" | # TODO : handle colors better with a mapping and user input
if self . per_class :
for cls in self . classes_ :
precision = self . precision_ [ cls ]
recall = self . recall_ [ cls ]
label = "PR for class {} (area={:0.2f})" . format ( cls , self . score_ [ cls ] )
self . _draw_pr_curve... |
def _two_to_one ( datadir ) :
"""After this command , your environment will be converted to format version { }
and will not work with Datacats versions beyond and including 1.0.0.
This format version doesn ' t support multiple sites , and after this only your
" primary " site will be usable , though other sit... | _ , env_name = _split_path ( datadir )
print 'Making sure that containers are stopped...'
# New - style names
remove_container ( 'datacats_web_{}_primary' . format ( env_name ) )
remove_container ( 'datacats_postgres_{}_primary' . format ( env_name ) )
remove_container ( 'datacats_solr_{}_primary' . format ( env_name )... |
def _set_esp_auth ( self , v , load = False ) :
"""Setter method for esp _ auth , mapped from YANG variable / routing _ system / interface / ve / ipv6 / interface _ ospfv3 _ conf / authentication / ipsec _ auth _ key _ config / esp _ auth ( algorithm - type - ah )
If this variable is read - only ( config : false ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'hmac-sha1' : { 'value' : 2 } , u'hmac-md5' : { 'value' : 1 } } , ) , is_leaf = True , yang_name = "esp-auth" , rest_name = "esp... |
def get_token ( opts , tok ) :
'''Fetch the token data from the store .
: param opts : Salt master config options
: param tok : Token value to get
: returns : Token data if successful . Empty dict if failed .''' | redis_client = _redis_client ( opts )
if not redis_client :
return { }
serial = salt . payload . Serial ( opts )
try :
tdata = serial . loads ( redis_client . get ( tok ) )
return tdata
except Exception as err :
log . warning ( 'Authentication failure: cannot get token %s from redis: %s' , tok , err )
... |
def _loop_use_cache ( self , helper_function , num , fragment ) :
"""Synthesize all fragments using the cache""" | self . log ( [ u"Examining fragment %d (cache)..." , num ] )
fragment_info = ( fragment . language , fragment . filtered_text )
if self . cache . is_cached ( fragment_info ) :
self . log ( u"Fragment cached: retrieving audio data from cache" )
# read data from file , whose path is in the cache
file_handler ... |
def get_tags ( container = None , search_folders = None , file_list = None , return_unique = True ) :
'''get tags will return a list of tags that describe the software in an image ,
meaning inside of a paricular folder . If search _ folder is not defined , uses lib
: param container : if provided , will use con... | if file_list is None :
file_list = get_container_contents ( container , split_delim = '\n' ) [ 'all' ]
if search_folders == None :
search_folders = 'bin'
if not isinstance ( search_folders , list ) :
search_folders = [ search_folders ]
tags = [ ]
for search_folder in search_folders :
for file_name in fi... |
def impact_table_pdf_extractor ( impact_report , component_metadata ) :
"""Extracting impact summary of the impact layer .
For PDF generations
: param impact _ report : the impact report that acts as a proxy to fetch
all the data that extractor needed
: type impact _ report : safe . report . impact _ report... | # QGIS Composer needed certain context to generate the output
# - Map Settings
# - Substitution maps
# - Element settings , such as icon for picture file or image source
context = QGISComposerContext ( )
extra_args = component_metadata . extra_args
html_report_component_key = resolve_from_dictionary ( extra_args , [ 'h... |
def _argspec ( func ) :
"""For a callable , get the full argument spec
: type func : Callable
: rtype : list [ data . ArgumentSpec ]""" | assert isinstance ( func , collections . Callable ) , 'Argument must be a callable'
try :
sp = inspect . getargspec ( func ) if six . PY2 else inspect . getfullargspec ( func )
except TypeError : # inspect . getargspec ( ) fails for built - in functions
return [ ]
# Collect arguments with defaults
ret = [ ]
def... |
def _node_name ( self , concept ) :
"""Return a standardized name for a node given a Concept .""" | if ( # grounding threshold is specified
self . grounding_threshold is not None # The particular eidos ontology grounding ( un / wdi / fao ) is present
and concept . db_refs [ self . grounding_ontology ] # The grounding score is above the grounding threshold
and ( concept . db_refs [ self . grounding_ontology ] [ 0 ] [ ... |
def Indirect ( self , off ) :
"""Indirect retrieves the relative offset stored at ` offset ` .""" | N . enforce_number ( off , N . UOffsetTFlags )
return off + encode . Get ( N . UOffsetTFlags . packer_type , self . Bytes , off ) |
def assortativity_wei ( CIJ , flag = 0 ) :
'''The assortativity coefficient is a correlation coefficient between the
strengths ( weighted degrees ) of all nodes on two opposite ends of a link .
A positive assortativity coefficient indicates that nodes tend to link to
other nodes with the same or similar stren... | if flag == 0 : # undirected version
str = strengths_und ( CIJ )
i , j = np . where ( np . triu ( CIJ , 1 ) > 0 )
K = len ( i )
stri = str [ i ]
strj = str [ j ]
else :
ist , ost = strengths_dir ( CIJ )
# directed version
i , j = np . where ( CIJ > 0 )
K = len ( i )
if flag == 1 :... |
def create ( cls , env , filenames , trim = False ) :
"""Create and return a final graph .
Args :
env : An environment . Environment object
filenames : A list of filenames
trim : Whether to trim the dependencies of builtin and system files .
Returns :
An immutable ImportGraph with the recursive dependen... | import_graph = cls ( env )
for filename in filenames :
import_graph . add_file_recursive ( os . path . abspath ( filename ) , trim )
import_graph . build ( )
return import_graph |
def encode_kv_node ( keypath , child_node_hash ) :
"""Serializes a key / value node""" | if keypath is None or keypath == b'' :
raise ValidationError ( "Key path can not be empty" )
validate_is_bytes ( keypath )
validate_is_bytes ( child_node_hash )
validate_length ( child_node_hash , 32 )
return KV_TYPE_PREFIX + encode_from_bin_keypath ( keypath ) + child_node_hash |
def add_items ( self , items , index_items ) :
"""Add items to template if is template , else add in item list
: param items : items list to add
: type items : alignak . objects . item . Items
: param index _ items : Flag indicating if the items should be indexed on the fly .
: type index _ items : bool
:... | count_templates = 0
count_items = 0
generated_items = [ ]
for item in items :
if item . is_tpl ( ) :
self . add_template ( item )
count_templates = count_templates + 1
else :
new_items = self . add_item ( item , index_items )
count_items = count_items + max ( 1 , len ( new_items ... |
def sort_by_dependencies ( exts , retry = None ) :
"""Calculate the Feature Extractor Resolution Order .""" | sorted_ext , features_from_sorted = [ ] , set ( )
pending = [ ( e , 0 ) for e in exts ]
retry = len ( exts ) * 100 if retry is None else retry
while pending :
ext , cnt = pending . pop ( 0 )
if not isinstance ( ext , Extractor ) and not issubclass ( ext , Extractor ) :
msg = "Only Extractor instances ar... |
def fake_upload_from_url ( url ) :
"""Return a ' fake ' upload data record , so that upload errors
can be mitigated by using an original / alternative URL ,
especially when cross - loading from the web .""" | return parts . Bunch ( image = parts . Bunch ( animated = 'false' , bandwidth = 0 , caption = None , views = 0 , deletehash = None , hash = None , name = ( url . rsplit ( '/' , 1 ) + [ url ] ) [ 1 ] , title = None , type = 'image/*' , width = 0 , height = 0 , size = 0 , datetime = int ( time . time ( ) ) , # XXX was fm... |
def confirmdir ( self , target_directory ) :
"""Test that the target is actually a directory , raising OSError
if not .
Args :
target _ directory : Path to the target directory within the fake
filesystem .
Returns :
The FakeDirectory object corresponding to target _ directory .
Raises :
OSError : if... | try :
directory = self . resolve ( target_directory )
except IOError as exc :
self . raise_os_error ( exc . errno , target_directory )
if not directory . st_mode & S_IFDIR :
if self . is_windows_fs and IS_PY2 :
error_nr = errno . EINVAL
else :
error_nr = errno . ENOTDIR
self . raise_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.