signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def string_format ( data , out = 'nested' , opts = None , ** kwargs ) :
'''Return the outputter formatted string , removing the ANSI escape sequences .
data
The JSON serializable object .
out : ` ` nested ` `
The name of the output to use to transform the data . Default : ` ` nested ` ` .
opts
Dictionar... | if not opts :
opts = __opts__
return salt . output . string_format ( data , out , opts = opts , ** kwargs ) |
def _partial_precolor ( G , chi_ub ) :
"""In order to reduce the number of variables in the QUBO , we want to
color as many nodes as possible without affecting the min vertex
coloring . Without loss of generality , we can choose a single maximal
clique and color each node in it uniquely .
Returns
partial ... | # find a random maximal clique and give each node in it a unique color
v = next ( iter ( G ) )
clique = [ v ]
for u in G [ v ] :
if all ( w in G [ u ] for w in clique ) :
clique . append ( u )
partial_coloring = { v : c for c , v in enumerate ( clique ) }
chi_lb = len ( partial_coloring )
# lower bound for ... |
def crinfo_from_specific_data ( data , margin = 0 ) :
"""Create crinfo of minimum orthogonal nonzero block in input data .
: param data : input data
: param margin : add margin to minimum block
: return :""" | # hledáme automatický ořez , nonzero dá indexy
logger . debug ( "crinfo" )
logger . debug ( str ( margin ) )
nzi = np . nonzero ( data )
logger . debug ( str ( nzi ) )
if np . isscalar ( margin ) :
margin = [ margin ] * 3
x1 = np . min ( nzi [ 0 ] ) - margin [ 0 ]
x2 = np . max ( nzi [ 0 ] ) + margin [ 0 ] + 1
... |
def stringize ( self , rnf_profile = RnfProfile ( ) , ) :
"""Create RNF representation of this read .
Args :
read _ tuple _ id _ width ( int ) : Maximal expected string length of read tuple ID .
genome _ id _ width ( int ) : Maximal expected string length of genome ID .
chr _ id _ width ( int ) : Maximal ex... | sorted_segments = sorted ( self . segments , key = lambda x : ( x . genome_id * ( 10 ** 23 ) + x . chr_id * ( 10 ** 21 ) + ( x . left + ( int ( x . left == 0 ) * x . right - 1 ) ) * ( 10 ** 11 ) + x . right * ( 10 ** 1 ) + int ( x . direction == "F" ) ) )
segments_strings = [ x . stringize ( rnf_profile ) for x in sort... |
def get_fetch_request ( self , method , fetch_url , * args , ** kwargs ) :
"""This is handy if you want to modify the request right before passing it
to requests , or you want to do something extra special customized
: param method : string , the http method ( eg , GET , POST )
: param fetch _ url : string , ... | return requests . request ( method , fetch_url , * args , ** kwargs ) |
def parse_query ( self , query ) :
"""Parse query string using given grammar""" | tree = pypeg2 . parse ( query , Main , whitespace = "" )
return tree . accept ( self . converter ) |
def get ( self , repository , snapshot , params = None ) :
"""Retrieve information about a snapshot .
` < http : / / www . elastic . co / guide / en / elasticsearch / reference / current / modules - snapshots . html > ` _
: arg repository : A repository name
: arg snapshot : A comma - separated list of snapsh... | for param in ( repository , snapshot ) :
if param in SKIP_IN_PATH :
raise ValueError ( "Empty value passed for a required argument." )
return self . transport . perform_request ( 'GET' , _make_path ( '_snapshot' , repository , snapshot ) , params = params ) |
def add_auth ( self , req , ** kwargs ) :
"""Add AWS3 authentication to a request .
: type req : : class ` boto . connection . HTTPRequest `
: param req : The HTTPRequest object .""" | # This could be a retry . Make sure the previous
# authorization header is removed first .
if 'X-Amzn-Authorization' in req . headers :
del req . headers [ 'X-Amzn-Authorization' ]
req . headers [ 'X-Amz-Date' ] = formatdate ( usegmt = True )
req . headers [ 'X-Amz-Security-Token' ] = self . _provider . security_to... |
def MatrixSolveLs ( a , rhs , l2_reg ) :
"""Matrix least - squares solve op .""" | r = np . empty ( rhs . shape ) . astype ( a . dtype )
for coord in np . ndindex ( a . shape [ : - 2 ] ) :
pos = coord + ( Ellipsis , )
r [ pos ] = np . linalg . lstsq ( a [ pos ] , rhs [ pos ] ) [ 0 ]
return r , |
def normalizeDefaultLayerName ( value , font ) :
"""Normalizes default layer name .
* * * value * * must normalize as layer name with
: func : ` normalizeLayerName ` .
* * * value * * must be a layer in * * font * * .
* Returned value will be an unencoded ` ` unicode ` ` string .""" | value = normalizeLayerName ( value )
if value not in font . layerOrder :
raise ValueError ( "No layer with the name '%s' exists." % value )
return unicode ( value ) |
def collection ( self , name ) :
"""Returns a collection with the given name
: param name Collection name
: returns Collection""" | return Collection ( name = name , api_resource = self . api . collection ( name ) , api = self . api , ) |
def write_table ( table , filename ) :
"""Write a table to a file .
Parameters
table : Table
Table to be written
filename : str
Destination for saving table .
Returns
None""" | try :
if os . path . exists ( filename ) :
os . remove ( filename )
table . write ( filename )
log . info ( "Wrote {0}" . format ( filename ) )
except Exception as e :
if "Format could not be identified" not in e . message :
raise e
else :
fmt = os . path . splitext ( filenam... |
def host ( self ) -> str :
"""获取 host + port , 如果开启 proxy 开关 。 使用 X - Forwarded - Host 头""" | host = cast ( Optional [ str ] , None )
if self . proxy and 'X-Forwarded-Host' in self . _headers :
xhost = cast ( Optional [ str ] , self . get ( 'X-Forwarded-Host' ) )
if xhost is not None :
host = xhost . split ( "," ) [ 0 ] . strip ( )
host = host or cast ( str , self . get ( 'Host' ) )
return host |
def _substitute_file_uuids_throughout_template ( self , template , file_dependencies ) :
"""Anywhere in " template " that refers to a data object but does not
give a specific UUID , if a matching file can be found in " file _ dependencies " ,
we will change the data object reference to use that UUID . That way ... | if not isinstance ( template , dict ) : # Nothing to do if this is a reference to a previously imported template .
return
for input in template . get ( 'inputs' , [ ] ) :
self . _substitute_file_uuids_in_input ( input , file_dependencies )
for step in template . get ( 'steps' , [ ] ) :
self . _substitute_fi... |
def list ( self , out = sys . stdout ) :
"""Prints a listing of the properties to the
stream ' out ' which defaults to the standard output""" | out . write ( '-- listing properties --\n' )
for key , value in self . _properties . items ( ) :
out . write ( '' . join ( ( key , '=' , value , '\n' ) ) ) |
def incver ( self ) :
"""Increment all of the version numbers""" | d = { }
for p in self . __mapper__ . attrs :
if p . key in [ 'vid' , 'vname' , 'fqname' , 'version' , 'cache_key' ] :
continue
if p . key == 'revision' :
d [ p . key ] = self . revision + 1
else :
d [ p . key ] = getattr ( self , p . key )
n = Dataset ( ** d )
return n |
def clone ( self , ** kwargs ) :
"""Make a fresh thread with the same options . This is usually used on dead threads .""" | return ManholeThread ( self . get_socket , self . sigmask , self . start_timeout , connection_handler = self . connection_handler , daemon_connection = self . daemon_connection , ** kwargs ) |
def enqueue ( self , obj , * args , ** kwargs ) :
"""Enqueue a function call or : doc : ` job ` instance .
: param func : Function or : doc : ` job < job > ` . Must be serializable and
importable by : doc : ` worker < worker > ` processes .
: type func : callable | : doc : ` kq . Job < job > `
: param args ... | timestamp = int ( time . time ( ) * 1000 )
if isinstance ( obj , Job ) :
job_id = uuid . uuid4 ( ) . hex if obj . id is None else obj . id
func = obj . func
args = tuple ( ) if obj . args is None else obj . args
kwargs = { } if obj . kwargs is None else obj . kwargs
timeout = self . _timeout if obj ... |
def view ( template = None ) :
"""Create the Maintenance view
Must be instantiated
import maintenance _ view
MaintenanceView = maintenance _ view ( )
: param template _ : The directory containing the view pages
: return :""" | if not template :
template = "Juice/Plugin/MaintenancePage/index.html"
class Maintenance ( View ) :
@ classmethod
def register ( cls , app , ** kwargs ) :
super ( cls , cls ) . register ( app , ** kwargs )
if cls . get_config ( "APPLICATION_MAINTENANCE_ON" ) :
app . logger . info... |
def fanqie2mch ( fanqie , debug = False ) :
"""Convert a Fǎnqiè reading to it ' s MCH counterpart .
Important : we need to identify the medials in the xia - syllable . We also
need to make additional background - checks , since in the current form , the
approach is not error - prone and does not what it is ... | # check for gbk
fanqie = gbk2big5 ( fanqie )
# get normal vals
shangxia = chars2baxter ( fanqie )
# check for good fixed solutions in our dictionary
if fanqie [ 0 ] in _cd . GY [ 'sheng' ] :
shang = _cd . GY [ 'sheng' ] [ fanqie [ 0 ] ] + 'a'
else :
shang = shangxia [ 0 ]
xia = shangxia [ 1 ]
# check for bad va... |
def ParseFileObject ( self , parser_mediator , file_object ) :
"""Parses a Systemd journal file - like object .
Args :
parser _ mediator ( ParserMediator ) : parser mediator .
file _ object ( dfvfs . FileIO ) : a file - like object .
Raises :
UnableToParseFile : when the header cannot be parsed .""" | file_header_map = self . _GetDataTypeMap ( 'systemd_journal_file_header' )
try :
file_header , _ = self . _ReadStructureFromFileObject ( file_object , 0 , file_header_map )
except ( ValueError , errors . ParseError ) as exception :
raise errors . UnableToParseFile ( 'Unable to parse file header with error: {0!s... |
def update_one_time_key_counts ( self , counts ) :
"""Update data on one - time keys count and upload new ones if necessary .
Args :
counts ( dict ) : Counts of keys currently on the HS for each key type .""" | self . one_time_keys_manager . server_counts = counts
if self . one_time_keys_manager . should_upload ( ) :
logger . info ( 'Uploading new one-time keys.' )
self . upload_one_time_keys ( ) |
def writecooked ( self , text ) :
"""Put data directly into the output queue""" | # Ensure this is the only thread writing
self . OQUEUELOCK . acquire ( )
TelnetHandlerBase . writecooked ( self , text )
self . OQUEUELOCK . release ( ) |
def add_option ( self , option ) :
"""Add a new option to this key .
Parameters
option : Sized or str or int or float
A new option to add . This must have the same format with exsiting
options .
Raises
TypeError
If the format of the given ` ` option ` ` is different .""" | if len ( self . options ) == 0 :
self . options . append ( option )
else :
sized_op = isinstance ( option , ( list , tuple ) )
if self . _sized_op != sized_op :
raise TypeError ( "Option type is mismatched!" )
self . options . append ( option ) |
def update ( self , * args , ** kwargs ) :
"""Equivalent to the python dict update method .
Update the dictionary with the key / value pairs from other , overwriting
existing keys .
Args :
other ( dict ) : The source of key value pairs to add to headers
Keyword Args :
All keyword arguments are stored in... | for next_dict in chain ( args , ( kwargs , ) ) :
for k , v in next_dict . items ( ) :
self [ k ] = v |
def email ( self , name , to , from_addr , subject , body , header , owner = None , ** kwargs ) :
"""Create the Email TI object .
Args :
owner :
to :
from _ addr :
name :
subject :
header :
body :
* * kwargs :
Return :""" | return Email ( self . tcex , name , to , from_addr , subject , body , header , owner = owner , ** kwargs ) |
def tables_ ( self ) -> list :
"""Return a list of the existing tables in a database
: return : list of the table names
: rtype : list
: example : ` ` tables = ds . tables _ ( ) ` `""" | if self . _check_db ( ) == False :
return
try :
return self . _tables ( )
except Exception as e :
self . err ( e , "Can not print tables" ) |
def get_data ( self , url , * args , ** kwargs ) :
"""Gets data from url as text
Returns content under the provided url as text
Args :
* * url * * : address of the wanted data
. . versionadded : : 0.3.2
* * additional _ headers * * : ( optional ) Additional headers
to be used with request
Returns :
... | res = self . _conn . get ( url , headers = self . _prepare_headers ( ** kwargs ) )
if res . status_code == 200 :
return res . text
else :
return None |
def no_duplicates_constructor ( loader , node , deep = False ) :
"""Check for duplicate keys while loading YAML
https : / / gist . github . com / pypt / 94d747fe5180851196eb""" | mapping = { }
for key_node , value_node in node . value :
key = loader . construct_object ( key_node , deep = deep )
value = loader . construct_object ( value_node , deep = deep )
if key in mapping :
from intake . catalog . exceptions import DuplicateKeyError
raise DuplicateKeyError ( "while... |
def normalize_surfs ( in_file , transform_file , newpath = None ) :
"""Re - center GIFTI coordinates to fit align to native T1 space
For midthickness surfaces , add MidThickness metadata
Coordinate update based on :
https : / / github . com / Washington - University / workbench / blob / 1b79e56 / src / Algori... | img = nb . load ( in_file )
transform = load_transform ( transform_file )
pointset = img . get_arrays_from_intent ( 'NIFTI_INTENT_POINTSET' ) [ 0 ]
coords = pointset . data . T
c_ras_keys = ( 'VolGeomC_R' , 'VolGeomC_A' , 'VolGeomC_S' )
ras = np . array ( [ [ float ( pointset . metadata [ key ] ) ] for key in c_ras_key... |
def maximum_vline_bundle ( self , x0 , y0 , y1 ) :
"""Compute a maximum set of vertical lines in the unit cells ` ` ( x0 , y ) ` `
for : math : ` y0 \ leq y \ leq y1 ` .
INPUTS :
y0 , x0 , x1 : int
OUTPUT :
list of lists of qubits""" | y_range = range ( y1 , y0 - 1 , - 1 ) if y0 < y1 else range ( y1 , y0 + 1 )
vlines = [ [ ( x0 , y , 1 , k ) for y in y_range ] for k in range ( self . L ) ]
return list ( filter ( self . _contains_line , vlines ) ) |
def calculate_check_interval ( self , max_interval , ewma_factor , max_days = None , max_updates = None , ewma = 0 , ewma_ts = None , add_partial = None ) :
'''Calculate interval for checks as average
time ( ewma ) between updates for specified period .''' | if not add_partial :
posts_base = self . posts . only ( 'date_modified' ) . order_by ( 'date_modified' )
if ewma_ts :
posts_base = posts_base . filter ( date_modified__gt = ewma_ts )
posts = posts_base
if max_days :
posts = posts . filter ( date_modified__gt = timezone . now ( ) - timede... |
def sendFax_multi ( self , CorpNum , SenderNum , Receiver , FilePath , ReserveDT = None , UserID = None , SenderName = None , adsYN = False , title = None , RequestNum = None ) :
"""팩스 전송
args
CorpNum : 팝빌회원 사업자번호
SenderNum : 발신자 번호 ( 동보전송용 )
Receiver : 수신자 번호 ( ... | if SenderNum == None or SenderNum == "" :
raise PopbillException ( - 99999999 , "발신자 번호가 입력되지 않았습니다." )
if Receiver == None :
raise PopbillException ( - 99999999 , "수신자 정보가 입력되지 않았습니다." )
if not ( type ( Receiver ) is str or type ( Receiver ) is FaxReceiver or type ( Receiver ) is list ) :
raise PopbillExce... |
def run ( self , ** kwargs ) :
"""Does the magic !""" | logger . info ( 'UpdateLocationsIfNecessaryTask was called' )
# read last ip count
try :
with open ( app_settings . IP_ASSEMBLER_IP_CHANGED_FILE , 'r' ) as f :
content_list = f . readlines ( )
if len ( content_list ) == 0 :
ip_count_old = - 1
else :
ip_count_old = int... |
def _diffSchema ( diskSchema , memorySchema ) :
"""Format a schema mismatch for human consumption .
@ param diskSchema : The on - disk schema .
@ param memorySchema : The in - memory schema .
@ rtype : L { bytes }
@ return : A description of the schema differences .""" | diskSchema = set ( diskSchema )
memorySchema = set ( memorySchema )
diskOnly = diskSchema - memorySchema
memoryOnly = memorySchema - diskSchema
diff = [ ]
if diskOnly :
diff . append ( 'Only on disk:' )
diff . extend ( map ( repr , diskOnly ) )
if memoryOnly :
diff . append ( 'Only in memory:' )
diff . ... |
def infer_reference_name ( reference_name_or_path ) :
"""Given a string containing a reference name ( such as a path to
that reference ' s FASTA file ) , return its canonical name
as used by Ensembl .""" | # identify all cases where reference name or path matches candidate aliases
reference_file_name = os . path . basename ( reference_name_or_path )
matches = { 'file_name' : list ( ) , 'full_path' : list ( ) }
for assembly_name in reference_alias_dict . keys ( ) :
candidate_list = [ assembly_name ] + reference_alias_... |
def adjoint ( self ) :
"""Adjoint of the linear operator .
Note that this implementation uses an approximation that is only
valid for small displacements .""" | # TODO allow users to select what method to use here .
div_op = Divergence ( domain = self . displacement . space , method = 'forward' , pad_mode = 'symmetric' )
jacobian_det = self . domain . element ( np . exp ( - div_op ( self . displacement ) ) )
return jacobian_det * self . inverse |
def char ( self , c : str ) -> None :
"""Parse the specified character .
Args :
c : One - character string .
Raises :
EndOfInput : If past the end of ` self . input ` .
UnexpectedInput : If the next character is different from ` c ` .""" | if self . peek ( ) == c :
self . offset += 1
else :
raise UnexpectedInput ( self , f"char '{c}'" ) |
def update_resources_from_resfile ( self , srcpath , types = None , names = None , languages = None ) :
"""Update or add resources from dll / exe file srcpath .
types = a list of resource types to update ( None = all )
names = a list of resource names to update ( None = all )
languages = a list of resource la... | UpdateResourcesFromResFile ( self . filename , srcpath , types , names , languages ) |
def resync ( self ) :
"""make sure we can ping the head and assigned node .
Possibly after an env . exit ( )""" | success = 0
for head in [ True , False ] :
for _ in range ( 30 ) :
try :
self . status ( head )
success += 1
break
except Exception as e :
self . _log_error ( e )
time . sleep ( 10 )
if success != 2 :
raise EnvException ( "Failed to con... |
def link ( self , mu , dist ) :
"""glm link function
this is useful for going from mu to the linear prediction
Parameters
mu : array - like of legth n
dist : Distribution instance
Returns
lp : np . array of length n""" | return np . log ( mu ) - np . log ( dist . levels - mu ) |
def getattrdeep ( obj , attr , * default ) :
'Return dotted attr ( like " a . b . c " ) from obj , or default if any of the components are missing .' | attrs = attr . split ( '.' )
if default :
getattr_default = lambda o , a , d = default [ 0 ] : getattr ( o , a , d )
else :
getattr_default = lambda o , a : getattr ( o , a )
for a in attrs [ : - 1 ] :
obj = getattr_default ( obj , a )
return getattr_default ( obj , attrs [ - 1 ] ) |
def alphanum_key ( string ) :
"""Return a comparable tuple with extracted number segments .
Adapted from : http : / / stackoverflow . com / a / 2669120/176978""" | convert = lambda text : int ( text ) if text . isdigit ( ) else text
return [ convert ( segment ) for segment in re . split ( '([0-9]+)' , string ) ] |
def get_generic_subseq_within_2_5D ( protein , prop_name , within , filter_resnums = None ) :
"""Get a subsequence from REPSEQ based on a feature stored in REPSEQ and within the set distance in REPSTRUCT . REPCHAIN .
If there are multiple sites within the feature , they are first searched separately for residues ... | from ssbio . biopython . Bio . Struct . Geometry import center_of_mass
sites = list ( set ( protein . representative_sequence . letter_annotations [ prop_name ] ) )
sites . remove ( False )
if len ( sites ) > 0 :
log . debug ( '{} unique {} sites to find subsequence within {} angstroms of' . format ( len ( sites ) ... |
def simple_separated_format ( separator ) :
"""Construct a simple TableFormat with columns separated by a separator .
> > > tsv = simple _ separated _ format ( " \\ t " ) ; tabulate ( [ [ " foo " , 1 ] , [ " spam " , 23 ] ] , tablefmt = tsv ) = = ' foo \\ t 1 \\ nspam \\ t23'
True""" | return TableFormat ( None , None , None , None , headerrow = DataRow ( '' , separator , '' ) , datarow = DataRow ( '' , separator , '' ) , padding = 0 , with_header_hide = None ) |
def detect_worksheets ( archive ) :
"""Return a list of worksheets""" | # content types has a list of paths but no titles
# workbook has a list of titles and relIds but no paths
# workbook _ rels has a list of relIds and paths but no titles
# rels = { ' id ' : { ' title ' : ' ' , ' path ' : ' ' } }
content_types = read_content_types ( archive )
valid_sheets = dict ( ( path , ct ) for ct , ... |
def reload ( self ) :
"""Reloads modules from the current plugin _ dirs .
This method will search the plugin _ dirs attribute finding new plugin modules ,
updating plugin modules that have changed , and unloading plugin modules that
no longer exist .""" | logger . debug ( "Reloading Plugins..." )
deleted_modules = set ( self . loaded_modules . keys ( ) )
for plugin_file in self . _get_plugin_files ( self . plugin_dirs ) :
if plugin_file not in self . loaded_modules :
logger . debug ( "New Plugin Module found. Loading: %s" , plugin_file )
self . _load... |
def decrby ( self , key , decrement ) :
"""Decrement the integer value of a key by the given number .
: raises TypeError : if decrement is not int""" | if not isinstance ( decrement , int ) :
raise TypeError ( "decrement must be of type int" )
return self . execute ( b'DECRBY' , key , decrement ) |
def _update_file ( self , seek_to_end = True ) :
"""Open the file for tailing""" | try :
self . close ( )
self . _file = self . open ( )
except IOError :
pass
else :
if not self . _file :
return
self . active = True
try :
st = os . stat ( self . _filename )
except EnvironmentError , err :
if err . errno == errno . ENOENT :
self . _log_in... |
def get_recent_trades ( self , pair = "SWTH_NEO" ) :
"""Function to fetch a list of the 20 most recently filled trades for the parameters requested .
Execution of this function is as follows : :
get _ recent _ trades ( pair = " SWTH _ NEO " )
The expected return result for this function is as follows : :
' ... | api_params = { "pair" : pair }
return self . request . get ( path = '/trades/recent' , params = api_params ) |
async def queue_declare ( self ) :
"""Override this method to change how a queue is declared""" | await self . channel . queue_declare ( self . queue , durable = self . durable , exclusive = self . exclusive , no_wait = self . no_wait ) |
def blit ( self , surface , pos = ( 0 , 0 ) ) :
"""Blits a surface on this surface at pos
: param surface : Surface to blit
: param pos : Top left point to start blitting
: type surface : Surface
: type pos : tuple""" | for x in range ( surface . width ) :
for y in range ( surface . height ) :
px = x + pos [ 0 ]
py = y + pos [ 1 ]
if 0 < px < self . width and 0 < py < self . height :
self . matrix [ px ] [ py ] = surface . matrix [ x ] [ y ] |
def get_alter_table_sql ( self , diff ) :
"""Get the ALTER TABLE SQL statement
: param diff : The table diff
: type diff : eloquent . dbal . table _ diff . TableDiff
: rtype : list""" | column_sql = [ ]
query_parts = [ ]
if diff . new_name is not False :
query_parts . append ( 'RENAME TO %s' % diff . new_name )
# Added columns ?
# Removed columns ?
for column_diff in diff . changed_columns . values ( ) :
column = column_diff . column
column_dict = column . to_dict ( )
# Don ' t propaga... |
def add_all ( self , items ) :
"""Adds all of the items in the specified collection to the end of this list . The order of new elements is
determined by the specified collection ' s iterator .
: param items : ( Collection ) , the specified collection which includes the elements to be added to list .
: return ... | check_not_none ( items , "Value can't be None" )
data_items = [ ]
for item in items :
check_not_none ( item , "Value can't be None" )
data_items . append ( self . _to_data ( item ) )
return self . _encode_invoke ( list_add_all_codec , value_list = data_items ) |
def restore ( self , viewWidget ) :
"""Applies the profile to the inputed view widget .
: param viewWidget | < XViewWidget >""" | if self . _xmlElement is None :
return False
# disable all the information
viewWidget . blockSignals ( True )
viewWidget . setUpdatesEnabled ( False )
viewWidget . setCursor ( Qt . WaitCursor )
viewWidget . reset ( force = True )
# make sure all the cleanup happens ( short of GUI updates )
QApplication . sendPosted... |
def get_services ( self , poc = "lab" ) :
"""Return all Services
: param poc : Point of capture ( lab / field )
: type poc : string
: returns : Mapping of category - > list of services
: rtype : dict""" | bsc = api . get_tool ( "bika_setup_catalog" )
query = { "portal_type" : "AnalysisService" , "getPointOfCapture" : poc , "is_active" : True , "sort_on" : "sortable_title" , }
services = bsc ( query )
categories = self . get_service_categories ( restricted = False )
analyses = { key : [ ] for key in map ( lambda c : c . ... |
def assign_document_controls_default_trigger ( plpy , td ) :
"""Trigger to fill in document _ controls when legacy publishes .
A compatibilty trigger to fill in ` ` uuid ` ` and ` ` licenseid ` ` columns
of the ` ` document _ controls ` ` table that are not
populated when inserting publications from legacy . ... | modified_state = "OK"
uuid = td [ 'new' ] [ 'uuid' ]
# Only do the procedure if this is a legacy publication .
if uuid is None :
modified_state = "MODIFY"
plan = plpy . prepare ( """\
INSERT INTO document_controls (uuid, licenseid) VALUES (DEFAULT, $1)
RETURNING uuid""" , ( 'integer' , ) )
uuid_ = plpy . ex... |
def state_cpfs ( self ) -> List [ CPF ] :
'''Returns list of state - fluent CPFs .''' | _ , cpfs = self . cpfs
state_cpfs = [ ]
for cpf in cpfs :
name = utils . rename_next_state_fluent ( cpf . name )
if name in self . state_fluents :
state_cpfs . append ( cpf )
state_cpfs = sorted ( state_cpfs , key = lambda cpf : cpf . name )
return state_cpfs |
def count_features_type ( features ) :
"""Counts three different types of features ( float , integer , binary ) .
: param features : pandas . DataFrame
A dataset in a panda ' s data frame
: returns a tuple ( binary , integer , float )""" | counter = { k . name : v for k , v in features . columns . to_series ( ) . groupby ( features . dtypes ) }
binary = 0
if ( 'int64' in counter ) :
binary = len ( set ( features . loc [ : , ( features <= 1 ) . all ( axis = 0 ) ] . columns . values ) & set ( features . loc [ : , ( features >= 0 ) . all ( axis = 0 ) ] ... |
def get_featured_entries ( number = 5 , template = 'zinnia/tags/entries_featured.html' ) :
"""Return the featured entries .""" | return { 'template' : template , 'entries' : Entry . published . filter ( featured = True ) [ : number ] } |
def authenticate_with_password ( self , username , password , security_question_id = None , security_question_answer = None ) :
"""Performs Username / Password Authentication
: param string username : your SoftLayer username
: param string password : your SoftLayer password
: param int security _ question _ i... | self . auth = None
res = self . call ( 'User_Customer' , 'getPortalLoginToken' , username , password , security_question_id , security_question_answer )
self . auth = slauth . TokenAuthentication ( res [ 'userId' ] , res [ 'hash' ] )
return res [ 'userId' ] , res [ 'hash' ] |
def unroll ( self , length , inputs , begin_state = None , layout = 'NTC' , merge_outputs = None , valid_length = None ) :
"""Unrolls an RNN cell across time steps .
Parameters
length : int
Number of steps to unroll .
inputs : Symbol , list of Symbol , or None
If ` inputs ` is a single Symbol ( usually th... | # Dropout on inputs and outputs can be performed on the whole sequence
# only when state dropout is not present .
if self . drop_states :
return super ( VariationalDropoutCell , self ) . unroll ( length , inputs , begin_state , layout , merge_outputs , valid_length = valid_length )
self . reset ( )
inputs , axis , ... |
def block ( self , other_user_id ) :
"""Block the given user .
: param str other _ user _ id : the ID of the user to block
: return : the block created
: rtype : : class : ` ~ groupy . api . blocks . Block `""" | params = { 'user' : self . user_id , 'otherUser' : other_user_id }
response = self . session . post ( self . url , params = params )
block = response . data [ 'block' ]
return Block ( self , ** block ) |
def _load ( self , scale = 0.001 ) :
"""Load the OLCI relative spectral responses""" | ncf = Dataset ( self . path , 'r' )
bandnum = OLCI_BAND_NAMES . index ( self . bandname )
# cam = 0
# view = 0
# resp = ncf . variables [
# ' spectral _ response _ function ' ] [ bandnum , cam , view , : ]
# wvl = ncf . variables [
# ' spectral _ response _ function _ wavelength ' ] [ bandnum , cam , view , : ] * scale... |
def cprint_map ( text , cmap , ** kwargs ) :
"""Print colorize text .
cmap is a dict mapping keys to color options .
kwargs are passed to print function
Example :
cprint _ map ( " Hello world " , { " Hello " : " red " } )""" | try :
print ( colored_map ( text , cmap ) , ** kwargs )
except TypeError : # flush is not supported by py2.7
kwargs . pop ( "flush" , None )
print ( colored_map ( text , cmap ) , ** kwargs ) |
def get_equivalent_distance_inslab ( mag , repi , hslab ) :
""": param float mag :
Magnitude
: param repi :
A : class : ` numpy . ndarray ` instance containing repi values
: param float hslab :
Depth of the slab""" | area = 10 ** ( - 3.225 + 0.89 * mag )
radius = ( area / scipy . constants . pi ) ** 0.5
rjb = np . max ( [ repi - radius , np . zeros_like ( repi ) ] , axis = 0 )
rrup = ( rjb ** 2 + hslab ** 2 ) ** 0.5
return rjb , rrup |
def to_tuples ( self , data ) :
'''path _ data : string , from an svg path tag ' s ' d ' attribute , eg :
' M 46,74 L 35,12 l 53 , - 13 z '
returns the same data collected in a list of tuples , eg :
[ ( ' M ' , 46 , 74 ) , ( ' L ' , 35 , 12 ) , ( ' l ' , 53 , - 13 ) , ( ' z ' ) ] ,
The input data may have f... | self . data = data
self . pos = 0
parsed = [ ]
command = [ ]
while self . pos < len ( self . data ) :
indicator = self . data [ self . pos ]
if indicator == ' ' :
self . pos += 1
elif indicator == ',' :
if len ( command ) >= 2 :
self . pos += 1
else :
msg = 'u... |
def can_take ( attrs_to_freeze = ( ) , defaults = None , source_attr = 'source' , instance_property_name = 'snapshot' , inner_class_name = 'Snapshot' ) :
"""Decorator to make a class allow their instances to generate
snapshot of themselves .
Decorates the class by allowing it to have :
* A custom class to ser... | def wrapper ( klass ) :
Snapshot = namedtuple ( inner_class_name , tuple ( attrs_to_freeze ) + ( source_attr , ) )
doc = """
From the current instance collects the following attributes:
%s
Additionally, using the attribute '%s', collects a reference
to the... |
def get_irregular_subnets ( cc , target_multicolor , exclude , verbose = False , verbose_destination = None ) :
"""For a supplied connected component ( which is assumed to be a deepcopy from an original breakpoint graph )
we filter out all edges , that are of no interest for the scaffolding purposes with current ... | to_remove = [ ]
if verbose :
print ( ">Getting irregular subnets" , file = verbose_destination )
print ( "Graph contains" , len ( list ( cc . edges ( ) ) ) , "edges" , file = verbose_destination )
print ( "Removing uninteresting irregular edges" , file = verbose_destination )
# we work with a supplied conne... |
def _calc_vcf_stats ( in_file ) :
"""Calculate statistics on VCF for filtering , saving to a file for quick re - runs .""" | out_file = "%s-stats.yaml" % utils . splitext_plus ( in_file ) [ 0 ]
if not utils . file_exists ( out_file ) :
stats = { "avg_depth" : _average_called_depth ( in_file ) }
with open ( out_file , "w" ) as out_handle :
yaml . safe_dump ( stats , out_handle , default_flow_style = False , allow_unicode = Fal... |
def _sort ( self ) :
"""Sort versions by their version number""" | self . versions = OrderedDict ( sorted ( self . versions . items ( ) , key = lambda v : v [ 0 ] ) ) |
def server_extensions_handshake ( requested , supported ) : # type : ( List [ str ] , List [ Extension ] ) - > Optional [ bytes ]
"""Agree on the extensions to use returning an appropriate header value .
This returns None if there are no agreed extensions""" | accepts = { }
for offer in requested :
name = offer . split ( ";" , 1 ) [ 0 ] . strip ( )
for extension in supported :
if extension . name == name :
accept = extension . accept ( offer )
if accept is True :
accepts [ extension . name ] = True
elif acce... |
def extract_tar ( url , target_dir , additional_compression = "" , remove_common_prefix = False , overwrite = False ) :
"""extract a targz and install to the target directory""" | try :
if not os . path . exists ( target_dir ) :
os . makedirs ( target_dir )
tf = tarfile . TarFile . open ( fileobj = download_to_bytesio ( url ) )
if not os . path . exists ( target_dir ) :
os . makedirs ( target_dir )
common_prefix = os . path . commonprefix ( tf . getnames ( ) )
... |
def revealjs ( basedir = None , title = None , subtitle = None , description = None , github_user = None , github_repo = None ) :
'''Set up or update a reveals . js presentation with slides written in markdown .
Several reveal . js plugins will be set up , too .
More info :
Demo : https : / / theno . github .... | basedir = basedir or query_input ( 'Base dir of the presentation?' , default = '~/repos/my_presi' )
revealjs_repo_name = 'reveal.js'
revealjs_dir = flo ( '{basedir}/{revealjs_repo_name}' )
_lazy_dict [ 'presi_title' ] = title
_lazy_dict [ 'presi_subtitle' ] = subtitle
_lazy_dict [ 'presi_description' ] = description
_l... |
def serialize ( self , private = False ) :
"""Go from a
cryptography . hazmat . primitives . asymmetric . ec . EllipticCurvePrivateKey
or EllipticCurvePublicKey instance to a JWK representation .
: param private : Whether we should include the private attributes or not .
: return : A JWK as a dictionary""" | if self . priv_key :
self . _serialize ( self . priv_key )
else :
self . _serialize ( self . pub_key )
res = self . common ( )
res . update ( { "crv" : self . crv , "x" : self . x , "y" : self . y } )
if private and self . d :
res [ "d" ] = self . d
return res |
def size_of_varint ( value ) :
"""Number of bytes needed to encode an integer in variable - length format .""" | value = ( value << 1 ) ^ ( value >> 63 )
if value <= 0x7f :
return 1
if value <= 0x3fff :
return 2
if value <= 0x1fffff :
return 3
if value <= 0xfffffff :
return 4
if value <= 0x7ffffffff :
return 5
if value <= 0x3ffffffffff :
return 6
if value <= 0x1ffffffffffff :
return 7
if value <= 0xfff... |
def custom_auth ( principal , credentials , realm , scheme , ** parameters ) :
"""Generate a basic auth token for a given user and password .
: param principal : specifies who is being authenticated
: param credentials : authenticates the principal
: param realm : specifies the authentication provider
: par... | from neobolt . security import AuthToken
return AuthToken ( scheme , principal , credentials , realm , ** parameters ) |
def get_delivery_notes_per_page ( self , per_page = 1000 , page = 1 , params = None ) :
"""Get delivery notes per page
: param per _ page : How many objects per page . Default : 1000
: param page : Which page . Default : 1
: param params : Search parameters . Default : { }
: return : list""" | return self . _get_resource_per_page ( resource = DELIVERY_NOTES , per_page = per_page , page = page , params = params ) |
def request ( self , hash_ , quickkey , doc_type , page = None , output = None , size_id = None , metadata = None , request_conversion_only = None ) :
"""Query conversion server
hash _ : 4 characters of file hash
quickkey : File quickkey
doc _ type : " i " for image , " d " for documents
page : The page to ... | if len ( hash_ ) > 4 :
hash_ = hash_ [ : 4 ]
query = QueryParams ( { 'quickkey' : quickkey , 'doc_type' : doc_type , 'page' : page , 'output' : output , 'size_id' : size_id , 'metadata' : metadata , 'request_conversion_only' : request_conversion_only } )
url = API_ENDPOINT + '?' + hash_ + '&' + urlencode ( query )
... |
def make_event_filter ( self , filter_key , filter_value ) :
"""Create a new event filter .""" | event_filter = EventFilter ( self . event_name , self . event , { filter_key : filter_value } , from_block = self . from_block , to_block = self . to_block )
event_filter . set_poll_interval ( 0.5 )
return event_filter |
def get_model_field_label_and_value ( instance , field_name ) -> ( str , str ) :
"""Returns model field label and value .
: param instance : Model instance
: param field _ name : Model attribute name
: return : ( label , value ) tuple""" | label = field_name
value = str ( getattr ( instance , field_name ) )
for f in instance . _meta . fields :
if f . attname == field_name :
label = f . verbose_name
if hasattr ( f , 'choices' ) and len ( f . choices ) > 0 :
value = choices_label ( f . choices , value )
break
return ... |
def energy ( data ) :
"""Computes signal energy of data""" | data = np . mean ( data , axis = 1 )
return np . sum ( data ** 2 ) / np . float64 ( len ( data ) ) |
def do_resolve ( cls , executor , extra_args , ivyxml , jvm_options , workdir_report_paths_by_conf , confs , ivy_resolution_cache_dir , ivy_cache_classpath_filename , resolve_hash_name , workunit_factory , workunit_name ) :
"""Execute Ivy with the given ivy . xml and copies all relevant files into the workdir .
T... | ivy = Bootstrapper . default_ivy ( bootstrap_workunit_factory = workunit_factory )
with safe_concurrent_creation ( ivy_cache_classpath_filename ) as raw_target_classpath_file_tmp :
extra_args = extra_args or [ ]
args = [ '-cachepath' , raw_target_classpath_file_tmp ] + extra_args
with cls . _ivy_lock :
... |
def _BuildFindSpecsFromArtifact ( self , definition , environment_variables ) :
"""Builds find specifications from an artifact definition .
Args :
definition ( artifacts . ArtifactDefinition ) : artifact definition .
environment _ variables ( list [ EnvironmentVariableArtifact ] ) :
environment variables . ... | find_specs = [ ]
for source in definition . sources :
if source . type_indicator == artifact_types . TYPE_INDICATOR_FILE :
for path_entry in set ( source . paths ) :
specifications = self . _BuildFindSpecsFromFileSourcePath ( path_entry , source . separator , environment_variables , self . _know... |
def __body_format ( self , body ) :
"""format body into different type
: param body :
: return :""" | ctype , pdict = parse_header ( self . content_type )
if ctype == 'application/json' :
self . form = json . loads ( body . decode ( ) )
elif ctype == 'application/x-www-form-urlencoded' :
for key , value in parse_qs ( body ) . items ( ) :
self . form [ key . decode ( ) ] = [ one_value . decode ( ) for on... |
def route ( self , url , host = None ) :
"""This is a decorator""" | def fn ( handler_cls ) :
handlers = self . _get_handlers_on_host ( host )
handlers . insert ( 0 , ( url , handler_cls ) )
return handler_cls
return fn |
def insert ( self , storagemodel ) -> StorageTableModel :
"""insert model into storage""" | modeldefinition = self . getmodeldefinition ( storagemodel , True )
try :
modeldefinition [ 'tableservice' ] . insert_or_replace_entity ( modeldefinition [ 'tablename' ] , storagemodel . entity ( ) )
storagemodel . _exists = True
except AzureMissingResourceHttpError as e :
storagemodel . _exists = False
... |
def random_string ( length = 6 ) :
"""Create a random 6 character string .
note : in case you use this function in a test during test together with
an awsclient then this function is altered so you get reproducible results
that will work with your recorded placebo json files ( see helpers _ aws . py ) .""" | return '' . join ( [ random . choice ( string . ascii_lowercase ) for i in range ( length ) ] ) |
def p_parameter_1 ( p ) :
"""parameter _ 1 : dataType parameterName
| dataType parameterName array""" | args = { }
if len ( p ) == 4 :
args [ 'is_array' ] = True
args [ 'array_size' ] = p [ 3 ]
p [ 0 ] = CIMParameter ( p [ 2 ] , p [ 1 ] , ** args ) |
def _make_exception ( self , response ) :
"""In case of exception , construct the exception
object that holds all important values returned by
the response .
: return : The exception instance
: rtype : PocketException""" | headers = response . headers
limit_headers = [ ]
if 'X-Limit-User-Limit' in headers :
limit_headers = [ headers [ 'X-Limit-User-Limit' ] , headers [ 'X-Limit-User-Remaining' ] , headers [ 'X-Limit-User-Reset' ] , headers [ 'X-Limit-Key-Limit' ] , headers [ 'X-Limit-Key-Remaining' ] , headers [ 'X-Limit-Key-Reset' ]... |
def set_room_name ( self , name ) :
"""Return True if room name successfully changed .""" | try :
self . client . api . set_room_name ( self . room_id , name )
self . name = name
return True
except MatrixRequestError :
return False |
def _list_samples ( self , predicate = None ) :
"""List all samples that meet the predicate or all if predicate is not specified .
Args :
predicate : Match samples against this predicate ( or all if not specified )
Returns :
List of the md5s for the matching samples""" | cursor = self . database [ self . sample_collection ] . find ( predicate , { '_id' : 0 , 'md5' : 1 } )
return [ item [ 'md5' ] for item in cursor ] |
def check_bottleneck ( text ) :
"""Avoid mixing metaphors about bottles and their necks .
source : Sir Ernest Gowers
source _ url : http : / / bit . ly / 1CQPH61""" | err = "mixed_metaphors.misc.bottleneck"
msg = u"Mixed metaphor — bottles with big necks are easy to pass through."
list = [ "biggest bottleneck" , "big bottleneck" , "large bottleneck" , "largest bottleneck" , "world-wide bottleneck" , "huge bottleneck" , "massive bottleneck" , ]
return existence_check ( text , list , ... |
def _list_templates ( settings ) :
"""List templates from settings .""" | for idx , option in enumerate ( settings . config . get ( "project_templates" ) , start = 1 ) :
puts ( " {0!s:5} {1!s:36}" . format ( colored . yellow ( "[{0}]" . format ( idx ) ) , colored . cyan ( option . get ( "name" ) ) ) )
if option . get ( "url" ) :
puts ( " {0}\n" . format ( option . get (... |
def write ( self , use_template = False , out_file_or_path = None , encoding = DEFAULT_ENCODING ) :
"""Validates instance properties , updates an XML tree with them , and writes the content to a file .
: param use _ template : if True , updates a new template XML tree ; otherwise the original XML tree
: param o... | if not out_file_or_path :
out_file_or_path = self . out_file_or_path
if not out_file_or_path : # FileNotFoundError doesn ' t exist in Python 2
raise IOError ( 'Output file path has not been provided' )
write_element ( self . update ( use_template ) , out_file_or_path , encoding ) |
def object_build ( self , node , obj ) :
"""recursive method which create a partial ast from real objects
( only function , class , and method are handled )""" | if obj in self . _done :
return self . _done [ obj ]
self . _done [ obj ] = node
for name in dir ( obj ) :
try :
member = getattr ( obj , name )
except AttributeError : # damned ExtensionClass . Base , I know you ' re there !
attach_dummy_node ( node , name )
continue
if inspect ... |
def exc_from_rc ( rc , msg = None , obj = None ) :
""". . warning : : INTERNAL
For those rare cases when an exception needs to be thrown from
Python using a libcouchbase error code .
: param rc : The error code
: param msg : Message ( description )
: param obj : Context
: return : a raisable exception""... | newcls = CouchbaseError . rc_to_exctype ( rc )
return newcls ( params = { 'rc' : rc , 'objextra' : obj , 'message' : msg } ) |
def get_default_config ( self ) :
"""Returns the default collector settings""" | config = super ( SidekiqCollector , self ) . get_default_config ( )
config . update ( { 'path' : 'sidekiq' , 'host' : 'localhost' , 'ports' : '6379' , 'password' : None , 'databases' : 16 , 'sentinel_ports' : None , 'sentinel_name' : None , 'cluster_prefix' : None } )
return config |
def model_reaction_limits ( model ) :
"""Yield model reaction limits as YAML dicts .""" | for reaction in sorted ( model . reactions , key = lambda r : r . id ) :
equation = reaction . properties . get ( 'equation' )
if equation is None :
continue
# Determine the default flux limits . If the value is already at the
# default it does not need to be included in the output .
lower_d... |
def wp_is_loiter ( self , i ) :
'''return true if waypoint is a loiter waypoint''' | loiter_cmds = [ mavutil . mavlink . MAV_CMD_NAV_LOITER_UNLIM , mavutil . mavlink . MAV_CMD_NAV_LOITER_TURNS , mavutil . mavlink . MAV_CMD_NAV_LOITER_TIME , mavutil . mavlink . MAV_CMD_NAV_LOITER_TO_ALT ]
if ( self . wpoints [ i ] . command in loiter_cmds ) :
return True
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.