signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def prune_indices ( self , transforms = None ) :
"""Return indices of pruned rows and columns as list .
The return value has one of three possible forms :
* a 1 - element list of row indices ( in case of 1D cube )
* 2 - element list of row and col indices ( in case of 2D cube )
* n - element list of tuples ... | if self . ndim >= 3 : # In case of a 3D cube , return list of tuples
# ( of row and col pruned indices ) .
return self . _prune_3d_indices ( transforms )
def prune_non_3d_indices ( transforms ) :
row_margin = self . _pruning_base ( hs_dims = transforms , axis = self . row_direction_axis )
row_indices = self... |
def start_engines ( opts , proc_mgr , proxy = None ) :
'''Fire up the configured engines !''' | utils = salt . loader . utils ( opts , proxy = proxy )
if opts [ '__role' ] == 'master' :
runners = salt . loader . runner ( opts , utils = utils )
else :
runners = [ ]
funcs = salt . loader . minion_mods ( opts , utils = utils , proxy = proxy )
engines = salt . loader . engines ( opts , funcs , runners , utils... |
def get_create_index_sql ( self , index , table ) :
"""Returns the SQL to create an index on a table on this platform .
: param index : The index
: type index : Index
: param table : The table
: type table : Table or str
: rtype : str""" | if isinstance ( table , Table ) :
table = table . get_quoted_name ( self )
name = index . get_quoted_name ( self )
columns = index . get_quoted_columns ( self )
if not columns :
raise DBALException ( 'Incomplete definition. "columns" required.' )
if index . is_primary ( ) :
return self . get_create_primary_... |
def root_indices ( sec_list ) :
"""Returns the index of all sections without a parent .""" | roots = [ ]
for i , section in enumerate ( sec_list ) :
sref = h . SectionRef ( sec = section )
# has _ parent returns a float . . . cast to bool
if sref . has_parent ( ) < 0.9 :
roots . append ( i )
return roots |
def receive_message ( self ) :
"""Receive a message from the file .""" | with self . lock :
assert self . can_receive_messages ( )
message_type = self . _read_message_type ( self . _file )
message = message_type ( self . _file , self )
self . _message_received ( message ) |
def write_files ( self , jdoc , output_dir ) :
'''Writes all jdoc records into files .
One file per schema plus index file .''' | # get all distinct schema names from jdoc :
schemas = [ j for j in jdoc if j . object_type == 'schema' ]
schemas = [ j for j in schemas if len ( [ x for x in jdoc if x . object_type != 'schema' and x . schema_name == j . object_name ] ) > 0 ]
if not os . path . exists ( output_dir ) :
os . makedirs ( output_dir )
t... |
def _fetch_itemslist ( self , current_item ) :
"""Get a all available apis""" | if current_item . is_root :
html = requests . get ( self . base_url ) . text
soup = BeautifulSoup ( html , 'html.parser' )
for item_html in soup . select ( ".row .col-md-6" ) :
try :
label = item_html . select_one ( "h2" ) . text
except Exception :
continue
yi... |
def get_custom_metrics ( ) :
""": return : mxnet metric object""" | _rse = mx . metric . create ( rse )
_rae = mx . metric . create ( rae )
_corr = mx . metric . create ( corr )
return mx . metric . create ( [ _rae , _rse , _corr ] ) |
def set_cache ( self , value ) :
"""Assign the cache in cache .""" | value . update ( self . cache )
return self . cache_backend . set ( self . cache_key , value ) |
def batch_predict ( training_dir , prediction_input_file , output_dir , mode , batch_size = 16 , shard_files = True , output_format = 'csv' , cloud = False ) :
"""Blocking versoin of batch _ predict .
See documentation of batch _ prediction _ async .""" | job = batch_predict_async ( training_dir = training_dir , prediction_input_file = prediction_input_file , output_dir = output_dir , mode = mode , batch_size = batch_size , shard_files = shard_files , output_format = output_format , cloud = cloud )
job . wait ( )
print ( 'Batch predict: ' + str ( job . state ) ) |
def _get_requirements ( fname ) :
"""Create a list of requirements from the output of the pip freeze command
saved in a text file .""" | packages = _read ( fname ) . split ( '\n' )
packages = ( p . strip ( ) for p in packages )
packages = ( p for p in packages if p and not p . startswith ( '#' ) )
return list ( packages ) |
def respond_from_question ( self , question , user_question , importance ) :
"""Copy the answer given in ` question ` to the logged in user ' s
profile .
: param question : A : class : ` ~ . Question ` instance to copy .
: param user _ question : An instance of : class : ` ~ . UserQuestion ` that
correspond... | option_index = user_question . answer_text_to_option [ question . their_answer ] . id
self . respond ( question . id , [ option_index ] , [ option_index ] , importance ) |
def open_array ( store = None , mode = 'a' , shape = None , chunks = True , dtype = None , compressor = 'default' , fill_value = 0 , order = 'C' , synchronizer = None , filters = None , cache_metadata = True , cache_attrs = True , path = None , object_codec = None , chunk_store = None , ** kwargs ) :
"""Open an arr... | # use same mode semantics as h5py
# r : read only , must exist
# r + : read / write , must exist
# w : create , delete if exists
# w - or x : create , fail if exists
# a : read / write if exists , create otherwise ( default )
# handle polymorphic store arg
clobber = mode == 'w'
store = normalize_store_arg ( store , clo... |
def generate_matches ( self , nodes ) :
"""Generator yielding matches for a sequence of nodes .
Args :
nodes : sequence of nodes
Yields :
( count , results ) tuples where :
count : the match comprises nodes [ : count ] ;
results : dict containing named submatches .""" | if self . content is None : # Shortcut for special case ( see _ _ init _ _ . _ _ doc _ _ )
for count in xrange ( self . min , 1 + min ( len ( nodes ) , self . max ) ) :
r = { }
if self . name :
r [ self . name ] = nodes [ : count ]
yield count , r
elif self . name == "bare_name" ... |
def _api ( fn ) :
"""API decorator for common tests ( sessions open , etc . ) and throttle
limitation ( calls per second ) .""" | @ _functools . wraps ( fn )
def _fn ( self , * args , ** kwargs ) :
self . _throttle_wait ( )
if not self . _SID :
raise RuntimeError ( 'Session closed. Invoke connect() before.' )
return fn ( self , * args , ** kwargs )
return _fn |
def bq ( line , cell = None ) :
"""Implements the bq cell magic for ipython notebooks .
The supported syntax is :
% % bq < command > [ < args > ]
< cell >
or :
% bq < command > [ < args > ]
Use % bq - - help for a list of commands , or % bq < command > - - help for help
on a specific command .""" | return google . datalab . utils . commands . handle_magic_line ( line , cell , _bigquery_parser ) |
def inject ( self , function = None , ** names ) :
"""Inject dependencies into ` funtion ` ' s arguments when called .
> > > @ injector . inject
. . . def use _ dependency ( dependency _ name ) :
> > > use _ dependency ( )
The ` Injector ` will look for registered dependencies
matching named arguments and... | def decorator ( function ) :
@ wraps ( function )
def wrapper ( * args , ** kwargs ) :
sig = signature ( function )
params = sig . parameters
bound = sig . bind_partial ( * args , ** kwargs )
bound . apply_defaults ( )
injected_kwargs = { }
for key , value in para... |
def term_symbols ( self ) :
"""All possible Russell - Saunders term symbol of the Element
eg . L = 1 , n _ e = 2 ( s2)
returns
[ [ ' 1D2 ' ] , [ ' 3P0 ' , ' 3P1 ' , ' 3P2 ' ] , [ ' 1S0 ' ] ]""" | L_symbols = 'SPDFGHIKLMNOQRTUVWXYZ'
L , v_e = self . valence
# for one electron in subshell L
ml = list ( range ( - L , L + 1 ) )
ms = [ 1 / 2 , - 1 / 2 ]
# all possible configurations of ml , ms for one e in subshell L
ml_ms = list ( product ( ml , ms ) )
# Number of possible configurations for r electrons in subshell... |
def make_frame ( fig , ax , plot_x : np . ndarray , plot_y : np . ndarray , frame_num : int , bodies : List [ str ] , plot_colors : Dict [ str , str ] , markersize_tbl : Dict [ str , float ] , fname : str ) :
"""Make a series of frames of the planetary orbits that can be assembled into a movie .
q is a Nx3B array... | # Clear the axis
ax . clear ( )
ax . set_title ( f'Inner Planetary Orbits in 2018' )
ax . set_xlabel ( 'x in J2000.0 Frame; Astronomical Units (au)' )
ax . set_ylabel ( 'y in J2000.0 Frame; Astronomical Units (au)' )
# Scale and tick size
a = 2.0
da = 1.0
ticks = np . arange ( - a , a + da , da )
# Set limits and ticks... |
def read_block ( self , size , from_date = None ) :
"""Read items and return them in blocks .
: param from _ date : start date for incremental reading .
: param size : block size .
: return : next block of items when any available .
: raises ValueError : ` metadata _ _ timestamp ` field not found in index
... | search_query = self . _build_search_query ( from_date )
hits_block = [ ]
for hit in helpers . scan ( self . _es_conn , search_query , scroll = '300m' , index = self . _es_index , preserve_order = True ) :
hits_block . append ( hit )
if len ( hits_block ) % size == 0 :
yield hits_block
# Reset hi... |
def toc ( self ) :
"""End collecting for current batch and return results .
Call after computation of current batch .
Returns
res : list of""" | if not self . activated :
return [ ]
for exe in self . exes :
for array in exe . arg_arrays :
array . wait_to_read ( )
for array in exe . aux_arrays :
array . wait_to_read ( )
for exe in self . exes :
for name , array in zip ( exe . _symbol . list_arguments ( ) , exe . arg_arrays ) :
... |
def set_servo_angle ( self , goalangle , goaltime , led ) :
"""Sets the servo angle ( in degrees )
Enable torque using torque _ on function before calling this
Args :
goalangle ( int ) : The desired angle in degrees , range - 150 to 150
goaltime ( int ) : the time taken to move from present
position to go... | if ( self . servomodel == 0x06 ) or ( self . servomodel == 0x04 ) :
goalposition = scale ( goalangle , - 159.9 , 159.6 , 10627 , 22129 )
else :
goalposition = scale ( goalangle , - 150 , 150 , 21 , 1002 )
self . set_servo_position ( goalposition , goaltime , led ) |
def walk_callbacks ( obj , func , log = None ) :
"""Call func ( callback , args ) for all callbacks and keep only those
callbacks for which the function returns True .""" | callbacks = obj . _callbacks
if isinstance ( callbacks , Node ) :
node = callbacks
try :
if not func ( node . data , node . extra ) :
obj . _callbacks = None
except Exception :
if log is None :
log = logging . get_logger ( )
log . exception ( 'uncaught excepti... |
def VersionPath ( ) :
"""Returns a path to version . ini .""" | # Try to get a version . ini . It should be in the resources if the code
# was packed with " pip sdist " . It will be 2 levels up from grr _ response _ core
# if the code was installed via " pip install - e " .
version_ini = ( package . ResourcePath ( "grr-response-core" , "version.ini" ) or package . ResourcePath ( "g... |
def gradient_descent ( self , start_x = None , tolerance = 1.0e-6 ) :
"""Optimise value of x using gradient descent""" | if start_x is None :
start_x = self . _analytical_fitter . fit ( self . _c )
return optimise_gradient_descent ( start_x , self . _a , self . _c , tolerance ) |
def _config_create ( self ) :
"""- - genconf""" | # Create ~ / . config / urlscan / config . json if if doesn ' t exist
if not exists ( self . conf ) :
try : # Python 2/3 compatible recursive directory creation
os . makedirs ( dirname ( expanduser ( self . conf ) ) )
except OSError as err :
if errno . EEXIST != err . errno :
raise
... |
def from_stream ( cls , stream , marker_code , offset ) :
"""Return a generic | _ Marker | instance for the marker at * offset * in
* stream * having * marker _ code * .""" | if JPEG_MARKER_CODE . is_standalone ( marker_code ) :
segment_length = 0
else :
segment_length = stream . read_short ( offset )
return cls ( marker_code , offset , segment_length ) |
def audiosamples ( language , word , key = '' ) :
'''Returns a list of URLs to suitable audiosamples for a given word .''' | from lltk . audiosamples import forvo , google
urls = [ ]
urls += forvo ( language , word , key )
urls += google ( language , word )
return urls |
def makedirs ( * args , ** kwargs ) :
"""Wrapper around os . makedirs that doesn ' t raise an exception if the
directory already exists .""" | try :
os . makedirs ( * args , ** kwargs )
except OSError as ex :
if ex . errno != errno . EEXIST :
raise |
def per_event_source_id ( event_space ) :
""": return :
a seeder function that returns an event ' s source id only if that event ' s
source space equals to ` ` event _ space ` ` .""" | def f ( event ) :
if is_event ( event ) :
v = peel ( event )
if v [ 'source' ] [ 'space' ] == event_space :
return v [ 'source' ] [ 'id' ]
else :
return None
else :
return None
return _wrap_none ( f ) |
def unify ( t1 , t2 ) :
"""Unify the two types t1 and t2.
Makes the types t1 and t2 the same .
Args :
t1 : The first type to be made equivalent
t2 : The second type to be be equivalent
Returns :
None
Raises :
InferenceError : Raised if the types cannot be unified .""" | a = prune ( t1 )
b = prune ( t2 )
if isinstance ( a , TypeVariable ) :
if a != b :
if occurs_in_type ( a , b ) :
raise InferenceError ( "recursive unification" )
a . instance = b
elif isinstance ( b , TypeVariable ) :
unify ( b , a )
elif isinstance ( a , TypeOperator ) and a . name ... |
def _build_arguments ( self ) :
"""build arguments for command .""" | self . _parser . add_argument ( '-a' , '--alias' , required = False , default = 'default' , type = str , help = 'registry alias created in freight-forwarder.yml. Example: tune_dev' ) |
def replace_version ( self , other , logger ) :
"""True if self can safely replace other
based on version numbers only - snapshot and branch tags are ignored""" | if other . library_name != self . library_name :
logger . debug ( 'not replacable: {} != {} ()' . format ( other . library_name , self . library_name , other . filename ) )
return False
elif int ( other . major_version ) != int ( self . major_version ) :
logger . debug ( 'not replacable: {} != {} ({})' . fo... |
def to_strings ( self , resource ) :
"""Dumps the all resources reachable from the given resource to a map of
string representations using the specified content _ type ( defaults
to CSV ) .
: returns : dictionary mapping resource member classes to string
representations""" | collections = self . __collect ( resource )
# Build a map of representations .
rpr_map = OrderedDict ( )
for ( mb_cls , coll ) in iteritems_ ( collections ) :
strm = NativeIO ( 'w' )
dump_resource ( coll , strm , content_type = self . __content_type )
rpr_map [ mb_cls ] = strm . getvalue ( )
return rpr_map |
def parameters_dict ( self ) :
"""Get the tool parameters as a simple dictionary
: return : The tool parameters""" | d = { }
for k , v in self . __dict__ . items ( ) :
if not k . startswith ( "_" ) :
d [ k ] = v
return d |
def set_driver ( self , driver = None ) :
"""Defines the driver that is used to recognize prompts and implement
behavior depending on the remote system .
The driver argument may be an instance of a protocols . drivers . Driver
subclass , a known driver name ( string ) , or None .
If the driver argument is N... | if driver is None :
self . manual_driver = None
elif isinstance ( driver , str ) :
if driver not in driver_map :
raise TypeError ( 'no such driver:' + repr ( driver ) )
self . manual_driver = driver_map [ driver ]
elif isinstance ( driver , Driver ) :
self . manual_driver = driver
else :
rai... |
def _color_im_callback ( self , msg ) :
"""Callback for handling textures ( greyscale images ) .""" | try :
data = self . _bridge . imgmsg_to_cv2 ( msg )
if np . max ( data ) > 255.0 :
data = 255.0 * data / 1200.0
# Experimentally set value for white
data = np . clip ( data , 0. , 255.0 ) . astype ( np . uint8 )
gsimage = GrayscaleImage ( data , frame = self . _frame )
self . _cur_co... |
def from_array ( array ) :
"""Deserialize a new Game from a given dictionary .
: return : new Game instance .
: rtype : Game""" | if array is None or not array :
return None
# end if
assert_type_or_raise ( array , dict , parameter_name = "array" )
from pytgbot . api_types . receivable . media import Animation
from pytgbot . api_types . receivable . media import MessageEntity
from pytgbot . api_types . receivable . media import PhotoSize
data ... |
def gen_checkbox_edit ( sig_dic ) :
'''for checkbox''' | edit_wuneisheshi = '''<label for="{0}"><span>
<a class="glyphicon glyphicon-star" style="color: red;font-size: xx-small;">
</a>{1}</span>
''' . format ( sig_dic [ 'en' ] , sig_dic [ 'zh' ] )
dic_tmp = sig_dic [ 'dic' ]
for key in dic_tmp . keys ( ) :
tmp_str = '''
<input id="{0}" name="{0}" ... |
def find_ip4_by_id ( self , id_ip ) :
"""Get an IP by ID
: param id _ ip : IP identifier . Integer value and greater than zero .
: return : Dictionary with the following structure :
{ ips { id : < id _ ip4 > ,
oct1 : < oct1 > ,
oct2 : < oct2 > ,
oct3 : < oct3 > ,
oct4 : < oct4 > ,
equipamento : [ { ... | if not is_valid_int_param ( id_ip ) :
raise InvalidParameterError ( u'Ip identifier is invalid or was not informed.' )
url = 'ip/get/' + str ( id_ip ) + "/"
code , xml = self . submit ( None , 'GET' , url )
return self . response ( code , xml ) |
def language ( lang_code ) :
'''Force a given language''' | ctx = None
if not request :
ctx = current_app . test_request_context ( )
ctx . push ( )
backup = g . get ( 'lang_code' )
g . lang_code = lang_code
refresh ( )
yield
g . lang_code = backup
if ctx :
ctx . pop ( )
refresh ( ) |
def off ( self , group = None ) :
"""Switch lights off . If group ( 1-4 ) is not specified ,
all four groups will be switched off .""" | if group is None or group == 0 :
self . _send_to_group ( group , send_on = False , command = "all_off" )
return
self . _send_to_group ( group , per_group = True , send_on = False , rgbw_cmd = self . RGBW_GROUP_X_OFF , white_cmd = self . WHITE_GROUP_X_OFF ) |
def event_matches ( self , event , simple = False , keys = False ) :
"""Get list of matches played at an event .
: param event : Event key to get data on .
: param keys : Return list of match keys only rather than full data on every match .
: param simple : Get only vital data .
: return : List of string ke... | if keys :
return self . _get ( 'event/%s/matches/keys' % event )
else :
return [ Match ( raw ) for raw in self . _get ( 'event/%s/matches%s' % ( event , '/simple' if simple else '' ) ) ] |
def _optimize ( self , maxIter = 1000 , c1 = 1.193 , c2 = 1.193 , lookback = 0.25 , standard_dev = None ) :
""": param maxIter : maximum number of swarm iterations
: param c1 : social weight
: param c2 : personal weight
: param lookback : how many particles to assess when considering convergence
: param sta... | gBests = [ ]
for swarm in self . _sample ( maxIter , c1 , c2 , lookback , standard_dev ) : # swarms . append ( swarm )
gBests . append ( self . _gbest . copy ( ) )
return gBests |
def tolerant_metaphone_processor ( words ) :
'''Double metaphone word processor slightly modified so that when no
words are returned by the algorithm , the original word is returned .''' | for word in words :
r = 0
for w in double_metaphone ( word ) :
if w :
w = w . strip ( )
if w :
r += 1
yield w
if not r :
yield word |
def ScanForWindowsVolume ( self , source_path ) :
"""Scans for a Windows volume .
Args :
source _ path ( str ) : source path .
Returns :
bool : True if a Windows volume was found .
Raises :
ScannerError : if the source path does not exists , or if the source path
is not a file or directory , or if the... | windows_path_specs = self . GetBasePathSpecs ( source_path )
if ( not windows_path_specs or self . _source_type == definitions . SOURCE_TYPE_FILE ) :
return False
file_system_path_spec = windows_path_specs [ 0 ]
self . _file_system = resolver . Resolver . OpenFileSystem ( file_system_path_spec )
if file_system_path... |
def handle_read ( self ) :
"""We got some output from a remote shell , this is one of the state
machine""" | if self . state == STATE_DEAD :
return
global nr_handle_read
nr_handle_read += 1
new_data = self . _handle_read_chunk ( )
if self . debug :
self . print_debug ( b'==> ' + new_data )
if self . handle_read_fast_case ( self . read_buffer ) :
return
lf_pos = new_data . find ( b'\n' )
if lf_pos >= 0 : # Optimiza... |
def ip_v4 ( self , with_port : bool = False ) -> str :
"""Generate a random IPv4 address .
: param with _ port : Add port to IP .
: return : Random IPv4 address .
: Example :
19.121.223.58""" | ip = '.' . join ( str ( self . random . randint ( 0 , 255 ) ) for _ in range ( 4 ) )
if with_port :
ip += ':{}' . format ( self . port ( ) )
return ip |
def generate_json_docs ( module , pretty_print = False , user = None ) :
"""Return a JSON string format of a Pale module ' s documentation .
This string can either be printed out , written to a file , or piped to some
other tool .
This method is a shorthand for calling ` generate _ doc _ dict ` and passing
... | indent = None
separators = ( ',' , ':' )
if pretty_print :
indent = 4
separators = ( ',' , ': ' )
module_doc_dict = generate_doc_dict ( module , user )
json_str = json . dumps ( module_doc_dict , indent = indent , separators = separators )
return json_str |
def _compute_magnitude_scaling_term ( self , C , mag ) :
"""Compute magnitude scaling term as defined in equation 19 , page 2291
( Tavakoli and Pezeshk , 2005)""" | assert mag <= 8.5
return C [ 'c1' ] + C [ 'c2' ] * mag + C [ 'c3' ] * ( 8.5 - mag ) ** 2.5 |
def create_intent ( project_id , display_name , training_phrases_parts , message_texts ) :
"""Create an intent of the given intent type .""" | import dialogflow_v2 as dialogflow
intents_client = dialogflow . IntentsClient ( )
parent = intents_client . project_agent_path ( project_id )
training_phrases = [ ]
for training_phrases_part in training_phrases_parts :
part = dialogflow . types . Intent . TrainingPhrase . Part ( text = training_phrases_part )
... |
def get_lead ( self , lead_id ) :
"""Get a specific lead saved on your account .
: param lead _ id : Id of the lead to search . Must be defined .
: return : Lead found as a dict .""" | params = self . base_params
endpoint = self . base_endpoint . format ( 'leads/' + str ( lead_id ) )
return self . _query_hunter ( endpoint , params ) |
async def get_final_destination ( self ) :
"""Get a list of final destinations for a stop .""" | dest = [ ]
await self . get_departures ( )
for departure in self . _departures :
dep = { }
dep [ 'line' ] = departure . get ( 'line' )
dep [ 'destination' ] = departure . get ( 'destination' )
dest . append ( dep )
return [ dict ( t ) for t in { tuple ( d . items ( ) ) for d in dest } ] |
def result_key_for ( self , op_name ) :
"""Checks for the presence of a ` ` result _ key ` ` , which defines what data
should make up an instance .
Returns ` ` None ` ` if there is no ` ` result _ key ` ` .
: param op _ name : The operation name to look for the ` ` result _ key ` ` in .
: type op _ name : s... | ops = self . resource_data . get ( 'operations' , { } )
op = ops . get ( op_name , { } )
key = op . get ( 'result_key' , None )
return key |
def _CalculateHashesFileEntry ( self , file_system , file_entry , parent_full_path , output_writer ) :
"""Recursive calculates hashes starting with the file entry .
Args :
file _ system ( dfvfs . FileSystem ) : file system .
file _ entry ( dfvfs . FileEntry ) : file entry .
parent _ full _ path ( str ) : fu... | # Since every file system implementation can have their own path
# segment separator we are using JoinPath to be platform and file system
# type independent .
full_path = file_system . JoinPath ( [ parent_full_path , file_entry . name ] )
for data_stream in file_entry . data_streams :
hash_value = self . _Calculate... |
def request_transfer ( subject , recipient , comment ) :
'''Initiate a transfer request''' | TransferPermission ( subject ) . test ( )
if recipient == ( subject . organization or subject . owner ) :
raise ValueError ( 'Recipient should be different than the current owner' )
transfer = Transfer . objects . create ( owner = subject . organization or subject . owner , recipient = recipient , subject = subject... |
def record ( self ) : # type : ( ) - > bytes
'''Generate a string representing the Rock Ridge Extension Selector record .
Parameters :
None .
Returns :
String containing the Rock Ridge record .''' | if not self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'ES record not yet initialized!' )
return b'ES' + struct . pack ( '=BBB' , RRESRecord . length ( ) , SU_ENTRY_VERSION , self . extension_sequence ) |
def _check_elements_equal ( lst ) :
"""Returns true if all of the elements in the list are equal .""" | assert isinstance ( lst , list ) , "Input value must be a list."
return not lst or lst . count ( lst [ 0 ] ) == len ( lst ) |
def if_else_action ( self , text , loc , arg ) :
"""Code executed after recognising if statement ' s else body""" | exshared . setpos ( loc , text )
if DEBUG > 0 :
print ( "IF_ELSE:" , arg )
if DEBUG == 2 :
self . symtab . display ( )
if DEBUG > 2 :
return
# jump to exit after all statements for true condition are executed
self . label_number = self . label_stack . pop ( )
label = self . codegen . label (... |
def find_content ( self , text ) :
"""Find content .""" | for m in self . pattern . finditer ( self . norm_nl ( text ) ) :
self . evaluate ( m ) |
def schemas_access_for_csv_upload ( self ) :
"""This method exposes an API endpoint to
get the schema access control settings for csv upload in this database""" | if not request . args . get ( 'db_id' ) :
return json_error_response ( 'No database is allowed for your csv upload' )
db_id = int ( request . args . get ( 'db_id' ) )
database = ( db . session . query ( models . Database ) . filter_by ( id = db_id ) . one ( ) )
try :
schemas_allowed = database . get_schema_acce... |
def _checkIndentationIssue ( self , node , node_type , linenoDocstring ) :
"""Check whether a docstring have consistent indentations .
@ param node : the node currently checks by pylint
@ param node _ type : type of given node
@ param linenoDocstring : line number the docstring begins""" | indentDocstring = node . col_offset and node . col_offset or 0
indentDocstring += len ( re . findall ( r'\n( *)"""' , node . as_string ( ) ) [ 0 ] )
linesDocstring = node . doc . lstrip ( "\n" ) . split ( "\n" )
for nline , lineDocstring in enumerate ( linesDocstring ) :
if ( nline < len ( linesDocstring ) - 1 and ... |
def serializePath ( pathObj , options ) :
"""Reserializes the path data with some cleanups .""" | # elliptical arc commands must have comma / wsp separating the coordinates
# this fixes an issue outlined in Fix https : / / bugs . launchpad . net / scour / + bug / 412754
return '' . join ( [ cmd + scourCoordinates ( data , options , control_points = controlPoints ( cmd , data ) , flags = flags ( cmd , data ) ) for c... |
def task ( name = None , t = INFO , * args , ** kwargs ) :
"""This decorator modifies current function such that its start , end , and
duration is logged in console . If the task name is not given , it will
attempt to infer it from the function name . Optionally , the decorator
can log information into files ... | def c_run ( name , f , t , args , kwargs ) :
def run ( * largs , ** lkwargs ) :
thread = __get_current_thread ( )
old_name = __THREAD_PARAMS [ thread ] [ __THREAD_PARAMS_FNAME_KEY ]
__THREAD_PARAMS [ thread ] [ __THREAD_PARAMS_FNAME_KEY ] = name
r = log ( name , f , t , largs , lkwar... |
def set_state ( self , state ) :
""": param state : a boolean of true ( on ) or false ( ' off ' )
: return : nothing""" | if self . index ( ) == 0 :
values = { "outlets" : [ { "desired_state" : { "powered" : state } } , { } ] }
else :
values = { "outlets" : [ { } , { "desired_state" : { "powered" : state } } ] }
response = self . api_interface . set_device_state ( self , values , id_override = self . parent_id ( ) , type_override ... |
def check_role ( self , identifiers , role_s , logical_operator ) :
""": param identifiers : a collection of identifiers
: type identifiers : subject _ abcs . IdentifierCollection
: param role _ s : 1 . . N role identifiers
: type role _ s : a String or Set of Strings
: param logical _ operator : indicates ... | self . assert_realms_configured ( )
has_role_s = self . has_role_collective ( identifiers , role_s , logical_operator )
if not has_role_s :
msg = "Subject does not have role(s) assigned."
raise UnauthorizedException ( msg ) |
def set_ctype ( self , ctype , orig_ctype = None ) :
"""Set the selected content type . Will not override the value of
the content type if that has already been determined .
: param ctype : The content type string to set .
: param orig _ ctype : The original content type , as found in the
configuration .""" | if self . ctype is None :
self . ctype = ctype
self . orig_ctype = orig_ctype |
def add_blackbox_or_builtin_call ( self , node , blackbox ) : # noqa : C901
"""Processes a blackbox or builtin function when it is called .
Nothing gets assigned to ret _ func _ foo in the builtin / blackbox case .
Increments self . function _ call _ index each time it is called , we can refer to it as N in the... | self . function_call_index += 1
saved_function_call_index = self . function_call_index
self . undecided = False
call_label_visitor = LabelVisitor ( )
call_label_visitor . visit ( node )
call_function_label = call_label_visitor . result [ : call_label_visitor . result . find ( '(' ) ]
# Check if function call matches a ... |
def kafka_install ( self ) :
"""kafka download and install
: return :""" | with cd ( '/tmp' ) :
if not exists ( 'kafka.tgz' ) :
sudo ( 'wget {0} -O kafka.tgz' . format ( bigdata_conf . kafka_download_url ) )
sudo ( 'tar -zxf kafka.tgz' )
sudo ( 'rm -rf {0}' . format ( bigdata_conf . kafka_home ) )
sudo ( 'mv kafka_* {0}' . format ( bigdata_conf . kafka_home ) ) |
def authorization_documents ( self ) :
""": rtype : twilio . rest . preview . hosted _ numbers . authorization _ document . AuthorizationDocumentList""" | if self . _authorization_documents is None :
self . _authorization_documents = AuthorizationDocumentList ( self )
return self . _authorization_documents |
def __validate_simple_subfield ( self , parameter , field , segment_list , _segment_index = 0 ) :
"""Verifies that a proposed subfield actually exists and is a simple field .
Here , simple means it is not a MessageField ( nested ) .
Args :
parameter : String ; the ' . ' delimited name of the current field bei... | if _segment_index >= len ( segment_list ) : # In this case , the field is the final one , so should be simple type
if isinstance ( field , messages . MessageField ) :
field_class = field . __class__ . __name__
raise TypeError ( 'Can\'t use messages in path. Subfield %r was ' 'included but is a %s.' ... |
def get_interval_timedelta ( self ) :
"""Spits out the timedelta in days .""" | now_datetime = timezone . now ( )
current_month_days = monthrange ( now_datetime . year , now_datetime . month ) [ 1 ]
# Two weeks
if self . interval == reminders_choices . INTERVAL_2_WEEKS :
interval_timedelta = datetime . timedelta ( days = 14 )
# One month
elif self . interval == reminders_choices . INTERVAL_ONE... |
def delete_message ( current ) :
"""Delete a message
. . code - block : : python
# request :
' view ' : ' _ zops _ delete _ message ,
' message _ key ' : key ,
# response :
' key ' : key ,
' status ' : ' OK ' ,
' code ' : 200""" | try :
Message ( current ) . objects . get ( sender_id = current . user_id , key = current . input [ 'key' ] ) . delete ( )
current . output = { 'status' : 'Deleted' , 'code' : 200 , 'key' : current . input [ 'key' ] }
except ObjectDoesNotExist :
raise HTTPError ( 404 , "" ) |
def cublasDgemm ( handle , transa , transb , m , n , k , alpha , A , lda , B , ldb , beta , C , ldc ) :
"""Matrix - matrix product for real general matrix .""" | status = _libcublas . cublasDgemm_v2 ( handle , _CUBLAS_OP [ transa ] , _CUBLAS_OP [ transb ] , m , n , k , ctypes . byref ( ctypes . c_double ( alpha ) ) , int ( A ) , lda , int ( B ) , ldb , ctypes . byref ( ctypes . c_double ( beta ) ) , int ( C ) , ldc )
cublasCheckStatus ( status ) |
def send_exception ( self , code , exc_info = None , headers = None ) :
"send an error response including a backtrace to the client" | if headers is None :
headers = { }
if not exc_info :
exc_info = sys . exc_info ( )
self . send_error_msg ( code , traceback . format_exception ( * exc_info ) , headers ) |
def from_file ( cls , paramname , filename ) :
"""Returns a new MultipartParam object constructed from the local
file at ` ` filename ` ` .
` ` filesize ` ` is determined by os . path . getsize ( ` ` filename ` ` )
` ` filetype ` ` is determined by mimetypes . guess _ type ( ` ` filename ` ` ) [ 0]
` ` file... | return cls ( paramname , filename = os . path . basename ( filename ) , filetype = mimetypes . guess_type ( filename ) [ 0 ] , filesize = os . path . getsize ( filename ) , fileobj = open ( filename , "rb" ) ) |
def cross ( v1 , v2 ) :
'''Computes the cross product of two vectors .''' | return ( v1 [ 1 ] * v2 [ 2 ] - v1 [ 2 ] * v2 [ 1 ] , v1 [ 2 ] * v2 [ 0 ] - v1 [ 0 ] * v2 [ 2 ] , v1 [ 0 ] * v2 [ 1 ] - v1 [ 1 ] * v2 [ 0 ] , ) |
def build_wheel ( ireq , sources , hashes = None , cache_dir = None ) :
"""Build a wheel file for the InstallRequirement object .
An artifact is downloaded ( or read from cache ) . If the artifact is not a
wheel , build one out of it . The dynamically built wheel is ephemeral ; do
not depend on its existence ... | kwargs = _prepare_wheel_building_kwargs ( ireq )
finder = _get_finder ( sources , cache_dir = cache_dir )
# Not for upgrade , hash not required . Hashes are not required here even
# when we provide them , because pip skips local wheel cache if we set it
# to True . Hashes are checked later if we need to download the fi... |
def geometrize_stops ( stops : List [ str ] , * , use_utm : bool = False ) -> DataFrame :
"""Given a stops DataFrame , convert it to a GeoPandas GeoDataFrame
and return the result .
Parameters
stops : DataFrame
A GTFS stops table
use _ utm : boolean
If ` ` True ` ` , then convert the output to local UTM... | import geopandas as gpd
g = ( stops . assign ( geometry = lambda x : [ sg . Point ( p ) for p in x [ [ "stop_lon" , "stop_lat" ] ] . values ] ) . drop ( [ "stop_lon" , "stop_lat" ] , axis = 1 ) . pipe ( lambda x : gpd . GeoDataFrame ( x , crs = cs . WGS84 ) ) )
if use_utm :
lat , lon = stops . loc [ 0 , [ "stop_lat... |
def get_gradient ( self , value , colors , upper_limit = 100 ) :
"""Map a value to a color
: param value : Some value
: return : A Hex color code""" | index = int ( self . percentage ( value , upper_limit ) )
if index >= len ( colors ) :
return colors [ - 1 ]
elif index < 0 :
return colors [ 0 ]
else :
return colors [ index ] |
def switch_state_machine_execution_engine ( self , new_state_machine_execution_engine ) :
"""Switch the state machine execution engine the main window controller listens to .
: param new _ state _ machine _ execution _ engine : the new state machine execution engine for this controller
: return :""" | # relieve old one
self . relieve_model ( self . state_machine_execution_model )
# register new
self . state_machine_execution_model = new_state_machine_execution_engine
self . observe_model ( self . state_machine_execution_model ) |
def get_playlist ( self , channel ) :
"""Return the playlist for the given channel
: param channel : the channel
: type channel : : class : ` models . Channel ` | : class : ` str `
: returns : the playlist
: rtype : : class : ` m3u8 . M3U8 `
: raises : : class : ` requests . HTTPError ` if channel is offl... | if isinstance ( channel , models . Channel ) :
channel = channel . name
token , sig = self . get_channel_access_token ( channel )
params = { 'token' : token , 'sig' : sig , 'allow_audio_only' : True , 'allow_source' : True }
r = self . usher_request ( 'GET' , 'channel/hls/%s.m3u8' % channel , params = params )
play... |
def GetQueryValuesFromDict ( cls , d , version = sorted ( _SERVICE_MAP . keys ( ) ) [ - 1 ] ) :
"""Converts a dict of python types into a list of PQL types .
Args :
d : A dictionary of variable names to python types .
version : A string identifying the Ad Manager version the values object
is compatible with... | return [ { 'key' : key , 'value' : cls . GetValueRepresentation ( value , version ) } for key , value in d . iteritems ( ) ] |
def flavor_rotation ( C_in , Uq , Uu , Ud , Ul , Ue , sm_parameters = True ) :
"""Gauge - invariant $ U ( 3 ) ^ 5 $ flavor rotation of all Wilson coefficients and
SM parameters .""" | C = { }
if sm_parameters : # shift of theta terms , see 0907.4763
C [ 'Thetas' ] = C_in [ 'Thetas' ] - 2 * argdet ( Uq ) + argdet ( Uu ) + argdet ( Ud )
C [ 'Theta' ] = C_in [ 'Theta' ] - 3 * argdet ( Uq ) - argdet ( Ul )
C [ 'Thetap' ] = ( C_in [ 'Thetap' ] - ( 1 / 6 ) * argdet ( Uq ) + ( 4 / 3 ) * argdet ... |
def interleave ( * args ) :
'''Interleaves the elements of the provided arrays .
> > > a = [ ( 0 , 0 ) , ( 1 , 0 ) , ( 2 , 0 ) , ( 3 , 0 ) ]
> > > b = [ ( 0 , 0 ) , ( 0 , 1 ) , ( 0 , 2 ) , ( 0 , 3 ) ]
> > > interleave ( a , b )
[ ( 0 , 0 , 0 , 0 ) , ( 1 , 0 , 0 , 1 ) , ( 2 , 0 , 0 , 2 ) , ( 3 , 0 , 0 , 3 ) ... | result = [ ]
for array in zip ( * args ) :
result . append ( tuple ( flatten ( array ) ) )
return result |
def utc_iso ( self , delimiter = 'T' , places = 0 ) :
"""Convert to an ISO 8601 string like ` ` 2014-01-18T01:35:38Z ` ` in UTC .
If this time is an array of dates , then a sequence of strings is
returned instead of a single string .""" | # " places " used to be the 1st argument , so continue to allow an
# integer in that spot . TODO : deprecate this in Skyfield 2.0
# and remove it in 3.0.
if isinstance ( delimiter , int ) :
places = delimiter
delimiter = 'T'
if places :
power_of_ten = 10 ** places
offset = _half_second / power_of_ten
... |
def get_area ( self , area_id , resolve_missing = False ) :
"""Get an area by its ID .
: param area _ id : The area ID
: type area _ id : Integer
: param resolve _ missing : Query the Overpass API if the area is missing in the result set .
: return : The area
: rtype : overpy . Area
: raises overpy . ex... | areas = self . get_areas ( area_id = area_id )
if len ( areas ) == 0 :
if resolve_missing is False :
raise exception . DataIncomplete ( "Resolve missing area is disabled" )
query = ( "\n" "[out:json];\n" "area({area_id});\n" "out body;\n" )
query = query . format ( area_id = area_id )
tmp_result... |
def new_recruit ( self , match ) :
"""Dispatched to by notify ( ) . If a recruitment request has been issued ,
open a browser window for the a new participant ( in this case the
person doing local debugging ) .""" | self . out . log ( "new recruitment request!" )
url = match . group ( 1 )
if self . proxy_port is not None :
self . out . log ( "Using proxy port {}" . format ( self . proxy_port ) )
url = url . replace ( str ( get_config ( ) . get ( "base_port" ) ) , self . proxy_port )
new_webbrowser_profile ( ) . open ( url ... |
def heptad_register ( self ) :
"""Returns the calculated register of the coiled coil and the fit quality .""" | base_reg = 'abcdefg'
exp_base = base_reg * ( self . cc_len // 7 + 2 )
ave_ca_layers = self . calc_average_parameters ( self . ca_layers ) [ 0 ] [ : - 1 ]
reg_fit = fit_heptad_register ( ave_ca_layers )
hep_pos = reg_fit [ 0 ] [ 0 ]
return exp_base [ hep_pos : hep_pos + self . cc_len ] , reg_fit [ 0 ] [ 1 : ] |
def AddAnalogShortIdMsecRecordNoStatus ( site_service , tag , time_value , msec , value ) :
"""This function will add an analog value to the specified eDNA service and
tag , without an associated point status .
: param site _ service : The site . service where data will be pushed
: param tag : The eDNA tag to... | # Define all required variables in the correct ctypes format
szService = c_char_p ( site_service . encode ( 'utf-8' ) )
szPointId = c_char_p ( tag . encode ( 'utf-8' ) )
tTime = c_long ( int ( time_value ) )
dValue = c_double ( value )
usMsec = c_ushort ( msec )
# Try to push the data . Function will return 0 if succes... |
def _load_json_file_or_url ( self , json_path_or_url ) :
'''Return the JSON at the local path or URL as a dict
This method raises DataPackageRegistryException if there were any
errors .''' | try :
if os . path . isfile ( json_path_or_url ) :
with open ( json_path_or_url , 'r' ) as f :
result = json . load ( f )
else :
res = requests . get ( json_path_or_url )
res . raise_for_status ( )
result = res . json ( )
return result
except ( ValueError , reques... |
def fft ( a , n = None , axis = - 1 , norm = None ) :
"""Compute the one - dimensional discrete Fourier Transform .
This function computes the one - dimensional * n * - point discrete Fourier
Transform ( DFT ) with the efficient Fast Fourier Transform ( FFT )
algorithm [ CT ] .
Parameters
a : array _ like... | output = mkl_fft . fft ( a , n , axis )
if _unitary ( norm ) :
output *= 1 / sqrt ( output . shape [ axis ] )
return output |
def basic_auth ( credentials ) :
"""Create an HTTP basic authentication callable
Parameters
credentials : ~ typing . Tuple [ str , str ]
The ( username , password ) - tuple
Returns
~ typing . Callable [ [ Request ] , Request ]
A callable which adds basic authentication to a : class : ` Request ` .""" | encoded = b64encode ( ':' . join ( credentials ) . encode ( 'ascii' ) ) . decode ( )
return header_adder ( { 'Authorization' : 'Basic ' + encoded } ) |
def add_process ( self , command = None , vsplit = False , start_directory = None ) :
"""Add a new process to the current window . ( vsplit / hsplit ) .""" | assert command is None or isinstance ( command , six . text_type )
assert start_directory is None or isinstance ( start_directory , six . text_type )
window = self . arrangement . get_active_window ( )
pane = self . _create_pane ( window , command , start_directory = start_directory )
window . add_pane ( pane , vsplit ... |
def add_document ( self , question , answer ) :
"""Add question answer set to DB .
: param question : A question to an answer
: type question : : class : ` str `
: param answer : An answer to a question
: type answer : : class : ` str `""" | question = question . strip ( )
answer = answer . strip ( )
session = self . Session ( )
if session . query ( Document ) . filter_by ( text = question , answer = answer ) . count ( ) :
logger . info ( 'Already here: {0} -> {1}' . format ( question , answer ) )
return
logger . info ( 'add document: {0} -> {1}' .... |
def read_samples ( self , parameters , array_class = None , ** kwargs ) :
"""Reads samples for the given parameter ( s ) .
The ` ` parameters ` ` can be the name of any dataset in ` ` samples _ group ` ` ,
a virtual field or method of ` ` FieldArray ` ` ( as long as the file
contains the necessary fields to d... | # get the type of array class to use
if array_class is None :
array_class = FieldArray
# get the names of fields needed for the given parameters
possible_fields = self [ self . samples_group ] . keys ( )
loadfields = array_class . parse_parameters ( parameters , possible_fields )
samples = self . read_raw_samples (... |
def _batched_op_msg_impl ( operation , command , docs , check_keys , ack , opts , ctx , buf ) :
"""Create a batched OP _ MSG write .""" | max_bson_size = ctx . max_bson_size
max_write_batch_size = ctx . max_write_batch_size
max_message_size = ctx . max_message_size
flags = b"\x00\x00\x00\x00" if ack else b"\x02\x00\x00\x00"
# Flags
buf . write ( flags )
# Type 0 Section
buf . write ( b"\x00" )
buf . write ( _dict_to_bson ( command , False , opts ) )
# Ty... |
def read_crtf ( filename , errors = 'strict' ) :
"""Reads a CRTF region file and returns a list of region objects .
Parameters
filename : ` str `
The file path
errors : ` ` warn ` ` , ` ` ignore ` ` , ` ` strict ` ` , optional
The error handling scheme to use for handling parsing errors .
The default is... | with open ( filename ) as fh :
if regex_begin . search ( fh . readline ( ) ) :
region_string = fh . read ( )
parser = CRTFParser ( region_string , errors )
return parser . shapes . to_regions ( )
else :
raise CRTFRegionParserError ( 'Every CRTF Region must start with "#CRTF" ' ) |
def _build_strain_specific_model ( self , strain_id , ref_functional_genes , orth_matrix , force_rerun = False ) :
"""Create strain GEMPRO , set functional genes""" | gp_noseqs_path = op . join ( self . model_dir , '{}_gp.pckl' . format ( strain_id ) )
if ssbio . utils . force_rerun ( flag = force_rerun , outfile = gp_noseqs_path ) :
logging . disable ( logging . WARNING )
strain_gp = GEMPRO ( gem_name = strain_id )
# if self . reference _ gempro . model :
# strain _... |
def get_timestamp ( time = True , precice = False ) :
'''What time is it ?
: param time :
Append ` ` - % H . % M . % S ` ` to the final string .
: param precice :
Append ` ` - % f ` ` to the final string .
Is only recognized when ` time ` is set to ` ` True ` `
: returns :
A timestamp string of now in... | f = '%Y.%m.%d'
if time :
f += '-%H.%M.%S'
if precice :
f += '-%f'
return _datetime . now ( ) . strftime ( f ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.