signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def libvlc_media_set_user_data ( p_md , p_new_user_data ) :
'''Sets media descriptor ' s user _ data . user _ data is specialized data
accessed by the host application , VLC . framework uses it as a pointer to
an native object that references a L { Media } pointer .
@ param p _ md : media descriptor object . ... | f = _Cfunctions . get ( 'libvlc_media_set_user_data' , None ) or _Cfunction ( 'libvlc_media_set_user_data' , ( ( 1 , ) , ( 1 , ) , ) , None , None , Media , ctypes . c_void_p )
return f ( p_md , p_new_user_data ) |
def _init_from_csc ( self , csc ) :
"""Initialize data from a CSC matrix .""" | if len ( csc . indices ) != len ( csc . data ) :
raise ValueError ( 'length mismatch: {} vs {}' . format ( len ( csc . indices ) , len ( csc . data ) ) )
self . handle = ctypes . c_void_p ( )
_check_call ( _LIB . XGDMatrixCreateFromCSC ( c_array ( ctypes . c_ulong , csc . indptr ) , c_array ( ctypes . c_uint , csc ... |
def remove_regions_with_no_gates ( regions ) :
"""Removes all Jove regions from a list of regions .
: param regions : A list of tuples ( regionID , regionName )
: type regions : list
: return : A list of regions minus those in jove space
: rtype : list""" | list_of_gateless_regions = [ ( 10000004 , 'UUA-F4' ) , ( 10000017 , 'J7HZ-F' ) , ( 10000019 , 'A821-A' ) , ]
for gateless_region in list_of_gateless_regions :
if gateless_region in regions :
regions . remove ( gateless_region )
return regions |
def add_loghandler ( handler ) :
"""Add log handler to root logger and LOG _ ROOT and set formatting .""" | format = "%(levelname)s %(name)s %(asctime)s %(threadName)s %(message)s"
handler . setFormatter ( logging . Formatter ( format ) )
logging . getLogger ( LOG_ROOT ) . addHandler ( handler )
logging . getLogger ( ) . addHandler ( handler ) |
def eth_getBalance ( self , address = None , block = BLOCK_TAG_LATEST ) :
"""TODO : documentation
https : / / github . com / ethereum / wiki / wiki / JSON - RPC # eth _ getbalance
TESTED""" | address = address or self . eth_coinbase ( )
block = validate_block ( block )
return hex_to_dec ( self . _call ( "eth_getBalance" , [ address , block ] ) ) |
def firmware_download_input_protocol_type_scp_protocol_scp_user ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
firmware_download = ET . Element ( "firmware_download" )
config = firmware_download
input = ET . SubElement ( firmware_download , "input" )
protocol_type = ET . SubElement ( input , "protocol-type" )
scp_protocol = ET . SubElement ( protocol_type , "scp-protocol" )
scp = ET . SubEleme... |
def to_gds ( self , multiplier ) :
"""Convert this object to a series of GDSII elements .
Parameters
multiplier : number
A number that multiplies all dimensions written in the GDSII
elements .
Returns
out : string
The GDSII binary string that represents this object .""" | data = [ ]
for ii in range ( len ( self . polygons ) ) :
if len ( self . polygons [ ii ] ) > 4094 :
raise ValueError ( "[GDSPY] Polygons with more than 4094 are " "not supported by the GDSII format." )
data . append ( struct . pack ( '>10h' , 4 , 0x0800 , 6 , 0x0D02 , self . layers [ ii ] , 6 , 0x0E02 ,... |
async def handle_post_request ( self , environ ) :
"""Handle a long - polling POST request from the client .""" | length = int ( environ . get ( 'CONTENT_LENGTH' , '0' ) )
if length > self . server . max_http_buffer_size :
raise exceptions . ContentTooLongError ( )
else :
body = await environ [ 'wsgi.input' ] . read ( length )
p = payload . Payload ( encoded_payload = body )
for pkt in p . packets :
await s... |
def get_sign_command ( self , filename , signer , sign_password , keystore = None ) :
"""Return a suitable command for signing a file .
: param filename : The pathname to the file to be signed .
: param signer : The identifier of the signer of the file .
: param sign _ password : The passphrase for the signer... | cmd = [ self . gpg , '--status-fd' , '2' , '--no-tty' ]
if keystore is None :
keystore = self . gpg_home
if keystore :
cmd . extend ( [ '--homedir' , keystore ] )
if sign_password is not None :
cmd . extend ( [ '--batch' , '--passphrase-fd' , '0' ] )
td = tempfile . mkdtemp ( )
sf = os . path . join ( td , ... |
def compute_angle_weights_1d ( angles ) :
"""Compute the weight for each angle according to the distance between its
neighbors .
Parameters
angles : 1d ndarray of length A
Angles in radians
Returns
weights : 1d ndarray of length A
The weights for each angle
Notes
To compute the weights , the angle... | # copy and modulo np . pi
# This is an array with values in [ 0 , np . pi )
angles = ( angles . flatten ( ) - angles . min ( ) ) % ( np . pi )
# sort the array
sortargs = np . argsort ( angles )
sortangl = angles [ sortargs ]
# compute weights for sorted angles
da = ( np . roll ( sortangl , - 1 ) - np . roll ( sortangl... |
def ren ( i ) :
"""Input : {
( repo _ uoa ) - repo UOA
module _ uoa - module UOA
data _ uoa - old data UOA
new _ data _ uoa - new data alias
or
new _ data _ uid - new data UID ( leave empty to keep old one )
or
xcids [ 0 ] - { ' data _ uoa ' } - new data UOA
( new _ uid ) - generate new UID
( re... | # Check if global writing is allowed
r = check_writing ( { 'delete' : 'yes' } )
if r [ 'return' ] > 0 :
return r
o = i . get ( 'out' , '' )
ruoa = i . get ( 'repo_uoa' , '' )
muoa = i . get ( 'module_uoa' , '' )
duoa = i . get ( 'data_uoa' , '' )
if muoa == '' :
return { 'return' : 1 , 'error' : 'module UOA is ... |
def add_node ( self , node , adapter_number , port_number , label = None , dump = True ) :
"""Add a node to the link
: param dump : Dump project on disk""" | port = node . get_port ( adapter_number , port_number )
if port is None :
raise aiohttp . web . HTTPNotFound ( text = "Port {}/{} for {} not found" . format ( adapter_number , port_number , node . name ) )
if port . link is not None :
raise aiohttp . web . HTTPConflict ( text = "Port is already used" )
self . _... |
def on_bar_data ( self , bars ) :
"""Process the incoming tick data array""" | for tick in XmlHelper . node_iter ( bars ) :
names = [ str ( tick . getElement ( _ ) . name ( ) ) for _ in range ( tick . numElements ( ) ) ]
barmap = { n : XmlHelper . get_child_value ( tick , n ) for n in names }
self . response . bars . append ( barmap ) |
def find_element ( self , value , by = By . ID , update = False ) -> Elements :
'''Find a element or the first element .''' | if update or not self . _nodes :
self . uidump ( )
for node in self . _nodes :
if node . attrib [ by ] == value :
bounds = node . attrib [ 'bounds' ]
coord = list ( map ( int , re . findall ( r'\d+' , bounds ) ) )
click_point = ( coord [ 0 ] + coord [ 2 ] ) / 2 , ( coord [ 1 ] + coord [ ... |
def ip_addresses ( self , value ) :
""": param value : a list of ip addresses""" | if not isinstance ( value , list ) :
raise ValueError ( 'ip_addresses value must be a list' )
# in soem cases self . data might be none , so let ' s instantiate an empty dict
if self . data is None :
self . data = { }
# update field
self . data [ 'ip_addresses' ] = ', ' . join ( value ) |
def Set ( self , interface_name , property_name , value , * args , ** kwargs ) :
'''Standard D - Bus API for setting a property value''' | self . log ( 'Set %s.%s%s' % ( interface_name , property_name , self . format_args ( ( value , ) ) ) )
try :
iface_props = self . props [ interface_name ]
except KeyError :
raise dbus . exceptions . DBusException ( 'no such interface ' + interface_name , name = self . interface + '.UnknownInterface' )
if proper... |
def find_contig_distribution ( contig_lengths_dict ) :
"""Determine the frequency of different contig size ranges for each strain
: param contig _ lengths _ dict :
: return : contig _ len _ dist _ dict : dictionary of strain name : tuple of contig size range frequencies""" | # Initialise the dictionary
contig_len_dist_dict = dict ( )
for file_name , contig_lengths in contig_lengths_dict . items ( ) : # Initialise integers to store the number of contigs that fall into the different bin sizes
over_1000000 = 0
over_500000 = 0
over_100000 = 0
over_50000 = 0
over_10000 = 0
... |
def _badpath ( path , base ) :
"""joinpath will ignore base if path is absolute .""" | return not _resolved ( os . path . join ( base , path ) ) . startswith ( base ) |
def contains_only ( self , elements ) :
"""Ensures : attr : ` subject ` contains all of * elements * , which must be an iterable , and no other items .""" | for element in self . _subject :
if element not in elements :
raise self . _error_factory ( _format ( "Expected {} to have only {}, but it contains {}" , self . _subject , elements , element ) )
self . contains_all_of ( elements )
return ChainInspector ( self . _subject ) |
def update ( self , other , copy = True , * args , ** kwargs ) :
"""Update this element related to other element .
: param other : same type than this .
: param bool copy : copy other before update attributes .
: param tuple args : copy args .
: param dict kwargs : copy kwargs .
: return : this""" | if other : # dirty hack for python2.6
if isinstance ( other , self . __class__ ) :
if copy :
other = other . copy ( * args , ** kwargs )
for slot in other . __slots__ :
attr = getattr ( other , slot )
if attr is not None :
setattr ( self , slot , a... |
def _output_terms ( self ) :
"""A list of terms that are outputs of this pipeline .
Includes all terms registered as data outputs of the pipeline , plus the
screen , if present .""" | terms = list ( six . itervalues ( self . _columns ) )
screen = self . screen
if screen is not None :
terms . append ( screen )
return terms |
def _char_density ( self , c , font = ImageFont . load_default ( ) ) :
"""Count the number of black pixels in a rendered character .""" | image = Image . new ( '1' , font . getsize ( c ) , color = 255 )
draw = ImageDraw . Draw ( image )
draw . text ( ( 0 , 0 ) , c , fill = "white" , font = font )
return collections . Counter ( image . getdata ( ) ) [ 0 ] |
def add_mpl_dendrogram ( dfr , fig , heatmap_gs , orientation = "col" ) :
"""Return a dendrogram and corresponding gridspec , attached to the fig
Modifies the fig in - place . Orientation is either ' row ' or ' col ' and
determines location and orientation of the rendered dendrogram .""" | # Row or column axes ?
if orientation == "row" :
dists = distance . squareform ( distance . pdist ( dfr ) )
spec = heatmap_gs [ 1 , 0 ]
orient = "left"
nrows , ncols = 1 , 2
height_ratios = [ 1 ]
else : # Column dendrogram
dists = distance . squareform ( distance . pdist ( dfr . T ) )
spec =... |
def disconnect ( self ) :
"""Close the TCP connection with the graphite server .""" | try :
self . socket . shutdown ( 1 )
# If its currently a socket , set it to None
except AttributeError :
self . socket = None
except Exception :
self . socket = None
# Set the self . socket to None , no matter what .
finally :
self . socket = None |
def sender ( self , jid : str ) :
"""Set jid of the sender
Args :
jid ( str ) : jid of the sender""" | if jid is not None and not isinstance ( jid , str ) :
raise TypeError ( "'sender' MUST be a string" )
self . _sender = aioxmpp . JID . fromstr ( jid ) if jid is not None else None |
def request_middleware ( api = None ) :
"""Registers a middleware function that will be called on every request""" | def decorator ( middleware_method ) :
apply_to_api = hug . API ( api ) if api else hug . api . from_object ( middleware_method )
class MiddlewareRouter ( object ) :
__slots__ = ( )
def process_request ( self , request , response ) :
return middleware_method ( request , response )
... |
def base_ws_uri ( ) :
"""Base websocket URL that is advertised to external clients .
Useful when the websocket URL advertised to the clients needs to be
customized ( typically when running behind NAT , firewall , etc . )""" | scheme = config [ 'wsserver' ] [ 'advertised_scheme' ]
host = config [ 'wsserver' ] [ 'advertised_host' ]
port = config [ 'wsserver' ] [ 'advertised_port' ]
return '{}://{}:{}' . format ( scheme , host , port ) |
def decorate ( text , style ) :
"""Console decoration style definitions
: param text : the text string to decorate
: type text : str
: param style : the style used to decorate the string
: type style : str
: return : a decorated string
: rtype : str""" | return { 'step-maj' : click . style ( "\n" + '> ' + text , fg = 'yellow' , bold = True ) , 'step-min' : click . style ( ' - ' + text + ' ' , bold = True ) , 'item-maj' : click . style ( ' - ' + text + ' ' ) , 'item-min' : click . style ( ' - ' + text + ' ' ) , 'quote-head-fail' : click . style ( "\n" + chr ( 9... |
def validate_json ( self , json_value , validator ) :
"""Validates and returns the parsed JSON string .
If the value is not valid JSON , ParseError will be raised . If it is
valid JSON , but does not validate against the schema ,
SchemaValidationError will be raised .
: param str json _ value : JSON value .... | value = parse_json ( json_value )
return self . validate ( value , validator ) |
def add_cookie_header ( self , request , referrer_host = None ) :
'''Wrapped ` ` add _ cookie _ header ` ` .
Args :
request : An instance of : class : ` . http . request . Request ` .
referrer _ host ( str ) : An hostname or IP address of the referrer
URL .''' | new_request = convert_http_request ( request , referrer_host )
self . _cookie_jar . add_cookie_header ( new_request )
request . fields . clear ( )
for name , value in new_request . header_items ( ) :
request . fields . add ( name , value ) |
def body_echo ( cls , request , foo : ( Ptypes . body , String ( 'A body parameter' ) ) ) -> [ ( 200 , 'Ok' , String ) ] :
'''Echo the body parameter .''' | log . info ( 'Echoing body param, value is: {}' . format ( foo ) )
for i in range ( randint ( 0 , MAX_LOOP_DURATION ) ) :
yield
msg = 'The value sent was: {}' . format ( foo )
Respond ( 200 , msg ) |
def array_repeat ( col , count ) :
"""Collection function : creates an array containing a column repeated count times .
> > > df = spark . createDataFrame ( [ ( ' ab ' , ) ] , [ ' data ' ] )
> > > df . select ( array _ repeat ( df . data , 3 ) . alias ( ' r ' ) ) . collect ( )
[ Row ( r = [ u ' ab ' , u ' ab ... | sc = SparkContext . _active_spark_context
return Column ( sc . _jvm . functions . array_repeat ( _to_java_column ( col ) , count ) ) |
def run ( args ) :
"""Start an oct project
: param Namespace args : the commande - line arguments""" | kwargs = vars ( args )
if 'func' in kwargs :
del kwargs [ 'func' ]
project_path = kwargs . pop ( 'project_path' )
config = configure ( project_path , kwargs . get ( 'config_file' ) )
output_dir = kwargs . pop ( 'output_dir' , None ) or generate_output_path ( args , project_path )
stats_handler . init_stats ( output... |
def to_graphviz ( self ) -> str :
"""Converts the FSM behaviour structure to Graphviz syntax
Returns :
str : the graph in Graphviz syntax""" | graph = "digraph finite_state_machine { rankdir=LR; node [fixedsize=true];"
for origin , dest in self . _transitions . items ( ) :
origin = origin . replace ( " " , "_" )
for d in dest :
d = d . replace ( " " , "_" )
graph += "{0} -> {1};" . format ( origin , d )
graph += "}"
return graph |
def predict ( df , filters , model_fit , ytransform = None ) :
"""Apply model to new data to predict new dependent values .
Parameters
df : pandas . DataFrame
filters : list of str
Any filters to apply before doing prediction .
model _ fit : statsmodels . regression . linear _ model . OLSResults
Result ... | df = util . apply_filter_query ( df , filters )
with log_start_finish ( 'statsmodels predict' , logger ) :
sim_data = model_fit . predict ( df )
if len ( sim_data ) != len ( df ) :
raise ModelEvaluationError ( 'Predicted data does not have the same length as input. ' 'This suggests there are null values in one ... |
def get_listeners ( self , event_type : str ) -> List [ Callable ] :
"""Get all listeners of a particular type of event .""" | if event_type not in self . events :
raise ValueError ( f'No event {event_type} in system.' )
return self . events . get_listeners ( event_type ) |
def __Script_Editor_Output_plainTextEdit_contextMenuEvent ( self , event ) :
"""Reimplements the : meth : ` QPlainTextEdit . contextMenuEvent ` method .
: param event : QEvent .
: type event : QEvent""" | menu = self . Script_Editor_Output_plainTextEdit . createStandardContextMenu ( )
menu . addSeparator ( )
menu . addAction ( self . __engine . actions_manager . register_action ( "Actions|Umbra|Components|factory.script_editor|Edit Selected Path" , slot = self . __edit_selected_path_action__triggered ) )
menu . exec_ ( ... |
def generate_transaction_id ( stmt_line ) :
"""Generate pseudo - unique id for given statement line .
This function can be used in statement parsers when real transaction id is
not available in source statement .""" | return str ( abs ( hash ( ( stmt_line . date , stmt_line . memo , stmt_line . amount ) ) ) ) |
def set_config_from_commit ( self , commit ) :
"""Given a git commit , applies config specified in the commit message .
Supported :
- gitlint - ignore : all""" | for line in commit . message . body :
pattern = re . compile ( r"^gitlint-ignore:\s*(.*)" )
matches = pattern . match ( line )
if matches and len ( matches . groups ( ) ) == 1 :
self . set_option ( 'general' , 'ignore' , matches . group ( 1 ) ) |
def write_object_to_file ( self , obj , path = '.' , filename = None ) :
"""Convert obj ( dict ) to json string and write to file""" | output = self . json_dumps ( obj ) + '\n'
if filename is None :
filename = self . safe_filename ( obj [ '_type' ] , obj [ '_id' ] )
filename = os . path . join ( path , filename )
self . pr_inf ( "Writing to file: " + filename )
with open ( filename , 'w' ) as f :
f . write ( output )
# self . pr _ dbg ( " Cont... |
def get_build_path ( self ) :
"""Used to determine where to build the page . Override this if you
would like your page at a different location . By default it
will be built at self . get _ url ( ) + " / index . html " """ | target_path = path . join ( settings . BUILD_DIR , self . get_url ( ) . lstrip ( '/' ) )
if not self . fs . exists ( target_path ) :
logger . debug ( "Creating {}" . format ( target_path ) )
self . fs . makedirs ( target_path )
return os . path . join ( target_path , 'index.html' ) |
def decode ( response ) :
"""Decodes and returns the response as JSON ( dict ) or raise BackendException
: param response : requests . response object
: return : dict""" | # Second stage . Errors are backend errors ( bad login , bad url , . . . )
try :
response . raise_for_status ( )
except requests . HTTPError as exp :
response = { "_status" : "ERR" , "_error" : { "message" : exp , "code" : response . status_code } , "_issues" : { "message" : exp , "code" : response . status_cod... |
def info ( self , correlation_id , message , * args , ** kwargs ) :
"""Logs an important information message
: param correlation _ id : ( optional ) transaction id to trace execution through call chain .
: param message : a human - readable message to log .
: param args : arguments to parameterize the message... | self . _format_and_write ( LogLevel . Info , correlation_id , None , message , args , kwargs ) |
def addFilter ( self , field , value ) :
"""Add a filter to the seach .
: param field : what field filter ( see GitHub search ) .
: type field : str .
: param value : value of the filter ( see GitHub search ) .
: type value : str .""" | if "<" not in value or ">" not in value or ".." not in value :
value = ":" + value
if self . __urlFilters :
self . __urlFilters += "+" + field + str ( quote ( value ) )
else :
self . __urlFilters += field + str ( quote ( value ) ) |
def service ( action , service_name , ** kwargs ) :
"""Control a system service .
: param action : the action to take on the service
: param service _ name : the name of the service to perform th action on
: param * * kwargs : additional params to be passed to the service command in
the form of key = value ... | if init_is_systemd ( ) :
cmd = [ 'systemctl' , action , service_name ]
else :
cmd = [ 'service' , service_name , action ]
for key , value in six . iteritems ( kwargs ) :
parameter = '%s=%s' % ( key , value )
cmd . append ( parameter )
return subprocess . call ( cmd ) == 0 |
def watched ( cls , * args , ** kwargs ) :
"""Create and return a : class : ` Watchable ` with its : class : ` Specatator ` .
See : func : ` watch ` for more info on : class : ` Specatator ` registration .
Parameters
cls : type :
A subclass of : class : ` Watchable `
* args :
Positional arguments used t... | value = cls ( * args , ** kwargs )
return value , watch ( value ) |
def find_first_object ( self , ObjectClass , ** kwargs ) :
"""Retrieve the first object of type ` ` ObjectClass ` ` ,
matching the specified filters in ` ` * * kwargs ` ` - - case sensitive .""" | filter = None
for k , v in kwargs . items ( ) :
cond = getattr ( ObjectClass , k ) == v
filter = cond if filter is None else filter & cond
return list ( ObjectClass . scan ( filter , limit = 1 ) ) [ 0 ] |
def gen_TKIP_RC4_key ( TSC , TA , TK ) :
"""Implement TKIP WEPSeed generation
TSC : packet IV
TA : target addr bytes
TK : temporal key""" | assert len ( TSC ) == 6
assert len ( TA ) == 6
assert len ( TK ) == 16
assert all ( isinstance ( x , six . integer_types ) for x in TSC + TA + TK )
# Phase 1
# 802.11i p . 54
# Phase 1 - Step 1
TTAK = [ ]
TTAK . append ( _MK16 ( TSC [ 3 ] , TSC [ 2 ] ) )
TTAK . append ( _MK16 ( TSC [ 5 ] , TSC [ 4 ] ) )
TTAK . append (... |
def set_value ( self , value , layer = None , source = None ) :
"""Set a value for a particular layer with optional metadata about source .
Parameters
value : str
Data to store in the node .
layer : str
Name of the layer to use . If None then the outermost where the value
exists will be used .
source ... | if self . _frozen :
raise TypeError ( 'Frozen ConfigNode does not support assignment' )
if not layer :
layer = self . _layers [ - 1 ]
self . _values [ layer ] = ( source , value ) |
def declareAsOntology ( self , graph ) :
"""The file we output needs to be declared as an ontology ,
including it ' s version information .
TEC : I am not convinced dipper reformating external data as RDF triples
makes an OWL ontology ( nor that it should be considered a goal ) .
Proper ontologies are built... | # < http : / / data . monarchinitiative . org / ttl / biogrid . ttl > a owl : Ontology ;
# owl : versionInfo
# < https : / / archive . monarchinitiative . org / YYYYMM / ttl / biogrid . ttl >
model = Model ( graph )
# is self . outfile suffix set yet ? ? ?
ontology_file_id = 'MonarchData:' + self . name + ".ttl"
model ... |
def record_coverage_zero ( self , rule , offset ) :
"""Add entry to coverage saying this selector was parsed""" | self . coverage_lines . append ( 'DA:{},0' . format ( rule . source_line + offset ) ) |
def _process_response ( response ) :
"""Process the raw AWS response , returning either the mapped exception
or deserialized response .
: param tornado . concurrent . Future response : The request future
: rtype : dict or list
: raises : sprockets _ dynamodb . exceptions . DynamoDBException""" | error = response . exception ( )
if error :
if isinstance ( error , aws_exceptions . AWSError ) :
if error . args [ 1 ] [ 'type' ] in exceptions . MAP :
raise exceptions . MAP [ error . args [ 1 ] [ 'type' ] ] ( error . args [ 1 ] [ 'message' ] )
raise error
http_response = response . result... |
def process_custom ( custom ) :
"""Process custom .""" | custom_selectors = { }
if custom is not None :
for key , value in custom . items ( ) :
name = util . lower ( key )
if RE_CUSTOM . match ( name ) is None :
raise SelectorSyntaxError ( "The name '{}' is not a valid custom pseudo-class name" . format ( name ) )
if name in custom_sel... |
def replace ( self , infile ) :
'''Replace : 任意の箇所のバイト列と 同サイズの任意のバイト列を入れ換える''' | gf = infile [ 31 : ]
same_size_index = [ ]
while len ( same_size_index ) <= 1 :
index = random . randint ( 0 , len ( gf ) - 1 )
index_len = len ( gf [ index ] )
same_size_index = [ i for ( i , g ) in enumerate ( gf ) if len ( g ) == index_len ]
else :
same_size_index = random . choice ( same_size_index ... |
def fillna ( self , value = None , method = None , axis = None , inplace = False , limit = None , downcast = None , ** kwargs ) :
"""Fill NA / NaN values using the specified method .
Args :
value : Value to use to fill holes . This value cannot be a list .
method : Method to use for filling holes in reindexed... | # TODO implement value passed as DataFrame / Series
if isinstance ( value , BasePandasDataset ) :
new_query_compiler = self . _default_to_pandas ( "fillna" , value = value . _to_pandas ( ) , method = method , axis = axis , inplace = False , limit = limit , downcast = downcast , ** kwargs ) . _query_compiler
ret... |
def get_hdrs_len ( self ) : # type : ( ) - > int
"""get _ hdrs _ len computes the length of the hdrs field
To do this computation , the length of the padlen field , the priority
information fields and the actual padding is subtracted to the string
that was provided to the pre _ dissect fun of the pkt paramete... | padding_len = self . getfieldval ( 'padlen' )
fld , fval = self . getfield_and_val ( 'padlen' )
padding_len_len = fld . i2len ( self , fval )
bit_cnt = self . get_field ( 'exclusive' ) . size
bit_cnt += self . get_field ( 'stream_dependency' ) . size
fld , fval = self . getfield_and_val ( 'weight' )
weight_len = fld . ... |
def get_file_to_path ( self , share_name , directory_name , file_name , file_path , open_mode = 'wb' , start_range = None , end_range = None , validate_content = False , progress_callback = None , max_connections = 2 , timeout = None ) :
'''Downloads a file to a file path , with automatic chunking and progress
no... | _validate_not_none ( 'share_name' , share_name )
_validate_not_none ( 'file_name' , file_name )
_validate_not_none ( 'file_path' , file_path )
_validate_not_none ( 'open_mode' , open_mode )
if max_connections > 1 and 'a' in open_mode :
raise ValueError ( _ERROR_PARALLEL_NOT_SEEKABLE )
with open ( file_path , open_m... |
def mixedToUnder ( s ) : # pragma : no cover
"""Sample :
> > > mixedToUnder ( " FooBarBaz " )
' foo _ bar _ baz '
Special case for ID :
> > > mixedToUnder ( " FooBarID " )
' foo _ bar _ id '""" | if s . endswith ( 'ID' ) :
return mixedToUnder ( s [ : - 2 ] + "_id" )
trans = _mixedToUnderRE . sub ( mixedToUnderSub , s )
if trans . startswith ( '_' ) :
trans = trans [ 1 : ]
return trans |
def find ( * _ , ** kwargs ) :
"""Find user by id / email""" | click . echo ( green ( '\nFind user:' ) )
click . echo ( green ( '-' * 40 ) )
with get_app ( ) . app_context ( ) :
user = find_user ( kwargs )
if not user :
click . echo ( red ( 'Not found\n' ) )
return
click . echo ( str ( user ) + '\n' )
return |
def reset_state ( self ) :
"""Resets some attributes to their default values .
This is especially useful when initializing a newly created
: class : ` SMTP ` instance and when closing an existing SMTP session .
It allows us to use the same SMTP instance and connect several times .""" | self . last_helo_response = ( None , None )
self . last_ehlo_response = ( None , None )
self . supports_esmtp = False
self . esmtp_extensions = { }
self . auth_mechanisms = [ ]
self . ssl_context = False
self . reader = None
self . writer = None
self . transport = None |
def trip ( self , origin_id , dest_id , date = None ) :
"""trip""" | date = date if date else datetime . now ( )
response = self . _request ( 'trip' , originId = origin_id , destId = dest_id , date = date . strftime ( DATE_FORMAT ) , time = date . strftime ( TIME_FORMAT ) )
return _get_node ( response , 'TripList' , 'Trip' ) |
def install_tab_event_filter ( self , value ) :
"""Install an event filter to capture mouse events in the tabs of a
QTabBar holding tabified dockwidgets .""" | dock_tabbar = None
tabbars = self . main . findChildren ( QTabBar )
for tabbar in tabbars :
for tab in range ( tabbar . count ( ) ) :
title = tabbar . tabText ( tab )
if title == self . title :
dock_tabbar = tabbar
break
if dock_tabbar is not None :
self . dock_tabbar = d... |
def set_selections ( path = None , selection = None , clear = False , saltenv = 'base' ) :
'''Change package state in the dpkg database .
The state can be any one of , documented in ` ` dpkg ( 1 ) ` ` :
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be he... | ret = { }
if not path and not selection :
return ret
if path and selection :
err = ( 'The \'selection\' and \'path\' arguments to ' 'pkg.set_selections are mutually exclusive, and cannot be ' 'specified together' )
raise SaltInvocationError ( err )
if isinstance ( selection , six . string_types ) :
try ... |
def mod_categorical_expval ( p ) :
"""Expected value of categorical distribution with parent p of length k - 1.
An implicit k ' th category is assumed to exist with associated
probability 1 - sum ( p ) .""" | p = extend_dirichlet ( p )
return np . sum ( [ p * i for i , p in enumerate ( p ) ] ) |
def load_key ( self , path ) :
"""Load key and secret from file .
: param path : path to file with first two lines are key , secret respectively""" | with open ( path , 'r' ) as f :
self . key = f . readline ( ) . strip ( )
self . secret = f . readline ( ) . strip ( ) |
def _extractErrorString ( request ) :
"""Extract error string from a failed UPnP call .
: param request : the failed request result
: type request : requests . Response
: return : an extracted error text or empty str
: rtype : str""" | errorStr = ""
tag = None
# noinspection PyBroadException
try : # parse XML return
root = ET . fromstring ( request . text . encode ( 'utf-8' ) )
tag = root [ 0 ] [ 0 ]
except : # return an empty string as we can not parse the structure
return errorStr
for element in tag . getiterator ( ) :
tagName = ele... |
def load_json ( filename , gzip_mode = False ) :
'''Return the json - file data , with all strings utf - 8 encoded .''' | open_file = open
if gzip_mode :
open_file = gzip . open
try :
with open_file ( filename , 'rt' ) as fh :
data = json . load ( fh )
data = convert_unicode_2_utf8 ( data )
return data
except AttributeError : # Python - 2.6
fh = open_file ( filename , 'rt' )
data = json . load ( fh ... |
def update_config ( self ) :
"""Creates or updates db config of the term . Requires bound to db tree .""" | dataset = self . _top . _config . dataset
session = object_session ( self . _top . _config )
# logger . debug ( ' Updating term config . dataset : { } , type : { } , key : { } , value : { } ' . format (
# dataset , self . _ top . _ type , self . _ key , self . get ( ) ) )
if not self . _parent . _config :
self . _p... |
def uniquify ( seq ) :
"""Return unique values in a list in the original order . See : http : / / www . peterbe . com / plog / uniqifiers - benchmark
Args :
seq ( list ) : original list .
Returns :
list : list without duplicates preserving original order .""" | seen = set ( )
seen_add = seen . add
return [ x for x in seq if x not in seen and not seen_add ( x ) ] |
def unpickle_docs ( self ) :
"""Sets the pointers for the docstrings that have groups .""" | for doc in self . docstring :
if ( doc . parent_name is not None and doc . parent_name in self . groups ) :
doc . group = self . groups [ doc . parent_name ] |
def nn ( self , x , k = 1 , radius = np . inf , eps = 0.0 , p = 2 ) :
"""Find the k nearest neighbors of x in the observed input data
: arg x : center
: arg k : the number of nearest neighbors to return ( default : 1)
: arg eps : approximate nearest neighbors .
the k - th returned value is guaranteed to be ... | assert len ( x ) == self . dim , 'dimension of input {} does not match expected dimension {}.' . format ( len ( x ) , self . dim )
k_x = min ( k , self . size )
# Because linear models requires x vector to be extended to [ 1.0 ] + x
# to accomodate a constant , we store them that way .
return self . _nn ( np . array ( ... |
def get_column_metadata ( conn , table : str , schema = 'public' ) :
"""Returns column data following db . Column parameter specification .""" | query = """\
SELECT
attname as name,
format_type(atttypid, atttypmod) AS data_type,
NOT attnotnull AS nullable
FROM pg_catalog.pg_attribute
WHERE attrelid=%s::regclass
AND attnum > 0 AND NOT attisdropped
ORDER BY attnum;"""
qualified_name = compile_qualified_name ( table , schema = schema )
for record in select... |
def cygpath ( path ) :
"""Use : meth : ` git . cmd . Git . polish _ url ( ) ` instead , that works on any environment .""" | if not path . startswith ( ( '/cygdrive' , '//' ) ) :
for regex , parser , recurse in _cygpath_parsers :
match = regex . match ( path )
if match :
path = parser ( * match . groups ( ) )
if recurse :
path = cygpath ( path )
break
else :
... |
def pull_folder ( self , path , decode = False ) :
"""Retrieves a folder at ` path ` . Returns the folder ' s contents zipped .
Android only .
- _ path _ - the path to the folder on the device
- _ decode _ - True / False decode the data ( base64 ) before returning it ( default = False )""" | driver = self . _current_application ( )
theFolder = driver . pull_folder ( path )
if decode :
theFolder = base64 . b64decode ( theFolder )
return theFolder |
def setdefault ( self , key , default = None ) :
"""Set ` default ` if the key is not in the cache otherwise
leave unchanged . Return the value of this key .""" | self . _wlock . acquire ( )
try :
try :
return self [ key ]
except KeyError :
self [ key ] = default
return default
finally :
self . _wlock . release ( ) |
def AND ( * args , ** kwargs ) :
"""ALL args must not raise an exception when called incrementally .
If an exception is specified , raise it , otherwise raise the callable ' s exception .
: params iterable [ Certifier ] args :
The certifiers to call
: param callable kwargs [ ' exc ' ] :
Callable that exce... | for arg in args :
try :
arg ( )
except CertifierError as e :
exc = kwargs . get ( 'exc' , None )
if exc is not None :
raise exc ( e )
raise |
def p_foreach_variable ( p ) :
'''foreach _ variable : VARIABLE
| AND VARIABLE''' | if len ( p ) == 2 :
p [ 0 ] = ast . ForeachVariable ( p [ 1 ] , False , lineno = p . lineno ( 1 ) )
else :
p [ 0 ] = ast . ForeachVariable ( p [ 2 ] , True , lineno = p . lineno ( 1 ) ) |
def from_array ( array ) :
"""Deserialize a new InvoiceMessage from a given dictionary .
: return : new InvoiceMessage instance .
: rtype : InvoiceMessage""" | if array is None or not array :
return None
# end if
assert_type_or_raise ( array , dict , parameter_name = "array" )
from pytgbot . api_types . sendable . payments import LabeledPrice
from pytgbot . api_types . sendable . reply_markup import InlineKeyboardMarkup
data = { }
data [ 'title' ] = u ( array . get ( 'tit... |
def cosi_pdf ( z , k = 1 ) :
"""Equation ( 11 ) of Morton & Winn ( 2014)""" | return 2 * k / ( np . pi * np . sinh ( k ) ) * quad ( cosi_integrand , z , 1 , args = ( k , z ) ) [ 0 ] |
def ddspmt ( t , peak_delay = 6 , under_delay = 16 , peak_disp = 1 , under_disp = 1 , p_u_ratio = 6 ) :
"""SPM canonical HRF dispersion derivative , values for time values ` t `
Parameters
t : array - like
vector of times at which to sample HRF
Returns
hrf : array
vector length ` ` len ( t ) ` ` of samp... | _spm_dd_func = partial ( spmt , peak_delay = peak_delay , under_delay = under_delay , under_disp = under_disp , p_u_ratio = p_u_ratio , peak_disp = 1.01 )
return ( spmt ( t ) - _spm_dd_func ( t ) ) / 0.01 |
def get_devices_by_parent ( self , hid_filter = None ) :
"""Group devices returned from filter query in order \
by devcice parent id .""" | all_devs = self . get_devices ( hid_filter )
dev_group = dict ( )
for hid_device in all_devs : # keep a list of known devices matching parent device Ids
parent_id = hid_device . get_parent_instance_id ( )
device_set = dev_group . get ( parent_id , [ ] )
device_set . append ( hid_device )
if parent_id no... |
def FromBinary ( cls , record_data , record_count = 1 ) :
"""Create an UpdateRecord subclass from binary record data .
This should be called with a binary record blob ( NOT including the
record type header ) and it will decode it into a ReflashTileRecord .
Args :
record _ data ( bytearray ) : The raw record... | if len ( record_data ) < ReflashTileRecord . RecordHeaderLength :
raise ArgumentError ( "Record was too short to contain a full reflash record header" , length = len ( record_data ) , header_length = ReflashTileRecord . RecordHeaderLength )
offset , data_length , raw_target , hardware_type = struct . unpack_from ( ... |
def format_datetime ( cls , timestamp ) :
"""Creates a string representing the date and time information provided by
the given ` timestamp ` object .""" | if not timestamp :
raise DateTimeFormatterException ( 'timestamp must a valid string {}' . format ( timestamp ) )
return timestamp . strftime ( cls . DATETIME_FORMAT ) |
def to_input_req ( self ) :
"""Converts the ` ` self ` ` instance to the desired input request format .
Returns :
dict : Containing the " WarmStartType " and " ParentHyperParameterTuningJobs " as the first class fields .
Examples :
> > > warm _ start _ config = WarmStartConfig ( warm _ start _ type = WarmSt... | return { WARM_START_TYPE : self . type . value , PARENT_HYPERPARAMETER_TUNING_JOBS : [ { HYPERPARAMETER_TUNING_JOB_NAME : parent } for parent in self . parents ] } |
def add ( self , origin , rel , target , attrs = None , rid = None ) :
'''Add one relationship to the extent
origin - origin of the relationship ( similar to an RDF subject )
rel - type IRI of the relationship ( similar to an RDF predicate )
target - target of the relationship ( similar to an RDF object ) , a... | # FIXME no it doesn ' t re :
# returns an ID ( IRI ) for the resulting relationship
cur = self . _conn . cursor ( )
# relationship .
if rid :
querystr = "INSERT INTO relationship (origin, rel, target, rid) VALUES (%s, %s, %s, %s) RETURNING rawid;"
cur . execute ( querystr , ( origin , rel , target , rid ) )
els... |
def _adjust_legend ( self , overlay , axis ) :
"""Accumulate the legend handles and labels for all subplots
and set up the legend""" | legend_data = [ ]
dimensions = overlay . kdims
title = ', ' . join ( [ d . name for d in dimensions ] )
for key , subplot in self . subplots . items ( ) :
element = overlay . data . get ( key , False )
if not subplot . show_legend or not element :
continue
title = ', ' . join ( [ d . name for d in d... |
def _ParseFilterOptions ( self , options ) :
"""Parses the filter options .
Args :
options ( argparse . Namespace ) : command line arguments .
Raises :
BadConfigOption : if the options are invalid .""" | names = [ 'artifact_filters' , 'date_filters' , 'filter_file' ]
helpers_manager . ArgumentHelperManager . ParseOptions ( options , self , names = names )
extensions_string = self . ParseStringOption ( options , 'extensions_string' )
self . _ParseExtensionsString ( extensions_string )
names_string = getattr ( options , ... |
def init_argparser_loaderplugin_registry ( self , argparser , default = None , help = ( 'the name of the registry to use for the handling of loader ' 'plugins that may be loaded from the given Python packages' ) ) :
"""Default helper for setting up the loaderplugin registries flags .
Note that this is NOT part of... | argparser . add_argument ( '--loaderplugin-registry' , default = default , dest = CALMJS_LOADERPLUGIN_REGISTRY_NAME , action = 'store' , metavar = metavar ( 'registry' ) , help = help , ) |
def resume_training ( self , sgd = None , ** cfg ) :
"""Continue training a pre - trained model .
Create and return an optimizer , and initialize " rehearsal " for any pipeline
component that has a . rehearse ( ) method . Rehearsal is used to prevent
models from " forgetting " their initialised " knowledge " ... | if cfg . get ( "device" , - 1 ) >= 0 :
util . use_gpu ( cfg [ "device" ] )
if self . vocab . vectors . data . shape [ 1 ] >= 1 :
self . vocab . vectors . data = Model . ops . asarray ( self . vocab . vectors . data )
link_vectors_to_models ( self . vocab )
if self . vocab . vectors . data . shape [ 1 ] ... |
def _check_special_kwargs ( self , name ) :
'''check special functions for kwargs
Checks the content of the special functions ( % methodname ) for
any keyword arguments referenced within
Parameters :
name ( str ) :
A path key name
Returns :
A list of keyword arguments found in any special functions''' | keys = [ ]
# find any % method names in the template string
functions = re . findall ( r"\%\w+" , self . templates [ name ] )
if not functions :
return keys
# loop over special method names and extract keywords
for function in functions :
method = getattr ( self , function [ 1 : ] )
# get source code of spe... |
def display ( self ) :
"Renders the scene once every refresh" | self . compositor . waitGetPoses ( self . poses , openvr . k_unMaxTrackedDeviceCount , None , 0 )
hmd_pose0 = self . poses [ openvr . k_unTrackedDeviceIndex_Hmd ]
if not hmd_pose0 . bPoseIsValid :
return
# hmd _ pose = hmd _ pose0 . mDeviceToAbsoluteTracking
# 1 ) On - screen render :
if True :
glClearColor ( 0... |
def context ( self ) :
"""Create an exectution context .
: rtype :
execution . Context
: return :
The created execution context .""" | return execution . Context ( self . __base_dir , self . __prof_dir , self . __prof_name ) |
def render ( self , at ) : # draw bg
surf = self . surf
surf . fill ( BASE3 )
bg = pygame . Surface ( ( self . size [ 0 ] , self . bar_height ) )
bg . fill ( BASE2 )
surf . blit ( bg , ( 0 , 0 ) )
# draw bar
ratio = self . gauge . get ( at ) / float ( self . gauge . max ( at ) )
if ratio... | return surf |
def installation_refused ( self , requirement , missing_dependencies , reason ) :
"""Raise : exc : ` . DependencyInstallationRefused ` with a user friendly message .
: param requirement : A : class : ` . Requirement ` object .
: param missing _ dependencies : A list of strings with missing dependencies .
: pa... | msg = "Missing %s (%s) required by Python package %s (%s) but %s!"
raise DependencyInstallationRefused ( msg % ( pluralize ( len ( missing_dependencies ) , "system package" , "system packages" ) , concatenate ( missing_dependencies ) , requirement . name , requirement . version , reason ) ) |
def _proxy ( self ) :
"""Generate an instance context for the instance , the context is capable of
performing various actions . All instance actions are proxied to the context
: returns : UserChannelContext for this UserChannelInstance
: rtype : twilio . rest . chat . v2 . service . user . user _ channel . Us... | if self . _context is None :
self . _context = UserChannelContext ( self . _version , service_sid = self . _solution [ 'service_sid' ] , user_sid = self . _solution [ 'user_sid' ] , channel_sid = self . _solution [ 'channel_sid' ] , )
return self . _context |
def _run_ensemble ( batch_id , vrn_files , config_file , base_dir , ref_file , data ) :
"""Run an ensemble call using merging and SVM - based approach in bcbio . variation""" | out_vcf_file = os . path . join ( base_dir , "{0}-ensemble.vcf" . format ( batch_id ) )
out_bed_file = os . path . join ( base_dir , "{0}-callregions.bed" . format ( batch_id ) )
work_dir = "%s-work" % os . path . splitext ( out_vcf_file ) [ 0 ]
if not utils . file_exists ( out_vcf_file ) :
_bcbio_variation_ensembl... |
def v_depth ( d , depth ) :
"""Iterate values on specific depth .
depth has to be greater equal than 0.
Usage reference see : meth : ` DictTree . kv _ depth ( ) < DictTree . kv _ depth > `""" | if depth == 0 :
yield d
else :
for node in DictTree . v ( d ) :
for node1 in DictTree . v_depth ( node , depth - 1 ) :
yield node1 |
def _append_slash_if_dir_path ( self , relpath ) :
"""For a dir path return a path that has a trailing slash .""" | if self . _isdir_raw ( relpath ) :
return self . _append_trailing_slash ( relpath )
return relpath |
def daemonize ( ** params ) :
"""This is a simple daemonization method . It just does a double fork ( ) and the
parent exits after closing a good clump of possibly open file descriptors . The
child redirects stdin from / dev / null and sets a new process group and session .
If you need fancier , suggest you l... | log = params . get ( 'log' )
redir = params . get ( 'redir' , True )
try :
if os . fork ( ) != 0 :
os . _exit ( 0 )
except Exception as e :
if log :
log ( "First fork failed -- %s" , e )
return False
try :
os . setsid ( )
except Exception as e :
if log :
log ( "Setsid() faile... |
def fisher_angular_deviation ( dec = None , inc = None , di_block = None , confidence = 95 ) :
'''The angle from the true mean within which a chosen percentage of directions
lie can be calculated from the Fisher distribution . This function uses the
calculated Fisher concentration parameter to estimate this ang... | if di_block is None :
di_block = make_di_block ( dec , inc )
mean = pmag . fisher_mean ( di_block )
else :
mean = pmag . fisher_mean ( di_block )
if confidence == 50 :
theta = old_div ( 67.5 , np . sqrt ( mean [ 'k' ] ) )
if confidence == 63 :
theta = old_div ( 81 , np . sqrt ( mean [ 'k' ] ) )
if c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.