signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def build_view_from_tag ( self , tag ) :
"""Build a view of group of Symbols based on their tag .
Parameters
tag : str
Use ' % ' to enable SQL ' s " LIKE " functionality .
Note
This function is written without SQLAlchemy ,
so it only tested on Postgres .""" | syms = self . search_tag ( tag )
names = [ sym . name for sym in syms ]
subs = [ "SELECT indx, '{}' AS symbol, final FROM {}" . format ( s , s ) for s in names ]
qry = " UNION ALL " . join ( subs )
qry = "CREATE VIEW {} AS {};" . format ( tag , qry )
self . ses . execute ( "DROP VIEW IF EXISTS {};" . format ( tag ) )
s... |
def endswith ( self , suffix ) :
"""Construct a Filter matching values ending with ` ` suffix ` ` .
Parameters
suffix : str
String suffix against which to compare values produced by ` ` self ` ` .
Returns
matches : Filter
Filter returning True for all sid / date pairs for which ` ` self ` `
produces a... | return ArrayPredicate ( term = self , op = LabelArray . endswith , opargs = ( suffix , ) , ) |
def _setup_cached ( self , filters = ( ) ) :
"""Find all currently - cached interpreters .""" | for interpreter_dir in os . listdir ( self . _cache_dir ) :
pi = self . _interpreter_from_relpath ( interpreter_dir , filters = filters )
if pi :
logger . debug ( 'Detected interpreter {}: {}' . format ( pi . binary , str ( pi . identity ) ) )
yield pi |
def update_account_password_policy ( MinimumPasswordLength = None , RequireSymbols = None , RequireNumbers = None , RequireUppercaseCharacters = None , RequireLowercaseCharacters = None , AllowUsersToChangePassword = None , MaxPasswordAge = None , PasswordReusePrevention = None , HardExpiry = None ) :
"""Updates th... | pass |
def jsonRpcLogout ( self , remote , session ) :
"""Logout of CCU""" | logout = False
try :
params = { "_session_id_" : session }
response = self . _rpcfunctions . jsonRpcPost ( self . remotes [ remote ] [ 'ip' ] , self . remotes [ remote ] . get ( 'jsonport' , DEFAULT_JSONPORT ) , "Session.logout" , params )
if response [ 'error' ] is None and response [ 'result' ] :
... |
def generate ( ast_tree : ast . Tree , model_name : str ) :
""": param ast _ tree : AST to generate from
: param model _ name : class to generate
: return : sympy source code for model""" | component_ref = ast . ComponentRef . from_string ( model_name )
ast_tree_new = copy . deepcopy ( ast_tree )
ast_walker = TreeWalker ( )
flat_tree = flatten ( ast_tree_new , component_ref )
sympy_gen = SympyGenerator ( )
ast_walker . walk ( sympy_gen , flat_tree )
return sympy_gen . src [ flat_tree ] |
def read ( self , size = - 1 ) :
"""Read up to * size * bytes .
This function reads from the buffer multiple times until the requested
number of bytes can be satisfied . This means that this function may
block to wait for more data , even if some data is available . The only
time a short read is returned , ... | self . _check_readable ( )
chunks = [ ]
bytes_read = 0
bytes_left = size
while True :
chunk = self . _buffer . get_chunk ( bytes_left )
if not chunk :
break
chunks . append ( chunk )
bytes_read += len ( chunk )
if bytes_read == size or not chunk :
break
if bytes_left > 0 :
... |
def find_ctrlpts ( obj , u , v = None , ** kwargs ) :
"""Finds the control points involved in the evaluation of the curve / surface point defined by the input parameter ( s ) .
: param obj : curve or surface
: type obj : abstract . Curve or abstract . Surface
: param u : parameter ( for curve ) , parameter on... | if isinstance ( obj , abstract . Curve ) :
return ops . find_ctrlpts_curve ( u , obj , ** kwargs )
elif isinstance ( obj , abstract . Surface ) :
if v is None :
raise GeomdlException ( "Parameter value for the v-direction must be set for operating on surfaces" )
return ops . find_ctrlpts_surface ( u... |
def handle ( self , * args , ** options ) :
"""Parses / validates , and breaks off into actions .""" | if len ( args ) < 1 :
raise CommandError ( "Please specify an action. See --help." )
action = args [ 0 ]
email = None
if action not in self . valid_actions :
message = "Invalid action: %s" % action
raise CommandError ( message )
if action in [ 'verify' , 'delete' ] :
if len ( args ) < 2 :
messag... |
def to_doc ( self , xmllist , decorates ) :
"""Converts the specified xml list to a list of docstring elements .""" | result = [ ]
for xitem in xmllist :
if xitem . tag != "group" : # The docstring allows a single string to point to multiple
# names in a comma - separated list in the names attribute .
if "name" in list ( xitem . keys ( ) ) :
names = re . split ( "[\s,]+" , xitem . get ( "name" ) )
... |
def _datetime_to_epoch ( self , dt ) :
"""Convert the datetime to unix epoch ( properly ) .""" | if dt :
td = ( dt - datetime . datetime . fromtimestamp ( 0 , tzutc ( ) ) )
# don ' t use total _ seconds ( ) , that ' s only available in 2.7
total_secs = int ( ( td . microseconds + ( td . seconds + td . days * 24 * 3600 ) * 10 ** 6 ) / 10 ** 6 )
return total_secs
else :
return 0 |
def delete_field ( field_uri ) :
"""Helper function to request deletion of a field . This is necessary when you want to overwrite values instead of
appending .
< t : DeleteItemField >
< t : FieldURI FieldURI = " calendar : Resources " / >
< / t : DeleteItemField >""" | root = T . DeleteItemField ( T . FieldURI ( FieldURI = field_uri ) )
return root |
def loads ( self , json_data , many = None , partial = None , unknown = None , ** kwargs ) :
"""Same as : meth : ` load ` , except it takes a JSON string as input .
: param str json _ data : A JSON string of the data to deserialize .
: param bool many : Whether to deserialize ` obj ` as a collection . If ` None... | data = self . opts . render_module . loads ( json_data , ** kwargs )
return self . load ( data , many = many , partial = partial , unknown = unknown ) |
def editfile ( fpath ) :
"""Runs gvim . Can also accept a module / class / function""" | if not isinstance ( fpath , six . string_types ) :
from six import types
print ( 'Rectify to module fpath = %r' % ( fpath , ) )
if isinstance ( fpath , types . ModuleType ) :
fpath = fpath . __file__
else :
fpath = sys . modules [ fpath . __module__ ] . __file__
fpath_py = fpath . re... |
def format_options ( self , ctx , formatter ) :
"""Writes all the options into the formatter if they exist .""" | opts = [ ]
for param in self . get_params ( ctx ) :
rv = param . get_help_record ( ctx )
if rv is not None :
opts . append ( rv )
if opts :
with formatter . section ( 'Options' ) :
formatter . write_dl ( opts ) |
def get ( method , hmc , uri , uri_parms , logon_required ) :
"""Operation : List Virtual Switches of a CPC ( empty result if not in
DPM mode ) .""" | cpc_oid = uri_parms [ 0 ]
query_str = uri_parms [ 1 ]
try :
cpc = hmc . cpcs . lookup_by_oid ( cpc_oid )
except KeyError :
raise InvalidResourceError ( method , uri )
result_vswitches = [ ]
if cpc . dpm_enabled :
filter_args = parse_query_parms ( method , uri , query_str )
for vswitch in cpc . virtual_s... |
def _map_arguments ( self , args ) :
"""Map from the top - level arguments to the arguments provided to
the indiviudal links""" | data = args . get ( 'data' )
comp = args . get ( 'comp' )
library = args . get ( 'library' )
dry_run = args . get ( 'dry_run' , False )
self . _set_link ( 'srcmaps-catalog' , SrcmapsCatalog_SG , comp = comp , data = data , library = library , nsrc = args . get ( 'nsrc' , 500 ) , dry_run = dry_run )
self . _set_link ( '... |
def _walk_depth ( self , fs , # type : FS
path , # type : Text
namespaces = None , # type : Optional [ Collection [ Text ] ]
) : # type : ( . . . ) - > Iterator [ Tuple [ Text , Optional [ Info ] ] ]
"""Walk files using a * depth first * search .""" | # No recursion !
_combine = combine
_scan = self . _scan
_calculate_depth = self . _calculate_depth
_check_open_dir = self . _check_open_dir
_check_scan_dir = self . _check_scan_dir
_check_file = self . check_file
depth = _calculate_depth ( path )
stack = [ ( path , _scan ( fs , path , namespaces = namespaces ) , None ... |
def root_sync ( args , l , config ) :
"""Sync with the remote . For more options , use library sync""" | from requests . exceptions import ConnectionError
all_remote_names = [ r . short_name for r in l . remotes ]
if args . all :
remotes = all_remote_names
else :
remotes = args . refs
prt ( "Sync with {} remotes or bundles " . format ( len ( remotes ) ) )
if not remotes :
return
for ref in remotes :
l . co... |
def divisions ( self ) :
"""Recursively get all the text divisions directly part of this element . If an element contains parts or text without tag . Those will be returned in order and wrapped with a TextDivision .""" | from . placeholder_division import PlaceholderDivision
placeholder = None
for item in self . __parts_and_divisions :
if item . tag == 'part' :
if not placeholder :
placeholder = PlaceholderDivision ( )
placeholder . parts . append ( item )
else :
if placeholder :
... |
def params_size ( m : Union [ nn . Module , Learner ] , size : tuple = ( 3 , 64 , 64 ) ) -> Tuple [ Sizes , Tensor , Hooks ] :
"Pass a dummy input through the model to get the various sizes . Returns ( res , x , hooks ) if ` full `" | if isinstance ( m , Learner ) :
if m . data . is_empty :
raise Exception ( "This is an empty `Learner` and `Learner.summary` requires some data to pass through the model." )
ds_type = DatasetType . Train if m . data . train_dl else ( DatasetType . Valid if m . data . valid_dl else DatasetType . Test )
... |
def parse ( self , val ) :
"""Parses a ` ` bool ` ` from the string , matching ' true ' or ' false ' ignoring case .""" | s = str ( val ) . lower ( )
if s == "true" :
return True
elif s == "false" :
return False
else :
raise ValueError ( "cannot interpret '{}' as boolean" . format ( val ) ) |
def run_command ( cls , cmd , # type : List [ str ]
show_stdout = True , # type : bool
cwd = None , # type : Optional [ str ]
on_returncode = 'raise' , # type : str
extra_ok_returncodes = None , # type : Optional [ Iterable [ int ] ]
command_desc = None , # type : Optional [ str ]
extra_environ = None , # type : Option... | cmd = [ cls . name ] + cmd
try :
return call_subprocess ( cmd , show_stdout , cwd , on_returncode = on_returncode , extra_ok_returncodes = extra_ok_returncodes , command_desc = command_desc , extra_environ = extra_environ , unset_environ = cls . unset_environ , spinner = spinner )
except OSError as e : # errno . EN... |
def _set_priority_tag_enable ( self , v , load = False ) :
"""Setter method for priority _ tag _ enable , mapped from YANG variable / interface / port _ channel / priority _ tag _ enable ( empty )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ priority _ tag _ enable i... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGBool , is_leaf = True , yang_name = "priority-tag-enable" , rest_name = "priority-tag" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , extensions = { u'tailf... |
def who ( self , * args ) :
"""Display a table of connected users and clients""" | if len ( self . _users ) == 0 :
self . log ( 'No users connected' )
if len ( self . _clients ) == 0 :
self . log ( 'No clients connected' )
return
Row = namedtuple ( "Row" , [ 'User' , 'Client' , 'IP' ] )
rows = [ ]
for user in self . _users . values ( ) :
for key , client in self . _clients... |
def iter ( self , string ) :
"""Generator performs Aho - Corasick search string algorithm , yielding
tuples containing two values :
- position in string
- outputs associated with matched strings""" | state = self . root
for index , c in enumerate ( string ) :
while c not in state . children :
state = state . fail
state = state . children . get ( c , self . root )
tmp = state
output = [ ]
while tmp is not nil :
if tmp . output is not nil :
output . append ( tmp . outpu... |
def can_review_whether_correct ( self ) :
"""stub""" | ao = self . my_osid_object . get_assessment_offered ( )
attempt_complete = self . my_osid_object . has_ended ( )
if ao . can_review_whether_correct_during_attempt ( ) and not attempt_complete :
return True
if ao . can_review_whether_correct_after_attempt and attempt_complete :
return True
return False |
def load_bcah98_mass_radius ( tablelines , metallicity = 0 , heliumfrac = 0.275 , age_gyr = 5. , age_tol = 0.05 ) :
"""Load mass and radius from the main data table for the famous models of
Baraffe + ( 1998A & A . . . 337 . . 403B ) .
tablelines
An iterable yielding lines from the table data file .
I ' ve n... | mdata , rdata = [ ] , [ ]
for line in tablelines :
a = line . strip ( ) . split ( )
thismetallicity = float ( a [ 0 ] )
if thismetallicity != metallicity :
continue
thisheliumfrac = float ( a [ 1 ] )
if thisheliumfrac != heliumfrac :
continue
thisage = float ( a [ 4 ] )
if ab... |
def delete_guest_property ( self , name ) :
"""Deletes an entry from the machine ' s guest property store .
in name of type str
The name of the property to delete .
raises : class : ` VBoxErrorInvalidVmState `
Machine session is not open .""" | if not isinstance ( name , basestring ) :
raise TypeError ( "name can only be an instance of type basestring" )
self . _call ( "deleteGuestProperty" , in_p = [ name ] ) |
def number_to_day ( self , day_number ) :
"""Returns localized day name by its CRON number
Args :
day _ number : Number of a day
Returns :
Day corresponding to day _ number
Raises :
IndexError : When day _ number is not found""" | return [ calendar . day_name [ 6 ] , calendar . day_name [ 0 ] , calendar . day_name [ 1 ] , calendar . day_name [ 2 ] , calendar . day_name [ 3 ] , calendar . day_name [ 4 ] , calendar . day_name [ 5 ] ] [ day_number ] |
def _integrateLinearOrbit ( vxvv , pot , t , method , dt ) :
"""NAME :
integrateLinearOrbit
PURPOSE :
integrate a one - dimensional orbit
INPUT :
vxvv - initial condition [ x , vx ]
pot - linearPotential or list of linearPotentials
t - list of times at which to output ( 0 has to be in this ! )
metho... | # First check that the potential has C
if '_c' in method :
if not ext_loaded or not _check_c ( pot ) :
if ( 'leapfrog' in method or 'symplec' in method ) :
method = 'leapfrog'
else :
method = 'odeint'
if not ext_loaded : # pragma : no cover
warnings . warn... |
def get_state_map ( meta_graph , state_ops , unsupported_state_ops , get_tensor_by_name ) :
"""Returns a map from tensor names to tensors that hold the state .""" | state_map = { }
for node in meta_graph . graph_def . node :
if node . op in state_ops :
tensor_name = node . name + ":0"
tensor = get_tensor_by_name ( tensor_name )
num_outputs = len ( tensor . op . outputs )
if num_outputs != 1 :
raise ValueError ( "Stateful op %s has %d... |
def crop_to_seg_extents ( img , seg , padding ) :
"""Crop the image ( usually MRI ) to fit within the bounding box of a segmentation ( or set of seg )""" | beg_coords , end_coords = crop_coords ( seg , padding )
img = crop_3dimage ( img , beg_coords , end_coords )
seg = crop_3dimage ( seg , beg_coords , end_coords )
return img , seg |
def _save_assignment ( self , node , name = None ) :
"""save assignement situation since node . parent is not available yet""" | if self . _global_names and node . name in self . _global_names [ - 1 ] :
node . root ( ) . set_local ( node . name , node )
else :
node . parent . set_local ( node . name , node ) |
def setupEnvironment ( self , cmd ) :
"""Turn all build properties into environment variables""" | shell . ShellCommand . setupEnvironment ( self , cmd )
env = { }
for k , v in self . build . getProperties ( ) . properties . items ( ) :
env [ str ( k ) ] = str ( v [ 0 ] )
if cmd . args [ 'env' ] is None :
cmd . args [ 'env' ] = { }
cmd . args [ 'env' ] . update ( env ) |
def _get_accept_languages_in_order ( self ) :
"""Reads an Accept HTTP header and returns an array of Media Type string in descending weighted order
: return : List of URIs of accept profiles in descending request order
: rtype : list""" | try : # split the header into individual URIs , with weights still attached
profiles = self . request . headers [ 'Accept-Language' ] . split ( ',' )
# remove \ s
profiles = [ x . replace ( ' ' , '' ) . strip ( ) for x in profiles ]
# split off any weights and sort by them with default weight = 1
pr... |
def fit ( self , data ) :
"""Fit a cover on the data . This method constructs centers and radii in each dimension given the ` perc _ overlap ` and ` n _ cube ` .
Parameters
data : array - like
Data to apply the cover to . Warning : First column must be an index column .
Returns
centers : list of arrays
... | # TODO : support indexing into any columns
di = np . array ( range ( 1 , data . shape [ 1 ] ) )
indexless_data = data [ : , di ]
n_dims = indexless_data . shape [ 1 ]
# support different values along each dimension
# # - - is a list , needs to be array
# # - - is a singleton , needs repeating
if isinstance ( self . n_c... |
def drawdown_details ( drawdown , index_type = pd . DatetimeIndex ) :
"""Returns a data frame with start , end , days ( duration ) and
drawdown for each drawdown in a drawdown series .
. . note : :
days are actual calendar days , not trading days
Args :
* drawdown ( pandas . Series ) : A drawdown Series
... | is_zero = drawdown == 0
# find start dates ( first day where dd is non - zero after a zero )
start = ~ is_zero & is_zero . shift ( 1 )
start = list ( start [ start == True ] . index )
# NOQA
# find end dates ( first day where dd is 0 after non - zero )
end = is_zero & ( ~ is_zero ) . shift ( 1 )
end = list ( end [ end ... |
def _GetExtractionErrorsAsWarnings ( self ) :
"""Retrieves errors from from the store , and converts them to warnings .
This method is for backwards compatibility with pre - 20190309 storage format
stores which used ExtractionError attribute containers .
Yields :
ExtractionWarning : extraction warnings .""" | for extraction_error in self . _GetAttributeContainers ( self . _CONTAINER_TYPE_EXTRACTION_ERROR ) :
error_attributes = extraction_error . CopyToDict ( )
warning = warnings . ExtractionWarning ( )
warning . CopyFromDict ( error_attributes )
yield warning |
def clear_cache ( cls ) :
"""Call this before closing tk root""" | # Prevent tkinter errors on python 2 ? ?
for key in cls . _cached :
cls . _cached [ key ] = None
cls . _cached = { } |
def main ( ) :
"""Transfer gTEX data from dbGaP ( NCBI ) to S3""" | # Define Parser object and add to toil
parser = build_parser ( )
Job . Runner . addToilOptions ( parser )
args = parser . parse_args ( )
# Store inputs from argparse
inputs = { 'sra' : args . sra , 'dbgap_key' : args . dbgap_key , 'ssec' : args . ssec , 's3_dir' : args . s3_dir , 'single_end' : args . single_end , 'sud... |
def _get_policies ( self , resource_properties ) :
"""Returns a list of policies from the resource properties . This method knows how to interpret and handle
polymorphic nature of the policies property .
Policies can be one of the following :
* Managed policy name : string
* List of managed policy names : l... | policies = None
if self . _contains_policies ( resource_properties ) :
policies = resource_properties [ self . POLICIES_PROPERTY_NAME ]
if not policies : # Policies is None or empty
return [ ]
if not isinstance ( policies , list ) : # Just a single entry . Make it into a list of convenience
policies = [ pol... |
def parser ( cls , buf , offset ) :
"""Returns an object which is generated from a buffer including the
expression of the wire protocol of the flow match .""" | match = OFPMatch ( )
type_ , length = struct . unpack_from ( '!HH' , buf , offset )
match . type = type_
match . length = length
# ofp _ match adjustment
offset += 4
length -= 4
fields = [ ]
while length > 0 :
n , value , mask , field_len = ofproto . oxm_parse ( buf , offset )
k , uv = ofproto . oxm_to_user ( n... |
def _getItems ( container , containerKeys = None , sort = False , reverse = False , selector = lambda item : True ) :
"""Generator that yields filtered and / or sorted items from the specified
" container " .
: param container : The container has to be a dictionary of dictionaries that
contain some kind of it... | if containerKeys is None :
containerKeys = [ _ for _ in viewkeys ( container ) ]
else :
containerKeys = aux . toList ( containerKeys )
if sort :
sortIdentifier = list ( )
for containerKey in containerKeys :
for identifier in [ _ for _ in viewkeys ( container [ containerKey ] ) ] :
it... |
def json ( self , url , params ) :
"""Low level method to execute JSON queries .
It basically performs a request and raises an
: class : ` odoorpc . error . RPCError ` exception if the response contains
an error .
You have to know the names of each parameter required by the function
called , and set them ... | data = self . _connector . proxy_json ( url , params )
if data . get ( 'error' ) :
raise error . RPCError ( data [ 'error' ] [ 'data' ] [ 'message' ] , data [ 'error' ] )
return data |
def embowel ( rest ) :
"Embowel some ( one | thing ) !" | if rest :
stabee = rest
karma . Karma . store . change ( stabee , 1 )
else :
stabee = "someone nearby"
return ( "/me (wearing a bright pink cape and yellow tights) swoops in " "through an open window, snatches %s, races out of the basement, " "takes them to the hospital with entrails on ice, and mercifully ... |
def pip_compile ( * packages : str ) :
"""Run pip - compile to pin down packages , also resolve their transitive dependencies .""" | result = None
packages = "\n" . join ( packages )
with tempfile . TemporaryDirectory ( ) as tmp_dirname , cwd ( tmp_dirname ) :
with open ( "requirements.in" , "w" ) as requirements_file :
requirements_file . write ( packages )
runner = CliRunner ( )
try :
result = runner . invoke ( cli , [ ... |
def plot_distributions ( self , parameters = None , truth = None , extents = None , display = False , filename = None , chains = None , col_wrap = 4 , figsize = None , blind = None ) : # pragma : no cover
"""Plots the 1D parameter distributions for verification purposes .
This plot is more for a sanity or consist... | chains , parameters , truth , extents , blind = self . _sanitise ( chains , parameters , truth , extents , blind = blind )
n = len ( parameters )
num_cols = min ( n , col_wrap )
num_rows = int ( np . ceil ( 1.0 * n / col_wrap ) )
if figsize is None :
figsize = 1.0
if isinstance ( figsize , float ) :
figsize_flo... |
def post ( self ) :
"""Create a new role""" | self . reqparse . add_argument ( 'name' , type = str , required = True )
self . reqparse . add_argument ( 'color' , type = str , required = True )
args = self . reqparse . parse_args ( )
role = Role ( )
role . name = args [ 'name' ]
role . color = args [ 'color' ]
db . session . add ( role )
db . session . commit ( )
a... |
def _execute_sub_tasks ( task_id , params , sig_content , verbosity , runmode , sigmode , monitor_interval , resource_monitor_interval , master_runtime ) :
'''If this is a master task , execute as individual tasks''' | m = ProcessMonitor ( task_id , monitor_interval = monitor_interval , resource_monitor_interval = resource_monitor_interval , max_walltime = params . sos_dict [ '_runtime' ] . get ( 'max_walltime' , None ) , max_mem = params . sos_dict [ '_runtime' ] . get ( 'max_mem' , None ) , max_procs = params . sos_dict [ '_runtime... |
def save ( self , p_todolist ) :
"""Saves a tuple with archive , todolist and command with its arguments
into the backup file with unix timestamp as the key . Tuple is then
indexed in backup file with combination of hash calculated from
p _ todolist and unix timestamp . Backup file is closed afterwards .""" | self . _trim ( )
current_hash = hash_todolist ( p_todolist )
list_todo = ( self . todolist . print_todos ( ) + '\n' ) . splitlines ( True )
try :
list_archive = ( self . archive . print_todos ( ) + '\n' ) . splitlines ( True )
except AttributeError :
list_archive = [ ]
self . backup_dict [ self . timestamp ] = ... |
def resizeEvent ( self , event ) :
"""Reimplement Qt method""" | if not self . isMaximized ( ) and not self . fullscreen_flag :
self . window_size = self . size ( )
QMainWindow . resizeEvent ( self , event )
# To be used by the tour to be able to resize
self . sig_resized . emit ( event ) |
def analyze_sentiment ( self , document , encoding_type = None , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) :
"""Analyzes the sentiment of the provided text .
Example :
> > > from google . cloud import language _ v1
... | # Wrap the transport method to add retry and timeout logic .
if "analyze_sentiment" not in self . _inner_api_calls :
self . _inner_api_calls [ "analyze_sentiment" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . analyze_sentiment , default_retry = self . _method_configs [ "AnalyzeSentime... |
def is_address_writeable ( self , address ) :
"""Determines if an address belongs to a commited and writeable page .
The page may or may not have additional permissions .
@ note : Returns always C { False } for kernel mode addresses .
@ type address : int
@ param address : Memory address to query .
@ rtyp... | try :
mbi = self . mquery ( address )
except WindowsError :
e = sys . exc_info ( ) [ 1 ]
if e . winerror == win32 . ERROR_INVALID_PARAMETER :
return False
raise
return mbi . is_writeable ( ) |
def find_include_path ( ) :
"""Find MXNet included header files .
Returns
incl _ path : string
Path to the header files .""" | incl_from_env = os . environ . get ( 'MXNET_INCLUDE_PATH' )
if incl_from_env :
if os . path . isdir ( incl_from_env ) :
if not os . path . isabs ( incl_from_env ) :
logging . warning ( "MXNET_INCLUDE_PATH should be an absolute path, instead of: %s" , incl_from_env )
else :
re... |
def _compute_response ( response_key , server_challenge , client_challenge ) :
"""ComputeResponse ( ) has been refactored slightly to reduce its complexity and improve
readability , the ' if ' clause which switches between LMv2 and NTLMv2 computation has been
removed . Users should not call this method directly... | hmac_context = hmac . HMAC ( response_key , hashes . MD5 ( ) , backend = default_backend ( ) )
hmac_context . update ( server_challenge )
hmac_context . update ( client_challenge )
return hmac_context . finalize ( ) |
def check_missing ( self , param , action ) :
"""Make sure the given parameter is missing in the job . ini file""" | assert action in ( 'debug' , 'info' , 'warn' , 'error' ) , action
if self . inputs . get ( param ) :
msg = '%s_file in %s is ignored in %s' % ( param , self . inputs [ 'job_ini' ] , self . calculation_mode )
if action == 'error' :
raise InvalidFile ( msg )
else :
getattr ( logging , action )... |
def enabled_logical_ids ( self ) :
""": return : only the logical id ' s for the deployment preferences in this collection which are enabled""" | return [ logical_id for logical_id , preference in self . _resource_preferences . items ( ) if preference . enabled ] |
def get ( self , ** params ) :
"""Performs get request to the biomart service .
Args :
* * params ( dict of str : any ) : Arbitrary keyword arguments , which
are added as parameters to the get request to biomart .
Returns :
requests . models . Response : Response from biomart for the request .""" | if self . _use_cache :
r = requests . get ( self . url , params = params )
else :
with requests_cache . disabled ( ) :
r = requests . get ( self . url , params = params )
r . raise_for_status ( )
return r |
def url_content ( url , cache_duration = None , from_cache_on_error = False ) :
"""Get content for the given URL
: param str url : The URL to get content from
: param int cache _ duration : Optionally cache the content for the given duration to avoid downloading too often .
: param bool from _ cache _ on _ er... | cache_file = _url_content_cache_file ( url )
if cache_duration :
if os . path . exists ( cache_file ) :
stat = os . stat ( cache_file )
cached_time = stat . st_mtime
if time . time ( ) - cached_time < cache_duration :
with open ( cache_file ) as fp :
return fp . r... |
def compile_rename_column ( self , blueprint , command , connection ) :
"""Compile a rename column command .
: param blueprint : The blueprint
: type blueprint : Blueprint
: param command : The command
: type command : Fluent
: param connection : The connection
: type connection : eloquent . connections... | # The code is a little complex . It will propably change
# if we support complete diffs in dbal
sql = [ ]
schema = connection . get_schema_manager ( )
table = self . get_table_prefix ( ) + blueprint . get_table ( )
column = connection . get_column ( table , command . from_ )
columns = schema . list_table_columns ( tabl... |
def _low_level_exec_command ( self , conn , cmd , tmp , sudoable = False , executable = None ) :
'''execute a command string over SSH , return the output''' | if executable is None :
executable = '/bin/sh'
sudo_user = self . sudo_user
rc , stdin , stdout , stderr = conn . exec_command ( cmd , tmp , sudo_user , sudoable = sudoable , executable = executable )
if type ( stdout ) not in [ str , unicode ] :
out = '' . join ( stdout . readlines ( ) )
else :
out = stdou... |
def get_revision ( self , id , revision_number , project = None , expand = None ) :
"""GetRevision .
[ Preview API ] Returns a fully hydrated work item for the requested revision
: param int id :
: param int revision _ number :
: param str project : Project ID or project name
: param str expand :
: rtyp... | route_values = { }
if project is not None :
route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' )
if id is not None :
route_values [ 'id' ] = self . _serialize . url ( 'id' , id , 'int' )
if revision_number is not None :
route_values [ 'revisionNumber' ] = self . _serialize . ... |
def delete ( cls , repo , * refs , ** kwargs ) :
"""Delete the given remote references
: note :
kwargs are given for comparability with the base class method as we
should not narrow the signature .""" | repo . git . branch ( "-d" , "-r" , * refs )
# the official deletion method will ignore remote symbolic refs - these
# are generally ignored in the refs / folder . We don ' t though
# and delete remainders manually
for ref in refs :
try :
os . remove ( osp . join ( repo . common_dir , ref . path ) )
exc... |
def humidity_unit ( self ) :
"""Get unit of humidity .""" | if CONST . UNIT_PERCENT in self . _get_status ( CONST . HUMI_STATUS_KEY ) :
return CONST . UNIT_PERCENT
return None |
def asDict ( self ) :
'''asDict - Returns a copy of the current state as a dictionary . This copy will not be updated automatically .
@ return < dict > - Dictionary with all fields in BackgroundTaskInfo . FIELDS''' | ret = { }
for field in BackgroundTaskInfo . FIELDS :
ret [ field ] = getattr ( self , field )
return ret |
def register ( self , collector ) :
"""Add a collector to the registry .""" | with self . _lock :
names = self . _get_names ( collector )
duplicates = set ( self . _names_to_collectors ) . intersection ( names )
if duplicates :
raise ValueError ( 'Duplicated timeseries in CollectorRegistry: {0}' . format ( duplicates ) )
for name in names :
self . _names_to_collec... |
def _rgb_to_hex ( rgbs ) :
"""Convert rgb to hex triplet""" | rgbs , n_dim = _check_color_dim ( rgbs )
return np . array ( [ '#%02x%02x%02x' % tuple ( ( 255 * rgb [ : 3 ] ) . astype ( np . uint8 ) ) for rgb in rgbs ] , '|U7' ) |
def sendBox ( self , box ) :
"""Add the route and send the box .""" | if self . remoteRouteName is _unspecified :
raise RouteNotConnected ( )
if self . remoteRouteName is not None :
box [ _ROUTE ] = self . remoteRouteName . encode ( 'ascii' )
self . router . _sender . sendBox ( box ) |
def drop ( self , async_ = False , if_exists = False , ** kw ) :
"""Drop this table .
: param async _ : run asynchronously if True
: return : None""" | async_ = kw . get ( 'async' , async_ )
return self . parent . delete ( self , async_ = async_ , if_exists = if_exists ) |
def find_your_legislator ( request ) :
'''Context :
- request
- lat
- long
- located
- legislators
Templates :
- billy / web / public / find _ your _ legislator _ table . html''' | # check if lat / lon are set
# if leg _ search is set , they most likely don ' t have ECMAScript enabled .
# XXX : fallback behavior here for alpha .
get = request . GET
context = { }
template = 'find_your_legislator'
context [ 'request' ] = ""
if "q" in get :
context [ 'request' ] = get [ 'q' ]
if "lat" in get and... |
def status ( self ) :
'''show status''' | for m in sorted ( self . mlog . messages . keys ( ) ) :
print ( str ( self . mlog . messages [ m ] ) ) |
def is_host_target_supported ( host_target , msvc_version ) :
"""Return True if the given ( host , target ) tuple is supported given the
msvc version .
Parameters
host _ target : tuple
tuple of ( canonalized ) host - target , e . g . ( " x86 " , " amd64 " ) for cross
compilation from 32 bits windows to 64... | # We assume that any Visual Studio version supports x86 as a target
if host_target [ 1 ] != "x86" :
maj , min = msvc_version_to_maj_min ( msvc_version )
if maj < 8 :
return False
return True |
def open_preview ( self ) :
'''Try to open a preview of the generated document .
Currently only supported on Windows .''' | self . log . info ( 'Opening preview...' )
if self . opt . pdf :
ext = 'pdf'
else :
ext = 'dvi'
filename = '%s.%s' % ( self . project_name , ext )
if sys . platform == 'win32' :
try :
os . startfile ( filename )
except OSError :
self . log . error ( 'Preview-Error: Extension .%s is not l... |
def get ( self , name , return_json = False , quiet = False ) :
'''get is a list for a single instance . It is assumed to be running ,
and we need to look up the PID , etc .''' | from spython . utils import check_install
check_install ( )
# Ensure compatible for singularity prior to 3.0 , and after 3.0
subgroup = "instance.list"
if 'version 3' in self . version ( ) :
subgroup = [ "instance" , "list" ]
cmd = self . _init_command ( subgroup )
cmd . append ( name )
output = run_command ( cmd ,... |
def parse_ACCT ( chunk , encryption_key ) :
"""Parses an account chunk , decrypts and creates an Account object .
May return nil when the chunk does not represent an account .
All secure notes are ACCTs but not all of them strore account
information .""" | # TODO : Make a test case that covers secure note account
io = BytesIO ( chunk . payload )
id = read_item ( io )
name = decode_aes256_plain_auto ( read_item ( io ) , encryption_key )
group = decode_aes256_plain_auto ( read_item ( io ) , encryption_key )
url = decode_hex ( read_item ( io ) )
notes = decode_aes256_plain_... |
def _safe_read ( self , amt ) :
"""Read the number of bytes requested , compensating for partial reads .
Normally , we have a blocking socket , but a read ( ) can be interrupted
by a signal ( resulting in a partial read ) .
Note that we cannot distinguish between EOF and an interrupt when zero
bytes have be... | s = [ ]
while amt > 0 :
chunk = self . fp . read ( min ( amt , MAXAMOUNT ) )
if not chunk :
raise IncompleteRead ( bytes ( b'' ) . join ( s ) , amt )
s . append ( chunk )
amt -= len ( chunk )
return bytes ( b"" ) . join ( s ) |
def nucleotide_counts ( variant_reads ) :
"""Count the number of times { A , C , T , G } occur at each position to the
left and right of the variant .
Parameters
variant _ reads : list of AlleleRead objects
Expected to all contain the same variant allele .
Returns a tuple with the following elements :
-... | variant_seq = get_single_allele_from_reads ( variant_reads )
prefix_suffix_pairs = make_prefix_suffix_pairs ( variant_reads )
n_reads = len ( prefix_suffix_pairs )
max_prefix_length = max ( len ( p ) for ( p , _ ) in prefix_suffix_pairs )
max_suffix_length = max ( len ( s ) for ( _ , s ) in prefix_suffix_pairs )
n_vari... |
def print_seqs ( seqs , id2name , name ) :
"""print fasta of introns and ORFs
# seqs [ id ] = [ gene , model , [ [ i - gene _ pos , i - model _ pos , i - length , iseq , [ orfs ] , [ introns ] , orfs ? , introns ? , [ orf annotations ] ] , . . . ] ]""" | orfs = open ( '%s.orfs.faa' % ( name . rsplit ( '.' , 1 ) [ 0 ] ) , 'w' )
introns = open ( '%s.introns.fa' % ( name . rsplit ( '.' , 1 ) [ 0 ] ) , 'w' )
insertions = open ( '%s.insertions.fa' % ( name . rsplit ( '.' , 1 ) [ 0 ] ) , 'w' )
for seq in seqs :
for i , ins in enumerate ( seqs [ seq ] [ 2 ] , 1 ) :
... |
def random_discrete_dp ( num_states , num_actions , beta = None , k = None , scale = 1 , sparse = False , sa_pair = False , random_state = None ) :
"""Generate a DiscreteDP randomly . The reward values are drawn from the
normal distribution with mean 0 and standard deviation ` scale ` .
Parameters
num _ state... | if sparse :
sa_pair = True
# Number of state - action pairs
L = num_states * num_actions
random_state = check_random_state ( random_state )
R = scale * random_state . randn ( L )
Q = _random_stochastic_matrix ( L , num_states , k = k , sparse = sparse , format = 'csr' , random_state = random_state )
if beta is None... |
def crypto_secretstream_xchacha20poly1305_rekey ( state ) :
"""Explicitly change the encryption key in the stream .
Normally the stream is re - keyed as needed or an explicit ` ` tag ` ` of
: data : ` . crypto _ secretstream _ xchacha20poly1305 _ TAG _ REKEY ` is added to a
message to ensure forward secrecy ,... | ensure ( isinstance ( state , crypto_secretstream_xchacha20poly1305_state ) , 'State must be a crypto_secretstream_xchacha20poly1305_state object' , raising = exc . TypeError , )
lib . crypto_secretstream_xchacha20poly1305_rekey ( state . statebuf ) |
def BasenamePath ( self , path ) :
"""Determines the basename of the path .
Args :
path ( str ) : path .
Returns :
str : basename of the path .""" | if path . endswith ( self . PATH_SEPARATOR ) :
path = path [ : - 1 ]
_ , _ , basename = path . rpartition ( self . PATH_SEPARATOR )
return basename |
def createMultipleL246aLocationColumn ( network , numberOfColumns , L2Params , L4Params , L6aParams , inverseReadoutResolution = None , baselineCellsPerAxis = 6 ) :
"""Create a network consisting of multiple columns . Each column contains one L2,
one L4 and one L6a layers identical in structure to the network cre... | L2Params = copy . deepcopy ( L2Params )
L4Params = copy . deepcopy ( L4Params )
L6aParams = copy . deepcopy ( L6aParams )
# Update L2 numOtherCorticalColumns parameter
L2Params [ "numOtherCorticalColumns" ] = numberOfColumns - 1
for i in xrange ( numberOfColumns ) : # Make sure random seed is different for each column
... |
def generatePlugin ( sourcePath , buildPath = None ) :
"""Generates a particular ui plugin for ths system and imports it .
: param widgetPath | < str >
buildPath | < str > | | None""" | if ( buildPath is None ) :
buildPath = BUILD_PATH
pkg_name = projex . packageFromPath ( sourcePath )
module = os . path . basename ( sourcePath ) . split ( '.' ) [ 0 ]
if module != '__init__' :
pkg_name += '.' + module
try :
__import__ ( pkg_name )
except ImportError , e :
logging . exception ( e )
... |
def set_note_footer ( data , trigger ) :
"""handle the footer of the note""" | footer = ''
if data . get ( 'link' ) :
provided_by = _ ( 'Provided by' )
provided_from = _ ( 'from' )
footer_from = "<br/><br/>{} <em>{}</em> {} <a href='{}'>{}</a>"
footer = footer_from . format ( provided_by , trigger . trigger . description , provided_from , data . get ( 'link' ) , data . get ( 'link... |
def eventFilter ( self , object , event ) :
"""Ignore all events for the text label .
: param object | < QObject >
event | < QEvent >""" | if object == self . _richTextLabel :
if event . type ( ) in ( event . MouseButtonPress , event . MouseMove , event . MouseButtonRelease , event . MouseButtonDblClick ) :
event . ignore ( )
return True
return False |
def clear_zone_conditions ( self ) :
"""stub""" | if ( self . get_zone_conditions_metadata ( ) . is_read_only ( ) or self . get_zone_conditions_metadata ( ) . is_required ( ) ) :
raise NoAccess ( )
self . my_osid_object_form . _my_map [ 'zoneConditions' ] = self . _zone_conditions_metadata [ 'default_object_values' ] [ 0 ] |
def set_parameter ( name , parameter , value , path = None ) :
'''Set the value of a cgroup parameter for a container .
path
path to the container parent directory
default : / var / lib / lxc ( system )
. . versionadded : : 2015.8.0
CLI Example :
. . code - block : : bash
salt ' * ' lxc . set _ parame... | if not exists ( name , path = path ) :
return None
cmd = 'lxc-cgroup'
if path :
cmd += ' -P {0}' . format ( pipes . quote ( path ) )
cmd += ' -n {0} {1} {2}' . format ( name , parameter , value )
ret = __salt__ [ 'cmd.run_all' ] ( cmd , python_shell = False )
if ret [ 'retcode' ] != 0 :
return False
else :
... |
def after_epoch ( self , epoch_data : EpochData , ** _ ) -> None :
"""Save the model if the new value of the monitored variable is better than the best value so far .
: param epoch _ data : epoch data to be processed""" | new_value = self . _get_value ( epoch_data )
if self . _is_value_better ( new_value ) :
self . _best_value = new_value
SaveEvery . save_model ( model = self . _model , name_suffix = self . _OUTPUT_NAME , on_failure = self . _on_save_failure ) |
def delete_puppetclass ( self , synchronous = True , ** kwargs ) :
"""Remove a Puppet class from host group
Here is an example of how to use this method : :
hostgroup . delete _ puppetclass ( data = { ' puppetclass _ id ' : puppet . id } )
Constructs path :
/ api / hostgroups / : hostgroup _ id / puppetclas... | kwargs = kwargs . copy ( )
kwargs . update ( self . _server_config . get_client_kwargs ( ) )
path = "{0}/{1}" . format ( self . path ( 'puppetclass_ids' ) , kwargs [ 'data' ] . pop ( 'puppetclass_id' ) )
return _handle_response ( client . delete ( path , ** kwargs ) , self . _server_config , synchronous ) |
def append_seeding_annotation ( self , annotation : str , values : Set [ str ] ) -> Seeding :
"""Add a seed induction method for single annotation ' s values .
: param annotation : The annotation to filter by
: param values : The values of the annotation to keep""" | return self . seeding . append_annotation ( annotation , values ) |
def image_to_data ( image , lang = None , config = '' , nice = 0 , output_type = Output . STRING ) :
'''Returns string containing box boundaries , confidences ,
and other information . Requires Tesseract 3.05 +''' | if get_tesseract_version ( ) < '3.05' :
raise TSVNotSupported ( )
config = '{} {}' . format ( '-c tessedit_create_tsv=1' , config . strip ( ) ) . strip ( )
args = [ image , 'tsv' , lang , config , nice ]
return { Output . BYTES : lambda : run_and_get_output ( * ( args + [ True ] ) ) , Output . DATAFRAME : lambda : ... |
def list ( self , argv ) :
"""List available indexes if no names provided , otherwise list the
properties of the named indexes .""" | def read ( index ) :
print ( index . name )
for key in sorted ( index . content . keys ( ) ) :
value = index . content [ key ]
print ( " %s: %s" % ( key , value ) )
if len ( argv ) == 0 :
for index in self . service . indexes :
count = index [ 'totalEventCount' ]
print ( "... |
def get_biopython_pepstats ( self , clean_seq = False ) :
"""Run Biopython ' s built in ProteinAnalysis module and store statistics in the ` ` annotations ` ` attribute .""" | if self . seq :
if clean_seq : # TODO : can make this a property of the SeqProp class
seq = self . seq_str . replace ( 'X' , '' ) . replace ( 'U' , '' )
else :
seq = self . seq_str
try :
pepstats = ssbio . protein . sequence . properties . residues . biopython_protein_analysis ( seq ... |
def to_binary_string ( self ) :
"""Pack the feedback to binary form and return it as string .""" | timestamp = datetime_to_timestamp ( self . when )
token = binascii . unhexlify ( self . token )
return struct . pack ( self . FORMAT_PREFIX + '{0}s' . format ( len ( token ) ) , timestamp , len ( token ) , token ) |
def function ( self , rule , args , ** kwargs ) :
"""Callback method for rule tree traversing . Will be called at proper time
from : py : class : ` pynspect . rules . FunctionRule . traverse ` method .
: param pynspect . rules . Rule rule : Reference to rule .
: param args : Optional function arguments .
: ... | return '<div class="pynspect-rule-function"><h3 class="pynspect-rule-function-name">{}</h3><ul class="pynspect-rule-function-arguments>{}</ul></div>' . format ( rule . function , '' . join ( [ '<li class="pynspect-rule-function-argument">{}</li>' . format ( v ) for v in args ] ) ) |
def js_html ( self ) :
"""Render HTML tags for Javascript assets .
Returns :
string : HTML for Javascript assets from every registered config .""" | output = io . StringIO ( )
for item in self . js ( ) :
output . write ( self . render_asset_html ( item , settings . CODEMIRROR_JS_ASSET_TAG ) )
content = output . getvalue ( )
output . close ( )
return content |
def remove_child_banks ( self , bank_id ) :
"""Removes all children from a bank .
arg : bank _ id ( osid . id . Id ) : the ` ` Id ` ` of a bank
raise : NotFound - ` ` bank _ id ` ` is not in hierarchy
raise : NullArgument - ` ` bank _ id ` ` is ` ` null ` `
raise : OperationFailed - unable to complete reque... | # Implemented from template for
# osid . resource . BinHierarchyDesignSession . remove _ child _ bin _ template
if self . _catalog_session is not None :
return self . _catalog_session . remove_child_catalogs ( catalog_id = bank_id )
return self . _hierarchy_session . remove_children ( id_ = bank_id ) |
def remove_bg ( img , th = ( 240 , 255 ) ) :
"""Removes similar colored background in the given image .
: param img : Input image
: param th : Tuple ( 2)
Background color threshold ( lower - limit , upper - limit )
: return : Background removed image as result""" | if img . size == 0 :
return img
img = gray3 ( img )
# delete rows with complete background color
h , w = img . shape [ : 2 ]
i = 0
while i < h :
mask = np . logical_or ( img [ i , : , : ] < th [ 0 ] , img [ i , : , : ] > th [ 1 ] )
if not mask . any ( ) :
img = np . delete ( img , i , axis = 0 )
... |
def get ( cls , sensor_type ) :
"""Shortcut that acquires the default Sensor of a given type .
Parameters
sensor _ type : int
Type of sensor to get .
Returns
result : Future
A future that resolves to an instance of the Sensor or None
if the sensor is not present or access is not allowed .""" | app = AndroidApplication . instance ( )
f = app . create_future ( )
def on_sensor ( sid , mgr ) :
if sid is None :
f . set_result ( None )
else :
f . set_result ( Sensor ( __id__ = sid , manager = mgr , type = sensor_type ) )
SensorManager . get ( ) . then ( lambda sm : sm . getDefaultSensor ( s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.