signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _extract_specification_parts ( specification ) : # type : ( str ) - > Tuple [ str , str ]
"""Extract the language and the interface from a " language : / interface "
interface name
: param specification : The formatted interface name
: return : A ( language , interface name ) tuple
: raise ValueError : ... | try : # Parse the URI - like string
parsed = urlparse ( specification )
except : # Invalid URL
raise ValueError ( "Invalid specification URL: {0}" . format ( specification ) )
# Extract the interface name
interface = parsed . path
# Extract the language , if given
language = parsed . scheme
if not language : # ... |
async def findArtifactFromTask ( self , * args , ** kwargs ) :
"""Get Artifact From Indexed Task
Find a task by index path and redirect to the artifact on the most recent
run with the given ` name ` .
Note that multiple calls to this endpoint may return artifacts from differen tasks
if a new task is inserte... | return await self . _makeApiCall ( self . funcinfo [ "findArtifactFromTask" ] , * args , ** kwargs ) |
def toNumber ( str , default = None ) :
"""toNumber ( str [ , default ] ) - > integer | float | default
Converts the given string to a numeric value . The string may be a
hexadecimal , integer , or floating number . If string could not be
converted , default ( None ) is returned .
Examples :
> > > n = toN... | value = default
try :
if str . startswith ( "0x" ) :
value = int ( str , 16 )
else :
try :
value = int ( str )
except ValueError :
value = float ( str )
except ValueError :
pass
return value |
def layer ( op ) :
'''Decorator for composable network layers .''' | def layer_decorated ( self , * args , ** kwargs ) : # Automatically set a name if not provided .
name = kwargs . setdefault ( 'name' , self . get_unique_name ( op . __name__ ) )
# Figure out the layer inputs .
if len ( self . terminals ) == 0 :
raise RuntimeError ( 'No input variables found for laye... |
def unzip_file ( self , zip_path , output_path ) :
"""Unzip a local file into a specified directory .""" | with zipfile . ZipFile ( zip_path , 'r' ) as z :
z . extractall ( output_path ) |
def bytes_from_decode_data ( s ) :
"""copy from base64 . _ bytes _ from _ decode _ data""" | if isinstance ( s , ( str , unicode ) ) :
try :
return s . encode ( 'ascii' )
except UnicodeEncodeError :
raise NotValidParamError ( 'String argument should contain only ASCII characters' )
if isinstance ( s , bytes_types ) :
return s
try :
return memoryview ( s ) . tobytes ( )
except Ty... |
def at ( self , t ) :
"""Return the modelled tidal height at given times .
Arguments :
t - - array of times at which to evaluate the tidal height""" | t0 = t [ 0 ]
hours = self . _hours ( t0 , t )
partition = 240.0
t = self . _partition ( hours , partition )
times = self . _times ( t0 , [ ( i + 0.5 ) * partition for i in range ( len ( t ) ) ] )
speed , u , f , V0 = self . prepare ( t0 , times , radians = True )
H = self . model [ 'amplitude' ] [ : , np . newaxis ]
p ... |
def run_latex_report ( base , report_dir , section_info ) :
"""Generate a pdf report with plots using latex .""" | out_name = "%s_recal_plots.tex" % base
out = os . path . join ( report_dir , out_name )
with open ( out , "w" ) as out_handle :
out_tmpl = Template ( out_template )
out_handle . write ( out_tmpl . render ( sections = section_info ) )
start_dir = os . getcwd ( )
try :
os . chdir ( report_dir )
cl = [ "pd... |
def summary ( self ) :
"""Summary statistics describing the fit .
Set alpha property in the object before calling .
Returns
df : DataFrame
Contains columns coef , np . exp ( coef ) , se ( coef ) , z , p , lower , upper""" | ci = 1 - self . alpha
with np . errstate ( invalid = "ignore" , divide = "ignore" ) :
df = pd . DataFrame ( index = self . hazards_ . index )
df [ "coef" ] = self . hazards_
df [ "exp(coef)" ] = np . exp ( self . hazards_ )
df [ "se(coef)" ] = self . standard_errors_
df [ "z" ] = self . _compute_z_v... |
def execute ( self , limit = 'default' , params = None , ** kwargs ) :
"""If this expression is based on physical tables in a database backend ,
execute it against that backend .
Parameters
limit : integer or None , default ' default '
Pass an integer to effect a specific row limit . limit = None means " no... | from ibis . client import execute
return execute ( self , limit = limit , params = params , ** kwargs ) |
def summarize_sec2hdrgos ( self , sec2d_hdrgos ) :
"""Get counts of header GO IDs and sections .""" | hdrgos_all = set ( [ ] )
hdrgos_grouped = set ( )
hdrgos_ungrouped = set ( )
sections_grouped = set ( )
for sectionname , hdrgos in sec2d_hdrgos :
self . _chk_hdrgoids ( hdrgos )
hdrgos_all . update ( hdrgos )
if sectionname != HdrgosSections . secdflt :
hdrgos_grouped . update ( hdrgos )
se... |
def check_error ( model , path , shapes , output = 'softmax_output' , verbose = True ) :
"""Check the difference between predictions from MXNet and CoreML .""" | coreml_model = _coremltools . models . MLModel ( path )
input_data = { }
input_data_copy = { }
for ip in shapes :
input_data [ ip ] = _np . random . rand ( * shapes [ ip ] ) . astype ( 'f' )
input_data_copy [ ip ] = _np . copy ( input_data [ ip ] )
dataIter = _mxnet . io . NDArrayIter ( input_data_copy )
mx_out... |
def save_json ( histogram : Union [ HistogramBase , HistogramCollection ] , path : Optional [ str ] = None , ** kwargs ) -> str :
"""Save histogram to JSON format .
Parameters
histogram : Any histogram
path : If set , also writes to the path .
Returns
json : The JSON representation of the histogram""" | # TODO : Implement multiple histograms in one file ?
data = histogram . to_dict ( )
data [ "physt_version" ] = CURRENT_VERSION
if isinstance ( histogram , HistogramBase ) :
data [ "physt_compatible" ] = COMPATIBLE_VERSION
elif isinstance ( histogram , HistogramCollection ) :
data [ "physt_compatible" ] = COLLEC... |
def add_labels_to_subsets ( ax , subset_by , subset_order , text_kwargs = None , add_hlines = True , hline_kwargs = None ) :
"""Helper function for adding labels to subsets within a heatmap .
Assumes that imshow ( ) was called with ` subsets ` and ` subset _ order ` .
Parameters
ax : matplotlib . Axes
The a... | _text_kwargs = dict ( transform = ax . get_yaxis_transform ( ) )
if text_kwargs :
_text_kwargs . update ( text_kwargs )
_hline_kwargs = dict ( color = 'k' )
if hline_kwargs :
_hline_kwargs . update ( hline_kwargs )
pos = 0
for label in subset_order :
ind = subset_by == label
last_pos = pos
pos += su... |
def element ( self , * args , ** kwargs ) :
"""Add a child element to the : class : ` xml4h . nodes . Element ` node
represented by this Builder .
: return : a new Builder that represents the child element .
Delegates to : meth : ` xml4h . nodes . Element . add _ element ` .""" | child_element = self . _element . add_element ( * args , ** kwargs )
return Builder ( child_element ) |
def check_file_exists ( self , remote_cmd = "dir home" ) :
"""Check if the dest _ file already exists on the file system ( return boolean ) .""" | if self . direction == "put" :
remote_out = self . ssh_ctl_chan . send_command_expect ( remote_cmd )
search_string = r"Directory contents .*{}" . format ( self . dest_file )
return bool ( re . search ( search_string , remote_out , flags = re . DOTALL ) )
elif self . direction == "get" :
return os . path... |
def make_noise_surface ( dims = DEFAULT_DIMS , blur = 10 , seed = None ) :
"""Makes a surface by generating random noise and blurring it .
Args :
dims ( pair ) : the dimensions of the surface to create
blur ( float ) : the amount of Gaussian blur to apply
seed ( int ) : a random seed to use ( optional )
R... | if seed is not None :
np . random . seed ( seed )
return gaussian_filter ( np . random . normal ( size = dims ) , blur ) |
def get_context ( awsclient , env , tool , command , arguments = None ) :
"""This assembles the tool context . Private members are preceded by a ' _ ' .
: param tool :
: param command :
: return : dictionary containing the gcdt tool context""" | # TODO : elapsed , artifact ( stack , depl - grp , lambda , api )
if arguments is None :
arguments = { }
context = { '_awsclient' : awsclient , 'env' : env , 'tool' : tool , 'command' : command , '_arguments' : arguments , # TODO clean up arguments - > args
'version' : __version__ , 'user' : _get_user ( ) , 'plugin... |
def fftlog ( fEM , time , freq , ftarg ) :
r"""Fourier Transform using FFTLog .
FFTLog is the logarithmic analogue to the Fast Fourier Transform FFT .
FFTLog was presented in Appendix B of [ Hami00 ] _ and published at
< http : / / casa . colorado . edu / ~ ajsh / FFTLog > .
This function uses a simplified ... | # Get tcalc , dlnr , kr , rk , q ; a and n
_ , _ , q , mu , tcalc , dlnr , kr , rk = ftarg
if mu > 0 : # Sine
a = - fEM . imag
else : # Cosine
a = fEM . real
n = a . size
# 1 . Amplitude and Argument of kr ^ ( - 2 i y ) U _ mu ( q + 2 i y )
ln2kr = np . log ( 2.0 / kr )
d = np . pi / ( n * dlnr )
m = np . arang... |
def funnel_rebuild ( psg_trm_spec ) :
"""Rebuilds a model and compares it to a reference model .
Parameters
psg _ trm : ( ( [ float ] , float , int ) , AMPAL , specification )
A tuple containing the parameters , score and generation for a
model as well as a model of the best scoring parameters .
Returns
... | param_score_gen , top_result_model , specification = psg_trm_spec
params , score , gen = param_score_gen
model = specification ( * params )
rmsd = top_result_model . rmsd ( model )
return rmsd , score , gen |
def revert ( self , snapshot : Tuple [ Hash32 , UUID ] ) -> None :
"""Revert the VM to the state at the snapshot""" | state_root , account_snapshot = snapshot
# first revert the database state root .
self . _account_db . state_root = state_root
# now roll the underlying database back
self . _account_db . discard ( account_snapshot ) |
def create_run_from_task_definition ( self , task_def_file , options , propertyfile , required_files_pattern ) :
"""Create a Run from a task definition in yaml format""" | task_def = load_task_definition_file ( task_def_file )
def expand_patterns_from_tag ( tag ) :
result = [ ]
patterns = task_def . get ( tag , [ ] )
if isinstance ( patterns , str ) or not isinstance ( patterns , collections . Iterable ) : # accept single string in addition to list of strings
patterns... |
def enroll ( self , uuid , organization , from_date = MIN_PERIOD_DATE , to_date = MAX_PERIOD_DATE , merge = False ) :
"""Enroll a unique identity in an organization .
This method adds a new relationship between the unique identity ,
identified by < uuid > , and < organization > . Both entities must exist
on t... | # Empty or None values for uuid and organizations are not allowed
if not uuid or not organization :
return CMD_SUCCESS
try :
api . add_enrollment ( self . db , uuid , organization , from_date , to_date )
code = CMD_SUCCESS
except ( NotFoundError , InvalidValueError ) as e :
self . error ( str ( e ) )
... |
def ObjectTransitionedEventHandler ( obj , event ) :
"""Object has been transitioned to an new state""" | # only snapshot supported objects
if not supports_snapshots ( obj ) :
return
# default transition entry
entry = { "modified" : DateTime ( ) . ISO ( ) , "action" : event . action , }
# get the last history item
history = api . get_review_history ( obj , rev = True )
if history :
entry = history [ 0 ]
# make ... |
def getAttributes ( self , found = None ) :
'''Method to extract additional attributes from a given expression ( i . e . : domains and ports from URL and so on ) . This method may be overwritten in certain child classes .
: param found : expression to be processed .
: return : The output format will be like :
... | # List of attributes
results = [ ]
if not '@' in found : # character may be ' @ ' or ' . '
for character in self . substitutionValues . keys ( ) :
for value in self . substitutionValues [ character ] : # replacing ' [ at ] ' for ' @ ' . . .
found = found . replace ( value , character )
# Bui... |
def get_file_nodes ( self , path , node = None ) :
"""Returns the : class : ` umbra . components . factory . script _ editor . nodes . FileNode ` class Nodes with given path .
: param node : Node to start walking from .
: type node : AbstractNode or AbstractCompositeNode or Object
: param path : File path .
... | return [ file_node for file_node in self . list_file_nodes ( node ) if file_node . path == path ] |
def _store_object ( self , obj_name , content , etag = None , chunked = False , chunk_size = None , headers = None ) :
"""Handles the low - level creation of a storage object and the uploading of
the contents of that object .""" | head_etag = headers . pop ( "ETag" , "" )
if chunked :
headers . pop ( "Content-Length" , "" )
headers [ "Transfer-Encoding" ] = "chunked"
elif etag is None and content is not None :
etag = utils . get_checksum ( content )
if etag :
headers [ "ETag" ] = etag
if not headers . get ( "Content-Type" ) :
... |
def sg_set_online ( self , online ) :
"""Set the sensor - graph online / offline .""" | self . sensor_graph . enabled = bool ( online )
return [ Error . NO_ERROR ] |
def setLocation ( self , x , y ) :
"""Set the location of this object to the specified coordinates .""" | self . x = int ( x )
self . y = int ( y )
return self |
def confirm_vlan ( self , number_net , id_environment_vlan , ip_version = None ) :
"""Checking if the vlan insert need to be confirmed
: param number _ net : Filter by vlan number column
: param id _ environment _ vlan : Filter by environment ID related
: param ip _ version : Ip version for checking
: retur... | url = 'vlan/confirm/' + str ( number_net ) + '/' + id_environment_vlan + '/' + str ( ip_version )
code , xml = self . submit ( None , 'GET' , url )
return self . response ( code , xml ) |
def delete_webhook ( self , ) :
"""Use this method to remove webhook integration if you decide to switch back to getUpdates . Returns True on success . Requires no parameters .
https : / / core . telegram . org / bots / api # deletewebhook
Returns :
: return : Returns True on success
: rtype : bool""" | result = self . do ( "deleteWebhook" , )
if self . return_python_objects :
logger . debug ( "Trying to parse {data}" . format ( data = repr ( result ) ) )
try :
return from_array_list ( bool , result , list_level = 0 , is_builtin = True )
except TgApiParseException :
logger . debug ( "Failed... |
def rpc_method ( func , doc = None , format = 'json' , request_handler = None ) :
'''A decorator which exposes a function ` ` func ` ` as an rpc function .
: param func : The function to expose .
: param doc : Optional doc string . If not provided the doc string of
` ` func ` ` will be used .
: param format... | def _ ( self , * args , ** kwargs ) :
request = args [ 0 ]
if request_handler :
kwargs = request_handler ( request , format , kwargs )
try :
return func ( * args , ** kwargs )
except TypeError :
msg = checkarity ( func , args , kwargs )
if msg :
raise InvalidP... |
def flip_video ( self , is_flip , callback = None ) :
'''Flip video
` ` is _ flip ` ` : 0 Not flip , 1 Flip''' | params = { 'isFlip' : is_flip }
return self . execute_command ( 'flipVideo' , params , callback = callback ) |
def find_by ( self , column = None , value = None , order_by = None , limit = 0 ) :
"""Find all items that matches your a column / value .
: param column : column to search .
: param value : value to look for in ` column ` .
: param limit : How many rows to fetch .
: param order _ by : column on which to or... | with rconnect ( ) as conn :
if column is None or value is None :
raise ValueError ( "You need to supply both a column and a value" )
try :
query = self . _base ( )
if order_by is not None :
query = self . _order_by ( query , order_by )
if limit > 0 :
query... |
def from_scene_coords ( self , x = 0 , y = 0 ) :
"""Converts x , y given in the scene coordinates to sprite ' s local ones
coordinates""" | matrix = self . get_matrix ( )
matrix . invert ( )
return matrix . transform_point ( x , y ) |
def init ( ctx , client , directory , name , force , use_external_storage ) :
"""Initialize a project .""" | if not client . use_external_storage :
use_external_storage = False
ctx . obj = client = attr . evolve ( client , path = directory , use_external_storage = use_external_storage , )
msg = 'Initialized empty project in {path}'
branch_name = None
stack = contextlib . ExitStack ( )
if force and client . repo :
msg ... |
def size_control_valve_g ( T , MW , mu , gamma , Z , P1 , P2 , Q , D1 = None , D2 = None , d = None , FL = 0.9 , Fd = 1 , xT = 0.7 , allow_choked = True , allow_laminar = True , full_output = False ) :
r'''Calculates flow coefficient of a control valve passing a gas
according to IEC 60534 . Uses a large number of... | MAX_C_POSSIBLE = 1E40
# Quit iterations if C reaches this high
# Pa to kPa , according to constants in standard
P1 , P2 = P1 / 1000. , P2 / 1000.
Q = Q * 3600.
# m ^ 3 / s to m ^ 3 / hr , according to constants in standard
# Convert dynamic viscosity to kinematic viscosity
Vm = Z * R * T / ( P1 * 1000 )
rho = ( Vm ) **... |
def libvlc_vlm_get_media_instance_time ( p_instance , psz_name , i_instance ) :
'''Get vlm _ media instance time by name or instance id .
@ param p _ instance : a libvlc instance .
@ param psz _ name : name of vlm media instance .
@ param i _ instance : instance id .
@ return : time as integer or - 1 on err... | f = _Cfunctions . get ( 'libvlc_vlm_get_media_instance_time' , None ) or _Cfunction ( 'libvlc_vlm_get_media_instance_time' , ( ( 1 , ) , ( 1 , ) , ( 1 , ) , ) , None , ctypes . c_int , Instance , ctypes . c_char_p , ctypes . c_int )
return f ( p_instance , psz_name , i_instance ) |
def _set_current_options ( self , options ) :
"""Set current options for a model .
Parameters
options : dict
A dictionary of the desired option settings . The key should be the name
of the option and each value is the desired value of the option .""" | opts = self . _get_current_options ( )
opts . update ( options )
response = self . __proxy__ . set_current_options ( opts )
return response |
def skew ( self , x = 0 , y = 0 ) :
"""Skew the element by x and y degrees
Convenience function which calls skew _ x and skew _ y
Parameters
x , y : float , float
skew angle in degrees ( default 0)
If an x / y angle is given as zero degrees , that transformation is omitted .""" | if x is not 0 :
self . skew_x ( x )
if y is not 0 :
self . skew_y ( y )
return self |
def interactive_imshow ( img , lclick_cb = None , rclick_cb = None , ** kwargs ) :
"""Args :
img ( np . ndarray ) : an image ( expect BGR ) to show .
lclick _ cb , rclick _ cb : a callback ` ` func ( img , x , y ) ` ` for left / right click event .
kwargs : can be { key _ cb _ a : callback _ img , key _ cb _ ... | name = 'tensorpack_viz_window'
cv2 . imshow ( name , img )
def mouse_cb ( event , x , y , * args ) :
if event == cv2 . EVENT_LBUTTONUP and lclick_cb is not None :
lclick_cb ( img , x , y )
elif event == cv2 . EVENT_RBUTTONUP and rclick_cb is not None :
rclick_cb ( img , x , y )
cv2 . setMouseCal... |
def guess_bonds ( r_array , type_array , threshold = 0.1 , maxradius = 0.3 , radii_dict = None ) :
'''Detect bonds given the coordinates ( r _ array ) and types of the
atoms involved ( type _ array ) , based on their covalent radii .
To fine - tune the detection , it is possible to set a * * threshold * * and a... | if radii_dict is None :
covalent_radii = cdb . get ( 'data' , 'covalentdict' )
else :
covalent_radii = radii_dict
# Find all the pairs
ck = cKDTree ( r_array )
pairs = ck . query_pairs ( maxradius )
bonds = [ ]
for i , j in pairs :
a , b = covalent_radii [ type_array [ i ] ] , covalent_radii [ type_array [ ... |
def diff ( self , other , ** kwargs ) :
"""Compare an object with another and return a : py : class : ` DiffInfo `
object . Accepts the same arguments as
: py : meth : ` normalize . record . Record . diff _ iter `""" | from normalize . diff import diff
return diff ( self , other , ** kwargs ) |
def drawSector ( page , center , point , beta , color = None , fill = None , dashes = None , fullSector = True , morph = None , width = 1 , closePath = False , roundCap = False , overlay = True ) :
"""Draw a circle sector given circle center , one arc end point and the angle of the arc .
Parameters :
center - -... | img = page . newShape ( )
Q = img . drawSector ( Point ( center ) , Point ( point ) , beta , fullSector = fullSector )
img . finish ( color = color , fill = fill , dashes = dashes , width = width , roundCap = roundCap , morph = morph , closePath = closePath )
img . commit ( overlay )
return Q |
def _calibrate ( self , data ) :
"""Visible / IR channel calibration .""" | lut = self . prologue [ 'ImageCalibration' ] [ self . chid ]
if abs ( lut ) . max ( ) > 16777216 :
lut = lut . astype ( np . float64 )
else :
lut = lut . astype ( np . float32 )
lut /= 1000
lut [ 0 ] = np . nan
# Dask / XArray don ' t support indexing in 2D ( yet ) .
res = data . data . map_blocks ( self . _get... |
def process_request ( self , request ) :
"""Process the web - based auth request .""" | # User has already been authed by alternate middleware
if hasattr ( request , "facebook" ) and request . facebook :
return
request . facebook = False
if not self . is_valid_path ( request ) :
return
if self . is_access_denied ( request ) :
return authorization_denied_view ( request )
request . facebook = Fa... |
def serialize ( self , ** kwargs ) -> str :
"""rdflib . Graph ( ) . serialize wrapper
Original serialize cannot handle PosixPath from pathlib . You should ignore everything , but
destination and format . format is a must , but if you don ' t include a destination , it will
just return the formated graph as an... | kwargs = { key : str ( value ) for key , value in kwargs . items ( ) }
return self . g . serialize ( ** kwargs ) |
def insert_table ( self , rows , cols ) :
"""Return a | PlaceholderGraphicFrame | object containing a table of
* rows * rows and * cols * columns . The position and width of the table
are those of the placeholder and its height is proportional to the
number of rows . A | PlaceholderGraphicFrame | object has a... | graphicFrame = self . _new_placeholder_table ( rows , cols )
self . _replace_placeholder_with ( graphicFrame )
return PlaceholderGraphicFrame ( graphicFrame , self . _parent ) |
def histogram ( self , column = 'r' , filename = None , log10 = False , ** kwargs ) :
"""Plot a histogram of one data column""" | return_dict = HS . plot_histograms ( self . data , column )
if filename is not None :
return_dict [ 'all' ] . savefig ( filename , dpi = 300 )
return return_dict |
def uncomment ( path , regex , char = '#' , backup = '.bak' ) :
'''. . deprecated : : 0.17.0
Use : py : func : ` ~ salt . modules . file . replace ` instead .
Uncomment specified commented lines in a file
path
The full path to the file to be edited
regex
A regular expression used to find the lines that ... | return comment_line ( path = path , regex = regex , char = char , cmnt = False , backup = backup ) |
def update ( self , source_file , configuration , declarations , included_files ) :
"""Replace a cache entry by a new value .
: param source _ file : a C + + source file name .
: type source _ file : str
: param configuration : configuration object .
: type configuration : : class : ` xml _ generator _ conf... | # Normlize all paths . . .
source_file = os . path . normpath ( source_file )
included_files = [ os . path . normpath ( p ) for p in included_files ]
# Create the list of dependent files . This is the included _ files list
# + the source file . Duplicate names are removed .
dependent_files = { }
for name in [ source_fi... |
def _from_json_list ( cls , response_raw , wrapper = None ) :
""": type response _ raw : client . BunqResponseRaw
: type wrapper : str | None
: rtype : client . BunqResponse [ list [ cls ] ]""" | json = response_raw . body_bytes . decode ( )
obj = converter . json_to_class ( dict , json )
array = obj [ cls . _FIELD_RESPONSE ]
array_deserialized = [ ]
for item in array :
item_unwrapped = item if wrapper is None else item [ wrapper ]
item_deserialized = converter . deserialize ( cls , item_unwrapped )
... |
def CEN_calc ( classes , table , TOP , P , class_name , modified = False ) :
"""Calculate CEN ( Confusion Entropy ) / MCEN ( Modified Confusion Entropy ) .
: param classes : classes
: type classes : list
: param table : input matrix
: type table : dict
: param TOP : test outcome positive
: type TOP : in... | try :
result = 0
class_number = len ( classes )
for k in classes :
if k != class_name :
P_j_k = CEN_misclassification_calc ( table , TOP , P , class_name , k , class_name , modified )
P_k_j = CEN_misclassification_calc ( table , TOP , P , k , class_name , class_name , modifie... |
def vis_aggregate_groups ( Verts , E2V , Agg , mesh_type , output = 'vtk' , fname = 'output.vtu' ) :
"""Coarse grid visualization of aggregate groups .
Create . vtu files for use in Paraview or display with Matplotlib .
Parameters
Verts : { array }
coordinate array ( N x D )
E2V : { array }
element inde... | check_input ( Verts = Verts , E2V = E2V , Agg = Agg , mesh_type = mesh_type )
map_type_to_key = { 'tri' : 5 , 'quad' : 9 , 'tet' : 10 , 'hex' : 12 }
if mesh_type not in map_type_to_key :
raise ValueError ( 'unknown mesh_type=%s' % mesh_type )
key = map_type_to_key [ mesh_type ]
Agg = csr_matrix ( Agg )
# remove ele... |
def confirm_phone_number ( self , sms_code ) :
"""Confirm phone number with the recieved SMS code
: param sms _ code : sms code
: type sms _ code : : class : ` str `
: return : success ( returns ` ` False ` ` on request fail / timeout )
: rtype : : class : ` bool `""" | sess = self . _get_web_session ( )
try :
resp = sess . post ( 'https://steamcommunity.com/steamguard/phoneajax' , data = { 'op' : 'check_sms_code' , 'arg' : sms_code , 'checkfortos' : 1 , 'skipvoip' : 1 , 'sessionid' : sess . cookies . get ( 'sessionid' , domain = 'steamcommunity.com' ) , } , timeout = 15 ) . json ... |
def parse_san ( self , san : str ) -> Move :
"""Uses the current position as the context to parse a move in standard
algebraic notation and returns the corresponding move object .
The returned move is guaranteed to be either legal or a null move .
: raises : : exc : ` ValueError ` if the SAN is invalid or amb... | # Castling .
try :
if san in [ "O-O" , "O-O+" , "O-O#" ] :
return next ( move for move in self . generate_castling_moves ( ) if self . is_kingside_castling ( move ) )
elif san in [ "O-O-O" , "O-O-O+" , "O-O-O#" ] :
return next ( move for move in self . generate_castling_moves ( ) if self . is_qu... |
def walletpassphrase ( self , passphrase , timeout = 99999999 , mint_only = True ) :
"""used to unlock wallet for minting""" | return self . req ( "walletpassphrase" , [ passphrase , timeout , mint_only ] ) |
def TP3 ( x , u , jac = False ) :
'''Demo problem 1 for horsetail matching , takes two input values of
size 1''' | q = 2 + 0.5 * x + 1.5 * ( 1 - x ) * u
if not jac :
return q
else :
grad = 0.5 - 1.5 * u
return q , grad |
def nsUriMatch ( self , value , wanted , strict = 0 , tt = type ( ( ) ) ) :
"""Return a true value if two namespace uri values match .""" | if value == wanted or ( type ( wanted ) is tt ) and value in wanted :
return 1
if not strict and value is not None :
wanted = type ( wanted ) is tt and wanted or ( wanted , )
value = value [ - 1 : ] != '/' and value or value [ : - 1 ]
for item in wanted :
if item == value or item [ : - 1 ] == va... |
def run_vardict ( align_bams , items , ref_file , assoc_files , region = None , out_file = None ) :
"""Run VarDict variant calling .""" | items = shared . add_highdepth_genome_exclusion ( items )
if vcfutils . is_paired_analysis ( align_bams , items ) :
call_file = _run_vardict_paired ( align_bams , items , ref_file , assoc_files , region , out_file )
else :
vcfutils . check_paired_problems ( items )
call_file = _run_vardict_caller ( align_ba... |
def update_express ( self , template_id , delivery_template ) :
"""增加邮费模板
: param template _ id : 邮费模板ID
: param delivery _ template : 邮费模板信息 ( 字段说明详见增加邮费模板 )
: return : 返回的 JSON 数据包""" | delivery_template [ 'template_id' ] = template_id
return self . _post ( 'merchant/express/update' , data = delivery_template ) |
def on_person_update ( self , people ) :
"""People have changed ( e . g . a sensor value )
: param people : People whos state changed ( may include unchanged )
: type people : list [ paps . person . Person ]
: rtype : None""" | self . debug ( "()" )
changed = [ ]
with self . _people_lock :
for p in people :
person = Person . from_person ( p )
if person . id not in self . _people :
self . warning ( u"{} not in audience" . format ( person . id ) )
self . _people [ person . id ] = person
# Check if... |
def parse ( argv , rules = None , config = None , ** kwargs ) :
"""Parse the given arg vector with the default Splunk command rules .""" | parser_ = parser ( rules , ** kwargs )
if config is not None :
parser_ . loadrc ( config )
return parser_ . parse ( argv ) . result |
def sort ( self , col : str ) :
"""Sorts the main dataframe according to the given column
: param col : column name
: type col : str
: example : ` ` ds . sort ( " Col 1 " ) ` `""" | try :
self . df = self . df . copy ( ) . sort_values ( col )
except Exception as e :
self . err ( e , "Can not sort the dataframe from column " + str ( col ) ) |
def result_worker ( ctx , result_cls , get_object = False ) :
"""Run result worker .""" | g = ctx . obj
ResultWorker = load_cls ( None , None , result_cls )
result_worker = ResultWorker ( resultdb = g . resultdb , inqueue = g . processor2result )
g . instances . append ( result_worker )
if g . get ( 'testing_mode' ) or get_object :
return result_worker
result_worker . run ( ) |
def configure_lease ( self , lease , lease_max , mount_point = DEFAULT_MOUNT_POINT ) :
"""Configure lease settings for the AWS secrets engine .
It is optional , as there are default values for lease and lease _ max .
Supported methods :
POST : / { mount _ point } / config / lease . Produces : 204 ( empty body... | params = { 'lease' : lease , 'lease_max' : lease_max , }
api_path = '/v1/{mount_point}/config/lease' . format ( mount_point = mount_point )
return self . _adapter . post ( url = api_path , json = params , ) |
def get_file_content ( self , path ) :
"""Returns content of the file at given ` ` path ` ` .""" | id = self . _get_id_for_path ( path )
blob = self . repository . _repo [ id ]
return blob . as_pretty_string ( ) |
def around_me ( self , member , ** options ) :
'''Retrieve a page of leaders from the leaderboard around a given member .
@ param member [ String ] Member name .
@ param options [ Hash ] Options to be used when retrieving the page from the leaderboard .
@ return a page of leaders from the leaderboard around a... | return self . around_me_in ( self . leaderboard_name , member , ** options ) |
def wrap_results_for_axis ( self ) :
"""return the results for the rows""" | results = self . results
result = self . obj . _constructor ( data = results )
if not isinstance ( results [ 0 ] , ABCSeries ) :
try :
result . index = self . res_columns
except ValueError :
pass
try :
result . columns = self . res_index
except ValueError :
pass
return result |
def get_attribute_compound ( attribute , value = None , splitter = "|" , binding_identifier = "@" ) :
"""Returns an attribute compound .
Usage : :
> > > data = " @ Link | Value | Boolean | Link Parameter "
> > > attribute _ compound = foundations . parsers . get _ attribute _ compound ( " Attribute Compound "... | LOGGER . debug ( "> Attribute: '{0}', value: '{1}'." . format ( attribute , value ) )
if type ( value ) is unicode :
if splitter in value :
value_tokens = value . split ( splitter )
if len ( value_tokens ) >= 3 and re . search ( r"{0}\w*" . format ( binding_identifier ) , value_tokens [ 0 ] ) :
... |
def remove ( self , dic ) :
'''remove the pair by passing a identical dict
Args :
dic ( dict ) : key and value''' | for kw in dic :
removePair = Pair ( kw , dic [ kw ] )
self . _remove ( [ removePair ] ) |
def db_snapshot_append ( cls , cur , block_id , consensus_hash , ops_hash , timestamp ) :
"""Append hash info for the last block processed , and the time at which it was done .
Meant to be executed as part of a transaction .
Return True on success
Raise an exception on invalid block number
Abort on db error... | query = 'INSERT INTO snapshots (block_id,consensus_hash,ops_hash,timestamp) VALUES (?,?,?,?);'
args = ( block_id , consensus_hash , ops_hash , timestamp )
cls . db_query_execute ( cur , query , args )
return True |
def evaluate ( self ) :
"""Evaluate functional value of previous iteration""" | if self . opt [ 'AccurateDFid' ] :
D = self . dstep . var_y ( )
X = self . xstep . var_y ( )
S = self . xstep . S
dfd = 0.5 * np . linalg . norm ( ( D . dot ( X ) - S ) ) ** 2
rl1 = np . sum ( np . abs ( X ) )
return dict ( DFid = dfd , RegL1 = rl1 , ObjFun = dfd + self . xstep . lmbda * rl1 )
e... |
def introspect_operation ( self , operation ) :
"""Introspects an entire operation , returning : :
* the method name ( to expose to the user )
* the API name ( used server - side )
* docs
* introspected information about the parameters
* information about the output
: param operation : The operation to ... | return { 'method_name' : operation . py_name , 'api_name' : operation . name , 'docs' : self . convert_docs ( operation . documentation ) , 'params' : self . parse_params ( operation . params ) , 'output' : operation . output , } |
def send ( self , message ) :
"""Sends a message to all subscribers of destination .
@ param message : The message frame . ( The frame will be modified to set command
to MESSAGE and set a message id . )
@ type message : L { stompclient . frame . Frame }""" | dest = message . headers . get ( 'destination' )
if not dest :
raise ValueError ( "Cannot send frame with no destination: %s" % message )
message . cmd = 'message'
message . headers . setdefault ( 'message-id' , str ( uuid . uuid4 ( ) ) )
bad_subscribers = set ( )
for subscriber in self . _topics [ dest ] :
try... |
def _get_pores ( self , sampling_points ) :
"""Under development .""" | pores = [ ]
for point in sampling_points :
pores . append ( Pore ( self . system [ 'elements' ] , self . system [ 'coordinates' ] , com = point ) )
return pores |
def _make_image_description ( self , datasets , ** kwargs ) :
"""generate image description for mitiff .
Satellite : NOAA 18
Date and Time : 06:58 31/05-2016
SatDir : 0
Channels : 6 In this file : 1 - VIS0.63 2 - VIS0.86 3(3B ) - IR3.7
4 - IR10.8 5 - IR11.5 6(3A ) - VIS1.6
Xsize : 4720
Ysize : 5544
... | translate_platform_name = { 'metop01' : 'Metop-B' , 'metop02' : 'Metop-A' , 'metop03' : 'Metop-C' , 'noaa15' : 'NOAA-15' , 'noaa16' : 'NOAA-16' , 'noaa17' : 'NOAA-17' , 'noaa18' : 'NOAA-18' , 'noaa19' : 'NOAA-19' }
first_dataset = datasets
if isinstance ( datasets , list ) :
LOG . debug ( "Datasets is a list of dat... |
def decorate_cls_with_validation ( cls , field_name , # type : str
* validation_func , # type : ValidationFuncs
** kwargs ) : # type : ( . . . ) - > Type [ Any ]
"""This method is equivalent to decorating a class with the ` @ validate _ field ` decorator but can be used a posteriori .
: param cls : the class to d... | error_type , help_msg , none_policy = pop_kwargs ( kwargs , [ ( 'error_type' , None ) , ( 'help_msg' , None ) , ( 'none_policy' , None ) ] , allow_others = True )
# the rest of keyword arguments is used as context .
kw_context_args = kwargs
if not isclass ( cls ) :
raise TypeError ( 'decorated cls should be a class... |
def _pre_commit ( self , transaction , * args , ** kwargs ) :
"""Begin transaction and call the wrapped callable .
If the callable raises an exception , the transaction will be rolled
back . If not , the transaction will be " ready " for ` ` Commit ` ` ( i . e .
it will have staged writes ) .
Args :
trans... | # Force the ` ` transaction ` ` to be not " in progress " .
transaction . _clean_up ( )
transaction . _begin ( retry_id = self . retry_id )
# Update the stored transaction IDs .
self . current_id = transaction . _id
if self . retry_id is None :
self . retry_id = self . current_id
try :
return self . to_wrap ( t... |
def s2time ( secs , show_secs = True , show_fracs = True ) :
"""Converts seconds to time""" | try :
secs = float ( secs )
except :
return "--:--:--.--"
wholesecs = int ( secs )
centisecs = int ( ( secs - wholesecs ) * 100 )
hh = int ( wholesecs / 3600 )
hd = int ( hh % 24 )
mm = int ( ( wholesecs / 60 ) - ( hh * 60 ) )
ss = int ( wholesecs - ( hh * 3600 ) - ( mm * 60 ) )
r = "{:02d}:{:02d}" . format ( h... |
def create_route ( self , item , routes ) :
"""Stores a new item in routing map""" | for route in routes :
self . _routes . setdefault ( route , set ( ) ) . add ( item )
return item |
def comment_magic ( source , language = 'python' , global_escape_flag = True ) :
"""Escape Jupyter magics with ' # '""" | parser = StringParser ( language )
next_is_magic = False
for pos , line in enumerate ( source ) :
if not parser . is_quoted ( ) and ( next_is_magic or is_magic ( line , language , global_escape_flag ) ) :
source [ pos ] = _COMMENT [ language ] + ' ' + line
next_is_magic = language == 'python' and _L... |
def GenerateDSP ( dspfile , source , env ) :
"""Generates a Project file based on the version of MSVS that is being used""" | version_num = 6.0
if 'MSVS_VERSION' in env :
version_num , suite = msvs_parse_version ( env [ 'MSVS_VERSION' ] )
if version_num >= 10.0 :
g = _GenerateV10DSP ( dspfile , source , env )
g . Build ( )
elif version_num >= 7.0 :
g = _GenerateV7DSP ( dspfile , source , env )
g . Build ( )
else :
g = ... |
def get_all_units ( self , params = None ) :
"""Get all units
This will iterate over all pages until it gets all elements .
So if the rate limit exceeded it will throw an Exception and you will get nothing
: param params : search params
: return : list""" | if not params :
params = { }
return self . _iterate_through_pages ( self . get_units_per_page , resource = UNITS , ** { 'params' : params } ) |
def validate_files ( pelican ) :
"""Validate a generated HTML file
: param pelican : pelican object""" | for dirpath , _ , filenames in os . walk ( pelican . settings [ 'OUTPUT_PATH' ] ) :
for name in filenames :
if should_validate ( name ) :
filepath = os . path . join ( dirpath , name )
validate ( filepath ) |
def get_jsapi_ticket ( self ) :
"""获取微信 JS - SDK ticket
该方法会通过 session 对象自动缓存管理 ticket
: return : ticket""" | ticket_key = '{}_jsapi_ticket' . format ( self . _client . corp_id )
expires_at_key = '{}_jsapi_ticket_expires_at' . format ( self . _client . corp_id )
ticket = self . session . get ( ticket_key )
expires_at = self . session . get ( expires_at_key , 0 )
if not ticket or expires_at < int ( time . time ( ) ) :
jsapi... |
def _SetOptions ( self , options , options_class_name ) :
"""Sets the descriptor ' s options
This function is used in generated proto2 files to update descriptor
options . It must not be used outside proto2.""" | self . _options = options
self . _options_class_name = options_class_name
# Does this descriptor have non - default options ?
self . has_options = options is not None |
def _tensor_proto_to_health_pill ( self , tensor_event , node_name , device , output_slot ) :
"""Converts an event _ accumulator . TensorEvent to a HealthPillEvent .
Args :
tensor _ event : The event _ accumulator . TensorEvent to convert .
node _ name : The name of the node ( without the output slot ) .
de... | return self . _process_health_pill_value ( wall_time = tensor_event . wall_time , step = tensor_event . step , device_name = device , output_slot = output_slot , node_name = node_name , tensor_proto = tensor_event . tensor_proto ) |
def elevate ( self ) :
r"""Return a degree - elevated version of the current surface .
Does this by converting the current nodes
: math : ` \ left \ { v _ { i , j , k } \ right \ } _ { i + j + k = d } ` to new nodes
: math : ` \ left \ { w _ { i , j , k } \ right \ } _ { i + j + k = d + 1 } ` . Does so
by r... | _ , num_nodes = self . _nodes . shape
# ( d + 1 ) ( d + 2 ) / 2 - - > ( d + 2 ) ( d + 3 ) / 2
num_new = num_nodes + self . _degree + 2
new_nodes = np . zeros ( ( self . _dimension , num_new ) , order = "F" )
# NOTE : We start from the index triples ( i , j , k ) for the current
# nodes and map them onto ( i + 1 , j , k... |
def clone_repo ( self ) :
"""Clone a repository containing the dotfiles source .""" | tempdir_path = tempfile . mkdtemp ( )
if self . args . git :
self . log . debug ( 'Cloning git source repository from %s to %s' , self . source , tempdir_path )
self . sh ( 'git clone' , self . source , tempdir_path )
else :
raise NotImplementedError ( 'Unknown repo type' )
self . source = tempdir_path |
def home ( request , hproPk ) :
"""Route the request to runURI if defined otherwise go to plugIt""" | if settings . PIAPI_STANDALONE :
return main ( request , '' , hproPk )
( plugIt , baseURI , hproject ) = getPlugItObject ( hproPk )
if hproject . runURI :
return HttpResponseRedirect ( hproject . runURI )
else : # Check if a custom url key is used
if hasattr ( hproject , 'plugItCustomUrlKey' ) and hproject ... |
def delete ( self , loc ) :
"""Make new index with passed location deleted
Returns
new _ index : MultiIndex""" | new_codes = [ np . delete ( level_codes , loc ) for level_codes in self . codes ]
return MultiIndex ( levels = self . levels , codes = new_codes , names = self . names , verify_integrity = False ) |
def get_verbose_field_name ( instance , field_name ) :
"""Returns verbose _ name for a field .""" | fields = [ field . name for field in instance . _meta . fields ]
if field_name in fields :
return instance . _meta . get_field ( field_name ) . verbose_name
else :
return field_name |
def object_to_dict ( cls , obj ) :
"""This function converts Objects into Dictionary""" | dict_obj = dict ( )
if obj is not None :
if type ( obj ) == list :
dict_list = [ ]
for inst in obj :
dict_list . append ( cls . object_to_dict ( inst ) )
dict_obj [ "list" ] = dict_list
elif not cls . is_primitive ( obj ) :
for key in obj . __dict__ : # is an object
... |
def CoefficientOfNetworkComplexity_metric ( bpmn_graph ) :
"""Returns the value of the Coefficient of Network Complexity metric
( " Ratio of the total number of arcs in a process model to its total number of nodes . " )
for the BPMNDiagramGraph instance .
: param bpmn _ graph : an instance of BpmnDiagramGraph... | return float ( len ( bpmn_graph . get_flows ( ) ) ) / float ( len ( bpmn_graph . get_nodes ( ) ) ) |
def get_symbol_id_map ( self ) :
"""A convenience method to create a mapping between the HGNC
symbols and their identifiers .
: return :""" | symbol_id_map = { }
f = '/' . join ( ( self . rawdir , self . files [ 'genes' ] [ 'file' ] ) )
with open ( f , 'r' , encoding = "utf8" ) as csvfile :
filereader = csv . reader ( csvfile , delimiter = '\t' , quotechar = '\"' )
for row in filereader :
( hgnc_id , symbol , name , locus_group , locus_type ,... |
def PushAttributeContainer ( self , serialized_data ) :
"""Pushes a serialized attribute container onto the list .
Args :
serialized _ data ( bytes ) : serialized attribute container data .""" | self . _list . append ( serialized_data )
self . data_size += len ( serialized_data )
self . next_sequence_number += 1 |
def get_preview_kwargs ( self , ** kwargs ) :
"""Gets the url keyword arguments to pass to the
` preview _ view ` callable . If the ` pass _ through _ kwarg `
attribute is set the value of ` pass _ through _ attr ` will
be looked up on the object .
So if you are previewing an item Obj < id = 2 > and
self ... | if not self . pass_through_kwarg :
return { }
obj = self . get_object ( )
return { self . pass_through_kwarg : getattr ( obj , self . pass_through_attr ) } |
def add ( env , securitygroup_id , network_component , server , interface ) :
"""Attach an interface to a security group .""" | _validate_args ( network_component , server , interface )
mgr = SoftLayer . NetworkManager ( env . client )
component_id = _get_component_id ( env , network_component , server , interface )
ret = mgr . attach_securitygroup_component ( securitygroup_id , component_id )
if not ret :
raise exceptions . CLIAbort ( "Cou... |
def tsToDf ( tso ) :
"""Create Pandas DataFrame from TimeSeries object .
Use : Must first extractTs to get a time series . Then pick one item from time series and pass it through
: param dict tso : Time series entry
: return dict dfs : Pandas dataframes""" | dfs = { }
try :
dfs = ts_to_df ( tso )
except Exception as e :
print ( "Error: Unable to create data frame" )
logger_start . warn ( "ts_to_df: tso malformed: {}" . format ( e ) )
return dfs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.