signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def getBody ( self ) :
"""Extract body json""" | data = None
try :
data = json . loads ( self . request . body )
except :
data = json . loads ( urllib . unquote_plus ( self . request . body ) )
return data |
def get_reference_template ( self , ref_type ) :
"""Return the reference template for the type as an ordered dictionary .
Zotero . item _ template ( ) caches data after the first API call .""" | template = self . _zotero_lib . item_template ( ref_type )
return OrderedDict ( sorted ( template . items ( ) , key = lambda x : x [ 0 ] ) ) |
def power_on ( self ) :
"""Power on the set - top box .""" | if not self . is_powered_on ( ) :
log . debug ( 'Powering on set-top box at %s:%s.' , self . ip , self . port )
self . send_key ( keys . POWER ) |
def get_checked ( self ) :
"""Return the list of checked items that do not have any child .""" | checked = [ ]
def get_checked_children ( item ) :
if not self . tag_has ( "unchecked" , item ) :
ch = self . get_children ( item )
if not ch and self . tag_has ( "checked" , item ) :
checked . append ( item )
else :
for c in ch :
get_checked_children (... |
def get_all_tags ( self ) :
"""Return a tuple of lists ( [ common _ tags ] , [ anti _ tags ] , [ organisational _ tags ] ) all tags of all tasks of this course
Since this is an heavy procedure , we use a cache to cache results . Cache should be updated when a task is modified .""" | if self . _all_tags_cache != None :
return self . _all_tags_cache
tag_list_common = set ( )
tag_list_misconception = set ( )
tag_list_org = set ( )
tasks = self . get_tasks ( )
for id , task in tasks . items ( ) :
for tag in task . get_tags ( ) [ 0 ] :
tag_list_common . add ( tag )
for tag in task .... |
def find_file_structure ( self , body , params = None ) :
"""` < http : / / www . elastic . co / guide / en / elasticsearch / reference / current / ml - file - structure . html > ` _
: arg body : The contents of the file to be analyzed
: arg charset : Optional parameter to specify the character set of the
fil... | if body in SKIP_IN_PATH :
raise ValueError ( "Empty value passed for a required argument 'body'." )
return self . transport . perform_request ( "POST" , "/_ml/find_file_structure" , params = params , body = self . _bulk_body ( body ) , ) |
def WriteClientStartupInfo ( self , client_id , startup_info , cursor = None ) :
"""Writes a new client startup record .""" | query = """
SET @now = NOW(6);
INSERT INTO client_startup_history (client_id, timestamp, startup_info)
VALUES (%(client_id)s, @now, %(startup_info)s);
UPDATE clients
SET last_startup_timestamp = @now
WHERE client_id = %(client_id)s;
"""
params = { "client_id" : db_utils . ClientID... |
def _netstat_sunos ( ) :
'''Return netstat information for SunOS flavors''' | log . warning ( 'User and program not (yet) supported on SunOS' )
ret = [ ]
for addr_family in ( 'inet' , 'inet6' ) : # Lookup TCP connections
cmd = 'netstat -f {0} -P tcp -an | tail +5' . format ( addr_family )
out = __salt__ [ 'cmd.run' ] ( cmd , python_shell = True )
for line in out . splitlines ( ) :
... |
def Back ( self , n = 1 , dl = 0 ) :
"""退格键n次""" | self . Delay ( dl )
self . keyboard . tap_key ( self . keyboard . backspace_key , n ) |
def check_for_lime ( self , pattern ) :
"""Check to see if LiME has loaded on the remote system
: type pattern : str
: param pattern : pattern to check output against
: type listen _ port : int
: param listen _ port : port LiME is listening for connections on""" | check = self . commands . lime_check . value
lime_loaded = False
result = self . shell . execute ( check )
stdout = self . shell . decode ( result [ 'stdout' ] )
connections = self . net_parser . parse ( stdout )
for conn in connections :
local_addr , remote_addr = conn
if local_addr == pattern :
lime_l... |
def rebin_spec ( spec , wavnew , oversamp = 100 , plot = False ) :
"""Rebin a spectrum to a new wavelength array while preserving
the total flux
Parameters
spec : array - like
The wavelength and flux to be binned
wavenew : array - like
The new wavelength array
Returns
np . ndarray
The rebinned flu... | wave , flux = spec
nlam = len ( wave )
x0 = np . arange ( nlam , dtype = float )
x0int = np . arange ( ( nlam - 1. ) * oversamp + 1. , dtype = float ) / oversamp
w0int = np . interp ( x0int , x0 , wave )
spec0int = np . interp ( w0int , wave , flux ) / oversamp
# Set up the bin edges for down - binning
maxdiffw1 = np .... |
def ensure_local_files ( ) :
"""Ensure that filesystem is setup / filled out in a valid way""" | if _file_permissions :
if not os . path . isdir ( AUTH_DIR ) :
os . mkdir ( AUTH_DIR )
for fn in [ CONFIG_FILE ] :
contents = load_json_dict ( fn )
for key , val in list ( _FILE_CONTENT [ fn ] . items ( ) ) :
if key not in contents :
contents [ key ] = val
... |
def flatten ( source , task_limit = None ) :
"""Given an asynchronous sequence of sequences , generate the elements
of the sequences as soon as they ' re received .
The sequences are awaited concurrently , although it ' s possible to limit
the amount of running sequences using the ` task _ limit ` argument . ... | return base_combine . raw ( source , task_limit = task_limit , switch = False , ordered = False ) |
def _put_buffers ( state , buffer_paths , buffers ) :
"""The inverse of _ remove _ buffers , except here we modify the existing dict / lists .
Modifying should be fine , since this is used when state comes from the wire .""" | for buffer_path , buffer in zip ( buffer_paths , buffers ) : # we ' d like to set say sync _ data [ ' x ' ] [ 0 ] [ ' y ' ] = buffer
# where buffer _ path in this example would be [ ' x ' , 0 , ' y ' ]
obj = state
for key in buffer_path [ : - 1 ] :
obj = obj [ key ]
obj [ buffer_path [ - 1 ] ] = buf... |
def expose_event ( self , widget , event ) :
"""When an area of the window is exposed , we just copy out of the
server - side , off - screen surface to that area .""" | x , y , width , height = event . area
self . logger . debug ( "surface is %s" % self . surface )
if self . surface is not None :
win = widget . get_window ( )
cr = win . cairo_create ( )
# set clip area for exposed region
cr . rectangle ( x , y , width , height )
cr . clip ( )
# Paint from off -... |
def _start_http_session ( self ) :
"""Start a new requests HTTP session , clearing cookies and session data .
: return : None""" | api_logger . debug ( "Starting new HTTP session..." )
self . session = requests . Session ( )
self . session . headers . update ( { "User-Agent" : self . user_agent } )
if self . username and self . password :
api_logger . debug ( "Requests will use authorization." )
self . session . auth = HTTPBasicAuth ( self... |
def read_table_pattern ( self , header_pattern , row_pattern , footer_pattern , postprocess = str , attribute_name = None , last_one_only = True ) :
"""Parse table - like data . A table composes of three parts : header ,
main body , footer . All the data matches " row pattern " in the main body
will be returned... | with zopen ( self . filename , 'rt' ) as f :
text = f . read ( )
table_pattern_text = header_pattern + r"\s*^(?P<table_body>(?:\s+" + row_pattern + r")+)\s+" + footer_pattern
table_pattern = re . compile ( table_pattern_text , re . MULTILINE | re . DOTALL )
rp = re . compile ( row_pattern )
tables = [ ]
for mt in t... |
def show_namespace ( name , ** kwargs ) :
'''Return information for a given namespace defined by the specified name
CLI Examples : :
salt ' * ' kubernetes . show _ namespace kube - system''' | cfg = _setup_conn ( ** kwargs )
try :
api_instance = kubernetes . client . CoreV1Api ( )
api_response = api_instance . read_namespace ( name )
return api_response . to_dict ( )
except ( ApiException , HTTPError ) as exc :
if isinstance ( exc , ApiException ) and exc . status == 404 :
return None... |
def set_work_request ( self , worker_name , sample_set , subkeys = None ) :
"""Make a work request for an existing stored sample ( or sample _ set ) .
Args :
worker _ name : ' strings ' , ' pe _ features ' , whatever
sample _ set : the md5 of a sample _ set in the Workbench data store
subkeys : just get a s... | # Does worker support sample _ set _ input ?
if self . plugin_meta [ worker_name ] [ 'sample_set_input' ] :
yield self . work_request ( worker_name , sample_set , subkeys )
# Loop through all the md5s and return a generator with yield
else :
md5_list = self . get_sample_set ( sample_set )
for md5 in md5_lis... |
def fatal ( ftn , txt ) :
"""If can ' t continue .""" | msg = "{0}.{1}:FATAL:{2}\n" . format ( modname , ftn , txt )
raise SystemExit ( msg ) |
def setmonitor ( self , enable = True ) :
"""Alias for setmode ( ' monitor ' ) or setmode ( ' managed ' )
Only available with Npcap""" | # We must reset the monitor cache
if enable :
res = self . setmode ( 'monitor' )
else :
res = self . setmode ( 'managed' )
if not res :
log_runtime . error ( "Npcap WlanHelper returned with an error code !" )
self . cache_mode = None
tmp = self . cache_mode = self . ismonitor ( )
return tmp if enable else (... |
def attack_class ( self , x , target_y ) :
"""Run the attack on a specific target class .
: param x : tf Tensor . The input example .
: param target _ y : tf Tensor . The attacker ' s desired target class .
Returns :
A targeted adversarial example , intended to be classified as the target class .""" | adv = self . base_attacker . generate ( x , y_target = target_y , ** self . params )
return adv |
def export_profile ( self ) :
"""Export minimum needs to a json file .
This method will save the current state of the minimum needs setup .
Then open a dialog allowing the user to browse to the desired
destination location and allow the user to save the needs as a json
file .""" | file_name_dialog = QFileDialog ( self )
file_name_dialog . setAcceptMode ( QFileDialog . AcceptSave )
file_name_dialog . setNameFilter ( self . tr ( 'JSON files (*.json *.JSON)' ) )
file_name_dialog . setDefaultSuffix ( 'json' )
file_name = None
if file_name_dialog . exec_ ( ) :
file_name = file_name_dialog . selec... |
def console_set_default_background ( con : tcod . console . Console , col : Tuple [ int , int , int ] ) -> None :
"""Change the default background color for a console .
Args :
con ( Console ) : Any Console instance .
col ( Union [ Tuple [ int , int , int ] , Sequence [ int ] ] ) :
An ( r , g , b ) sequence ... | lib . TCOD_console_set_default_background ( _console ( con ) , col ) |
def debug ( self , key ) :
"""Returns True if the debug setting is enabled .""" | return ( not self . quiet and not self . debug_none and ( self . debug_all or getattr ( self , "debug_%s" % key ) ) ) |
def move_to_pat ( pat : str , offset : ( float , float ) = None , tolerance : int = 0 ) -> None :
"""See help for click _ on _ pat""" | with tempfile . NamedTemporaryFile ( ) as f :
subprocess . call ( '''
xwd -root -silent -display :0 |
convert xwd:- png:''' + f . name , shell = True )
loc = visgrep ( f . name , pat , tolerance )
pat_size = get_png_dim ( pat )
if offset is None :
x , y = [ l + ps // 2 for l , ps in zip ( l... |
def replace ( self , s , data , attrs = None ) :
"""Replace the attributes of the plotter data in a string
% ( replace _ note ) s
Parameters
s : str
String where the replacements shall be made
data : InteractiveBase
Data object from which to use the coordinates and insert the
coordinate and attribute ... | # insert labels
s = s . format ( ** self . rc [ 'labels' ] )
# replace attributes
attrs = attrs or data . attrs
if hasattr ( getattr ( data , 'psy' , None ) , 'arr_name' ) :
attrs = attrs . copy ( )
attrs [ 'arr_name' ] = data . psy . arr_name
s = safe_modulo ( s , attrs )
# replace datetime . datetime like tim... |
def task_ref_role ( name , rawtext , text , lineno , inliner , options = None , content = None ) :
"""Process a role that references the target nodes created by the
` ` lsst - task ` ` directive .
Parameters
name
The role name used in the document .
rawtext
The entire markup snippet , with role .
text... | # app = inliner . document . settings . env . app
node = pending_task_xref ( rawsource = text )
return [ node ] , [ ] |
def update_req ( req ) :
"""Updates a given req object with the latest version .""" | if not req . name :
return req , None
info = get_package_info ( req . name )
if info [ 'info' ] . get ( '_pypi_hidden' ) :
print ( '{} is hidden on PyPI and will not be updated.' . format ( req ) )
return req , None
if _is_pinned ( req ) and _is_version_range ( req ) :
print ( '{} is pinned to a range a... |
def default_display ( value , with_module = True ) :
"""Default display for unknown objects .""" | object_type = type ( value )
try :
name = object_type . __name__
module = object_type . __module__
if with_module :
return name + ' object of ' + module + ' module'
else :
return name
except :
type_str = to_text_string ( object_type )
return type_str [ 1 : - 1 ] |
def list_env ( self , saltenv = 'base' ) :
'''Return a list of the files in the file server ' s specified environment''' | load = { 'saltenv' : saltenv , 'cmd' : '_file_list' }
return salt . utils . data . decode ( self . channel . send ( load ) ) if six . PY2 else self . channel . send ( load ) |
def convert ( args ) :
"""% prog convert in . fastq
illumina fastq quality encoding uses offset 64 , and sanger uses 33 . This
script creates a new file with the correct encoding . Output gzipped file if
input is also gzipped .""" | p = OptionParser ( convert . __doc__ )
p . set_phred ( )
opts , args = p . parse_args ( args )
if len ( args ) != 1 :
sys . exit ( not p . print_help ( ) )
infastq , = args
phred = opts . phred or str ( guessoffset ( [ infastq ] ) )
ophred = { "64" : "33" , "33" : "64" } [ phred ]
gz = infastq . endswith ( ".gz" )
... |
def info_dialog ( self , title = "Information" , message = "" , ** kwargs ) :
"""Show an information dialog
Usage : C { dialog . info _ dialog ( title = " Information " , message = " " , * * kwargs ) }
@ param title : window title for the dialog
@ param message : message displayed in the dialog
@ return : a... | return self . _run_kdialog ( title , [ "--msgbox" , message ] , kwargs ) |
def snap_picture ( self ) :
"""Take a picture with camera to create a new thumbnail .""" | return api . request_new_image ( self . sync . blink , self . network_id , self . camera_id ) |
def enter_unlink_mode ( self ) :
"""Enter unlinking mode for a group""" | self . logger . info ( "enter_unlink_mode Group %s" , self . group_id )
self . scene_command ( '0A' )
# should send http : / / 0.0.0.0/0?0A01 = I = 0
# # TODO check return status
status = self . hub . get_buffer_status ( )
return status |
def insert ( self , row ) :
"""Add a row ( type : dict ) by inserting it into the table .
Columns must exist .
data = dict ( title = ' I am a banana ! ' )
table . insert ( data )
Returns the inserted row ' s primary key .""" | self . _check_dropped ( )
res = self . engine . execute ( self . table . insert ( row ) )
if len ( res . inserted_primary_key ) > 0 :
return res . inserted_primary_key [ 0 ] |
def ack ( self ) :
"""Acknowledge Message .
: raises AMQPInvalidArgument : Invalid Parameters
: raises AMQPChannelError : Raises if the channel encountered an error .
: raises AMQPConnectionError : Raises if the connection
encountered an error .
: return :""" | if not self . _method :
raise AMQPMessageError ( 'Message.ack only available on incoming messages' )
self . _channel . basic . ack ( delivery_tag = self . delivery_tag ) |
def read_value ( self , key , filepath = None , filename = None ) :
"""Tries to read the value of given key from JSON file filename .
: param filepath : Path to file
: param filename : Name of file
: param key : Key to search for
: return : Value corresponding to given key
: raises OSError , EnvironmentEr... | path = filepath if filepath else self . filepath
name = filename if filename else self . filename
name = self . _ends_with ( name , ".json" )
path = self . _ends_with ( path , os . path . sep )
try :
output = self . _read_json ( path , name )
if key not in output :
raise KeyError ( "Key '{}' not found i... |
def standardized_compound ( self ) :
"""Return the : class : ` ~ pubchempy . Compound ` that was produced when this Substance was standardized .
Requires an extra request . Result is cached .""" | for c in self . record [ 'compound' ] :
if c [ 'id' ] [ 'type' ] == CompoundIdType . STANDARDIZED :
return Compound . from_cid ( c [ 'id' ] [ 'id' ] [ 'cid' ] ) |
def addPos ( self , dp_x = None , dy = None , dz = None ) :
"""Add vector to current actor position .""" | p = np . array ( self . GetPosition ( ) )
if dz is None : # assume dp _ x is of the form ( x , y , z )
self . SetPosition ( p + dp_x )
else :
self . SetPosition ( p + [ dp_x , dy , dz ] )
if self . trail :
self . updateTrail ( )
return self |
def _save_namepaths_bids_derivatives ( self , f , tag , save_directory , suffix = None ) :
"""Creates output directory and output name
Paramters
f : str
input files , includes the file bids _ suffix
tag : str
what should be added to f in the output file .
save _ directory : str
additional directory th... | file_name = f . split ( '/' ) [ - 1 ] . split ( '.' ) [ 0 ]
if tag != '' :
tag = '_' + tag
if suffix :
file_name , _ = drop_bids_suffix ( file_name )
save_name = file_name + tag
save_name += '_' + suffix
else :
save_name = file_name + tag
paths_post_pipeline = f . split ( self . pipeline )
if self .... |
def get_default_config ( self ) :
"""Returns the default collector settings""" | config = super ( VarnishCollector , self ) . get_default_config ( )
config . update ( { 'path' : 'varnish' , 'bin' : '/usr/bin/varnishstat' , 'use_sudo' : False , 'sudo_cmd' : '/usr/bin/sudo' , } )
return config |
def structure_results ( res ) :
"""Format Elasticsearch result as Python dictionary""" | out = { 'hits' : { 'hits' : [ ] } }
keys = [ u'admin1_code' , u'admin2_code' , u'admin3_code' , u'admin4_code' , u'alternativenames' , u'asciiname' , u'cc2' , u'coordinates' , u'country_code2' , u'country_code3' , u'dem' , u'elevation' , u'feature_class' , u'feature_code' , u'geonameid' , u'modification_date' , u'name'... |
def drop_callback_reference ( self , subscription ) :
"""Drop reference to the callback function after unsubscribing .
Any future messages arriving for that subscription will result in
exceptions being raised .
: param subscription : Subscription ID to delete callback reference for .""" | if subscription not in self . __subscriptions :
raise workflows . Error ( "Attempting to drop callback reference for unknown subscription" )
if not self . __subscriptions [ subscription ] [ "unsubscribed" ] :
raise workflows . Error ( "Attempting to drop callback reference for live subscription" )
del self . __... |
def download_next_song ( self , song ) :
"""Downloads the next song and starts playing it""" | dl_ydl_opts = dict ( ydl_opts )
dl_ydl_opts [ "progress_hooks" ] = [ self . ytdl_progress_hook ]
dl_ydl_opts [ "outtmpl" ] = self . output_format
# Move the songs from the next cache to the current cache
self . move_next_cache ( )
self . state = 'ready'
self . play_empty ( )
# Download the file and create the stream
wi... |
def item_frequency ( sa , xlabel = LABEL_DEFAULT , ylabel = LABEL_DEFAULT , title = LABEL_DEFAULT ) :
"""Plots an item frequency of the sarray provided as input , and returns the
resulting Plot object .
The function supports SArrays with dtype str .
Parameters
sa : SArray
The data to get an item frequency... | if ( not isinstance ( sa , tc . data_structures . sarray . SArray ) or sa . dtype != str ) :
raise ValueError ( "turicreate.visualization.item_frequency supports " + "SArrays of dtype str" )
title = _get_title ( title )
plt_ref = tc . extensions . plot_item_frequency ( sa , xlabel , ylabel , title )
return Plot ( p... |
def open_remote_file ( dataset_key , file_name , profile = 'default' , mode = 'w' , ** kwargs ) :
"""Open a remote file object that can be used to write to or read from
a file in a data . world dataset
: param dataset _ key : Dataset identifier , in the form of owner / id
: type dataset _ key : str
: param ... | return _get_instance ( profile , ** kwargs ) . open_remote_file ( dataset_key , file_name , mode = mode , ** kwargs ) |
def _create_trial_info ( self , expr_dir ) :
"""Create information for given trial .
Meta file will be loaded if exists , and the trial information
will be saved in db backend .
Args :
expr _ dir ( str ) : Directory path of the experiment .""" | meta = self . _build_trial_meta ( expr_dir )
self . logger . debug ( "Create trial for %s" % meta )
trial_record = TrialRecord . from_json ( meta )
trial_record . save ( ) |
def _new ( self , dx_hash , close = False , ** kwargs ) :
""": param dx _ hash : Standard hash populated in : func : ` dxpy . bindings . DXDataObject . new ( ) ` containing attributes common to all data object classes .
: type dx _ hash : dict
: param init _ from : Record from which to initialize the metadata
... | if "init_from" in kwargs :
if kwargs [ "init_from" ] is not None :
if not isinstance ( kwargs [ "init_from" ] , DXRecord ) :
raise DXError ( "Expected instance of DXRecord to init_from" )
dx_hash [ "initializeFrom" ] = { "id" : kwargs [ "init_from" ] . get_id ( ) , "project" : kwargs [ "... |
def guess_value ( text_value ) : # type : ( str ) - > str
"""Get string value for common strings .
Method is far from complete but helping with odd arxml files .
: param text _ value : value in text like " true "
: return : string for value like " 1" """ | if sys . version_info >= ( 3 , 0 ) :
text_value = text_value . casefold ( )
else :
text_value = text_value . lower ( )
if text_value in [ "false" , "off" ] :
return "0"
elif text_value in [ "true" , "on" ] :
return "1"
return text_value |
def get_member_class ( resource ) :
"""Returns the registered member class for the given resource .
: param resource : registered resource
: type resource : class implementing or instance providing or subclass of
a registered resource interface .""" | reg = get_current_registry ( )
if IInterface in provided_by ( resource ) :
member_class = reg . getUtility ( resource , name = 'member-class' )
else :
member_class = reg . getAdapter ( resource , IMemberResource , name = 'member-class' )
return member_class |
def save_hdf ( self , filename , path = '' , overwrite = False , append = False ) :
"""Saves object data to HDF file ( only works if MCMC is run )
Samples are saved to / samples location under given path ,
: class : ` ObservationTree ` is saved to / obs location under given path .
: param filename :
Name of... | if os . path . exists ( filename ) :
with pd . HDFStore ( filename ) as store :
if path in store :
if overwrite :
os . remove ( filename )
elif not append :
raise IOError ( '{} in {} exists. Set either overwrite or append option.' . format ( path , fi... |
async def _string_data ( self , data ) :
"""This is a private message handler method .
It is the message handler for String data messages that will be
printed to the console .
: param data : message
: returns : None - message is sent to console""" | reply = ''
data = data [ 1 : - 1 ]
for x in data :
reply_data = x
if reply_data :
reply += chr ( reply_data )
if self . log_output :
logging . info ( reply )
else :
print ( reply ) |
async def delCronJob ( self , iden ) :
'''Delete a cron job
Args :
iden ( bytes ) : The iden of the cron job to be deleted''' | cron = self . cell . agenda . appts . get ( iden )
if cron is None :
raise s_exc . NoSuchIden ( )
self . _trig_auth_check ( cron . useriden )
await self . cell . agenda . delete ( iden ) |
def rule_from_pattern ( pattern , base_path = None , source = None ) :
"""Take a . gitignore match pattern , such as " * . py [ cod ] " or " * * / * . bak " ,
and return an IgnoreRule suitable for matching against files and
directories . Patterns which do not match files , such as comments
and blank lines , w... | if base_path and base_path != abspath ( base_path ) :
raise ValueError ( 'base_path must be absolute' )
# Store the exact pattern for our repr and string functions
orig_pattern = pattern
# Early returns follow
# Discard comments and seperators
if pattern . strip ( ) == '' or pattern [ 0 ] == '#' :
return
# Disc... |
def interrogate ( self , platformIdentifier , configuration , libraries , libOverrides = { } ) :
"""Interrogates UnrealBuildTool about the build flags for the specified third - party libraries""" | # Determine which libraries need their modules parsed by UBT , and which are override - only
libModules = list ( [ lib for lib in libraries if lib not in libOverrides ] )
# Check that we have at least one module to parse
details = ThirdPartyLibraryDetails ( )
if len ( libModules ) > 0 : # Retrieve the list of third - p... |
def get_resources ( self ) :
"""Gets a JSON mapping of server - side resource names to paths
: rtype dict""" | status , _ , body = self . _request ( 'GET' , '/' , { 'Accept' : 'application/json' } )
if status == 200 :
tmp , resources = json . loads ( bytes_to_str ( body ) ) , { }
for k in tmp : # The keys and values returned by json . loads ( ) are unicode ,
# which will cause problems when passed into httplib later... |
def _read_preference_for ( self , session ) :
"""Read only access to the read preference of this instance or session .""" | # Override this operation ' s read preference with the transaction ' s .
if session :
return session . _txn_read_preference ( ) or self . __read_preference
return self . __read_preference |
def from_archive ( archive_filename , py_interpreter = sys . executable ) :
"""extract metadata from a given sdist archive file
: param archive _ filename : a sdist archive file
: param py _ interpreter : The full path to the used python interpreter
: returns : a json blob with metadata""" | with _extract_to_tempdir ( archive_filename ) as root_dir :
data = _setup_py_run_from_dir ( root_dir , py_interpreter )
return data |
def get_clients_groups ( self ) -> typing . Iterator [ 'Group' ] :
"""Gets all clients groups
Returns : generator of Groups""" | for group in self . groups :
if group . group_is_client_group :
yield group |
def iso_mesh_line ( vertices , tris , vertex_data , levels ) :
"""Generate an isocurve from vertex data in a surface mesh .
Parameters
vertices : ndarray , shape ( Nv , 3)
Vertex coordinates .
tris : ndarray , shape ( Nf , 3)
Indices of triangular element into the vertices array .
vertex _ data : ndarra... | lines = None
connects = None
vertex_level = None
level_index = None
if not all ( [ isinstance ( x , np . ndarray ) for x in ( vertices , tris , vertex_data , levels ) ] ) :
raise ValueError ( 'all inputs must be numpy arrays' )
if vertices . shape [ 1 ] <= 3 :
verts = vertices
elif vertices . shape [ 1 ] == 4 :... |
def send_cmd_recv_rsp ( self , cmd_code , cmd_data , timeout , send_idm = True , check_status = True ) :
"""Send a command and receive a response .
This low level method sends an arbitrary command with the
8 - bit integer * cmd _ code * , followed by the captured tag
identifier ( IDm ) if * send _ idm * is : ... | idm = self . idm if send_idm else bytearray ( )
cmd = chr ( 2 + len ( idm ) + len ( cmd_data ) ) + chr ( cmd_code ) + idm + cmd_data
log . debug ( ">> {0:02x} {1:02x} {2} {3} ({4}s)" . format ( cmd [ 0 ] , cmd [ 1 ] , hexlify ( cmd [ 2 : 10 ] ) , hexlify ( cmd [ 10 : ] ) , timeout ) )
started = time . time ( )
for retr... |
def create_new_csv ( samples , args ) :
"""create csv file that can be use with bcbio - w template""" | out_fn = os . path . splitext ( args . csv ) [ 0 ] + "-merged.csv"
logger . info ( "Preparing new csv: %s" % out_fn )
with file_transaction ( out_fn ) as tx_out :
with open ( tx_out , 'w' ) as handle :
handle . write ( _header ( args . csv ) )
for s in samples :
sample_name = s [ 'name' ... |
def size ( self ) :
"""Returns the size of the cache in bytes .""" | total_size = 0
for dir_path , dir_names , filenames in os . walk ( self . dir ) :
for f in filenames :
fp = os . path . join ( dir_path , f )
total_size += os . path . getsize ( fp )
return total_size |
def remove_unsupported_kwargs ( module_or_fn , all_kwargs_dict ) :
"""Removes any kwargs not supported by ` module _ or _ fn ` from ` all _ kwargs _ dict ` .
A new dict is return with shallow copies of keys & values from
` all _ kwargs _ dict ` , as long as the key is accepted by module _ or _ fn . The
return... | if all_kwargs_dict is None :
all_kwargs_dict = { }
if not isinstance ( all_kwargs_dict , dict ) :
raise ValueError ( "all_kwargs_dict must be a dict with string keys." )
return { kwarg : value for kwarg , value in all_kwargs_dict . items ( ) if supports_kwargs ( module_or_fn , kwarg ) != NOT_SUPPORTED } |
def all_schema_names ( self , cache = False , cache_timeout = None , force = False ) :
"""Parameters need to be passed as keyword arguments .
For unused parameters , they are referenced in
cache _ util . memoized _ func decorator .
: param cache : whether cache is enabled for the function
: type cache : boo... | return self . db_engine_spec . get_schema_names ( self . inspector ) |
def mx_page_trees ( self , mx_page ) :
"""return trees assigned to given MX Page""" | resp = dict ( )
for tree_name , tree in self . scheduler . timetable . trees . items ( ) :
if tree . mx_page == mx_page :
rest_tree = self . _get_tree_details ( tree_name )
resp [ tree . tree_name ] = rest_tree . document
return resp |
def _capture_original_object ( self ) :
"""Capture the original python object .""" | try :
self . _doubles_target = getattr ( self . target , self . _name )
except AttributeError :
raise VerifyingDoubleError ( self . target , self . _name ) |
def file_hash ( path , hash_type = "md5" , block_size = 65536 , hex_digest = True ) :
"""Hash a given file with md5 , or any other and return the hex digest . You
can run ` hashlib . algorithms _ available ` to see which are available on your
system unless you have an archaic python version , you poor soul ) . ... | hashed = hashlib . new ( hash_type )
with open ( path , "rb" ) as infile :
buf = infile . read ( block_size )
while len ( buf ) > 0 :
hashed . update ( buf )
buf = infile . read ( block_size )
return hashed . hexdigest ( ) if hex_digest else hashed . digest ( ) |
def _ttr ( self , k , dist , cache ) :
"""Three terms recursion coefficients .""" | a , b = evaluation . evaluate_recurrence_coefficients ( dist , k )
return - a , b |
def fetch ( bank , key , cachedir ) :
'''Fetch information from a file .''' | inkey = False
key_file = os . path . join ( cachedir , os . path . normpath ( bank ) , '{0}.p' . format ( key ) )
if not os . path . isfile ( key_file ) : # The bank includes the full filename , and the key is inside the file
key_file = os . path . join ( cachedir , os . path . normpath ( bank ) + '.p' )
inkey ... |
async def addNodes ( self , nodedefs ) :
'''Add / merge nodes in bulk .
The addNodes API is designed for bulk adds which will
also set properties and add tags to existing nodes .
Nodes are specified as a list of the following tuples :
( ( form , valu ) , { ' props ' : { } , ' tags ' : { } } )
Args :
nod... | for ( formname , formvalu ) , forminfo in nodedefs :
props = forminfo . get ( 'props' )
# remove any universal created props . . .
if props is not None :
props . pop ( '.created' , None )
node = await self . addNode ( formname , formvalu , props = props )
if node is not None :
tags =... |
def build ( self , builder ) :
"""Build XML by appending to builder""" | params = dict ( Value = self . value , Status = self . status . value , ProtocolDeviationRepeatKey = self . repeat_key )
if self . code :
params [ 'Code' ] = self . code
if self . pdclass :
params [ 'Class' ] = self . pdclass
if self . transaction_type :
params [ 'TransactionType' ] = self . transaction_typ... |
def _merge_args ( qCmd , parsed_args , _extra_values , value_specs ) :
"""Merge arguments from _ extra _ values into parsed _ args .
If an argument value are provided in both and it is a list ,
the values in _ extra _ values will be merged into parsed _ args .
@ param parsed _ args : the parsed args from know... | temp_values = _extra_values . copy ( )
for key , value in six . iteritems ( temp_values ) :
if hasattr ( parsed_args , key ) :
arg_value = getattr ( parsed_args , key )
if arg_value is not None and value is not None :
if isinstance ( arg_value , list ) :
if value and isin... |
def _resample_data ( self , gssha_var ) :
"""This function resamples the data to match the GSSHA grid
IN TESTING MODE""" | self . data = self . data . lsm . resample ( gssha_var , self . gssha_grid ) |
def not_empty ( message = None ) -> Filter_T :
"""Validate any object to ensure it ' s not empty ( is None or has no elements ) .""" | def validate ( value ) :
if value is None :
_raise_failure ( message )
if hasattr ( value , '__len__' ) and value . __len__ ( ) == 0 :
_raise_failure ( message )
return value
return validate |
def findCycle ( self , cycNum ) :
'''Method that looks through the self . cycles and returns the
nearest cycle :
Parameters
cycNum : int
int of the cycle desired cycle .''' | cycNum = int ( cycNum )
i = 0
while i < len ( self . cycles ) :
if cycNum < int ( self . cycles [ i ] ) :
break
i += 1
if i == 0 :
return self . cycles [ i ]
elif i == len ( self . cycles ) :
return self . cycles [ i - 1 ]
lower = int ( self . cycles [ i - 1 ] )
higher = int ( self . cycles [ i ... |
def added ( self , context ) :
"""Ingredient method called before anything else .
Here this method just builds the full command tree and stores it inside
the context as the ` ` cmd _ tree ` ` attribute . The structure of the tree is
explained by the : func : ` build _ cmd _ tree ( ) ` function .""" | context . cmd_tree = self . _build_cmd_tree ( self . command )
context . cmd_toplevel = context . cmd_tree . cmd_obj
# Collect spices from the top - level command
for spice in context . cmd_toplevel . get_cmd_spices ( ) :
context . bowl . add_spice ( spice ) |
def connect ( self , host = 'localhost' ) :
"""Connect to the server and set everything up .
Args :
host : hostname to connect to""" | # Connect
get_logger ( ) . info ( "Connecting to RabbitMQ server..." )
self . _conn = pika . BlockingConnection ( pika . ConnectionParameters ( host = host ) )
self . _channel = self . _conn . channel ( )
# Exchanger
get_logger ( ) . info ( "Declaring topic exchanger {}..." . format ( self . exchange ) )
self . _channe... |
def get ( self , key : str , default = None , as_type : type = None , binary_file = False ) :
"""Get a setting specified by key ` ` key ` ` . Normally , settings are strings , but
if you put non - strings into the settings object , you can request unserialization
by specifying ` ` as _ type ` ` . If the key doe... | if as_type is None and key in self . _h . defaults :
as_type = self . _h . defaults [ key ] . type
if key in self . _cache ( ) :
value = self . _cache ( ) [ key ]
else :
value = None
if self . _parent :
value = getattr ( self . _parent , self . _h . attribute_name ) . get ( key , as_type = str )... |
def connect ( self , uri , link_quality_callback , link_error_callback ) :
"""Connect the link driver to a specified URI of the format :
radio : / / < dongle nbr > / < radio channel > / [ 250K , 1M , 2M ]
The callback for linkQuality can be called at any moment from the
driver to report back the link quality ... | # check if the URI is a radio URI
if not re . search ( '^radio://' , uri ) :
raise WrongUriType ( 'Not a radio URI' )
# Open the USB dongle
if not re . search ( '^radio://([0-9a-fA-F]+)((/([0-9]+))' '((/(250K|1M|2M))?(/([A-F0-9]+))?)?)?$' , uri ) :
raise WrongUriType ( 'Wrong radio URI format!' )
uri_data = re ... |
def seen ( self , event , nickname ) :
"""Shows the amount of time since the given nickname was last
seen in the channel .""" | try :
self . joined [ nickname ]
except KeyError :
pass
else :
if nickname == self . get_nickname ( event ) :
prefix = "you are"
else :
prefix = "%s is" % nickname
return "%s here right now" % prefix
try :
seen = self . timesince ( self . quit [ nickname ] )
except KeyError :
... |
def parse ( cls , request , default_start = 0 , default_end = 9 , max_end = 50 ) :
'''Parse the range headers into a range object . When there are no range headers ,
check for a page ' pagina ' parameter , otherwise use the defaults defaults
: param request : a request object
: param default _ start : default... | settings = request . registry . settings
page_param = settings . get ( 'oe.paging.page.queryparam' , 'pagina' )
if 'Range' in request . headers and request . headers [ 'Range' ] is not '' :
match = re . match ( '^items=([0-9]+)-([0-9]+)$' , request . headers [ 'Range' ] )
if match :
start = int ( match ... |
def logplr ( self ) :
"""Returns the log of the prior - weighted likelihood ratio at the
current parameter values .
The logprior is calculated first . If the logprior returns ` ` - inf ` `
( possibly indicating a non - physical point ) , then ` ` loglr ` ` is not
called .""" | logp = self . logprior
if logp == - numpy . inf :
return logp
else :
return logp + self . loglr |
def get_eidos_bayesian_scorer ( prior_counts = None ) :
"""Return a BayesianScorer based on Eidos curation counts .""" | table = load_eidos_curation_table ( )
subtype_counts = { 'eidos' : { r : [ c , i ] for r , c , i in zip ( table [ 'RULE' ] , table [ 'Num correct' ] , table [ 'Num incorrect' ] ) } }
prior_counts = prior_counts if prior_counts else copy . deepcopy ( default_priors )
scorer = BayesianScorer ( prior_counts = prior_counts... |
def ensure_dir ( path , parents = False ) :
"""Returns a boolean indicating whether the directory already existed . Will
attempt to create parent directories if * parents * is True .""" | if parents :
from os . path import dirname
parent = dirname ( path )
if len ( parent ) and parent != path :
ensure_dir ( parent , True )
try :
os . mkdir ( path )
except OSError as e :
if e . errno == 17 : # EEXIST
return True
raise
return False |
def skip_if ( self , condition : bool , default : Any = None ) -> 'Question' :
"""Skip the question if flag is set and return the default instead .""" | self . should_skip_question = condition
self . default = default
return self |
def main ( ) :
"""NAME
scalc _ magic . py
DESCRIPTION
calculates Sb from pmag _ results files
SYNTAX
scalc _ magic - h [ command line options ]
INPUT
takes magic formatted pmag _ results ( 2.5 ) or sites ( 3.0 ) table
pmag _ result _ name ( 2.5 ) must start with " VGP : Site "
must have average _ ... | coord , kappa , cutoff , n = 0 , 0 , 180. , 0
nb , anti , spin , v , boot = 1000 , 0 , 0 , 0 , 0
data_model = 3
rev = 0
if '-dm' in sys . argv :
ind = sys . argv . index ( "-dm" )
data_model = int ( sys . argv [ ind + 1 ] )
if data_model == 2 :
coord_key = 'tilt_correction'
in_file = 'pmag_results.txt'
... |
def batlab2sparkle ( experiment_data ) :
"""Sparkle expects meta data to have a certain heirarchial organization ,
reformat batlab experiment data to fit .""" | # This is mostly for convention . . attribute that matters most is samplerate ,
# since it is used in the GUI to calculate things like duration
nsdata = { }
for attr in [ 'computername' , 'pst_filename' , 'title' , 'who' , 'date' , 'program_date' ] :
nsdata [ attr ] = experiment_data [ attr ]
for itest , test in en... |
def is_first ( self , value ) :
"""The is _ first property .
Args :
value ( string ) . the property value .""" | if value == self . _defaults [ 'ai.session.isFirst' ] and 'ai.session.isFirst' in self . _values :
del self . _values [ 'ai.session.isFirst' ]
else :
self . _values [ 'ai.session.isFirst' ] = value |
def getURL ( self , CorpNum , UserID , ToGo ) :
""": param CorpNum : 팝빌회원 사업자번호
: param UserID : 팝빌회원 아이디
: param ToGo : [ PLUSFRIEND - 플러스친구계정관리 , SENDER - 발신번호관리 , TEMPLATE - 알림톡템플릿관리 , BOX - 카카오톡전송내용 ]
: return : 팝빌 URL""" | if ToGo == None or ToGo == '' :
raise PopbillException ( - 99999999 , "TOGO값이 입력되지 않았습니다." )
if ToGo == 'SENDER' :
result = self . _httpget ( '/Message/?TG=' + ToGo , CorpNum , UserID )
else :
result = self . _httpget ( '/KakaoTalk/?TG=' + ToGo , CorpNum , UserID )
return result . url |
def discretize ( value , factor = 100 ) :
"""Discretize the given value , pre - multiplying by the given factor""" | if not isinstance ( value , Iterable ) :
return int ( value * factor )
int_value = list ( deepcopy ( value ) )
for i in range ( len ( int_value ) ) :
int_value [ i ] = int ( int_value [ i ] * factor )
return int_value |
def reqMktData ( self , contract : Contract , genericTickList : str = '' , snapshot : bool = False , regulatorySnapshot : bool = False , mktDataOptions : List [ TagValue ] = None ) -> Ticker :
"""Subscribe to tick data or request a snapshot .
Returns the Ticker that holds the market data . The ticker will
initi... | reqId = self . client . getReqId ( )
ticker = self . wrapper . startTicker ( reqId , contract , 'mktData' )
self . client . reqMktData ( reqId , contract , genericTickList , snapshot , regulatorySnapshot , mktDataOptions )
return ticker |
def serialize_date ( value ) :
"""Attempts to convert ` value ` into an ` ` xs : date ` ` string . If ` value ` is
` ` None ` ` , ` ` None ` ` will be returned .
Args :
value : A date value . This can be a string , datetime . date , or
datetime . datetime object .
Returns :
An ` ` xs : date ` ` formatte... | if not value :
return None
elif isinstance ( value , datetime . datetime ) :
return value . date ( ) . isoformat ( )
elif isinstance ( value , datetime . date ) :
return value . isoformat ( )
else :
return parse_date ( value ) . isoformat ( ) |
def transition_to_execute_complete ( self ) :
"""Transition to execute complate""" | assert self . state in [ AQStateMachineStates . execute ]
self . state = AQStateMachineStates . execute_complete |
def _should_wrap ( self , node , child , is_left ) :
"""Wrap child if :
- it has lower precedence
- same precedence with position opposite to associativity direction""" | node_precedence = node . op_precedence ( )
child_precedence = child . op_precedence ( )
if node_precedence > child_precedence : # 3 * ( 4 + 5)
return True
if ( node_precedence == child_precedence and is_left != node . op_left_associative ( ) ) : # 3 - ( 4 - 5)
# (2 * * 3 ) * * 4
return True
return False |
def dict_merge ( base , addition , append_lists = False ) :
"""Merge one dictionary with another , recursively .
Fields present in addition will be added to base if not present or merged
if both values are dictionaries or lists ( with append _ lists = True ) . If
the values are different data types , the valu... | if not isinstance ( base , dict ) or not isinstance ( addition , dict ) :
raise TypeError ( "dict_merge only works with dicts." )
new_base = deepcopy ( base )
for key , value in addition . items ( ) : # Simplest case : Key not in base , so add value to base
if key not in new_base . keys ( ) :
new_base [... |
def is_supported ( cls , desc ) :
"""Determines if the given label descriptor is supported .
Args :
desc ( : class : ` endpoints _ management . gen . servicemanagement _ v1 _ messages . LabelDescriptor ` ) :
the label descriptor to test
Return :
` True ` if desc is supported , otherwise ` False `""" | for l in cls :
if l . matches ( desc ) :
return True
return False |
def calculate_gamma_matrix ( magnetic_states , Omega = 1 ) :
r"""Calculate the matrix of decay between states .
This function calculates the matrix $ \ gamma _ { ij } $ of decay rates between
states | i > and | j > ( in the units specified by the Omega argument ) .
> > > g = State ( " Rb " , 87,5,0,1 / Intege... | Ne = len ( magnetic_states )
II = magnetic_states [ 0 ] . i
gamma = [ [ 0.0 for j in range ( Ne ) ] for i in range ( Ne ) ]
for i in range ( Ne ) :
for j in range ( i ) :
ei = magnetic_states [ i ]
ej = magnetic_states [ j ]
einsteinAij = Transition ( ei , ej ) . einsteinA
if einstei... |
def connect ( self , host , port ) :
'''Connect to a host and port .''' | # Clear the connect state immediately since we ' re no longer connected
# at this point .
self . _connected = False
# Only after the socket has connected do we clear this state ; closed
# must be False so that writes can be buffered in writePacket ( ) . The
# closed state might have been set to True due to a socket err... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.