signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_type_name ( t ) :
"""Get a human - friendly name for the given type .
: type t : type | None
: rtype : unicode""" | # Lookup in the mapping
try :
return __type_names [ t ]
except KeyError : # Specific types
if issubclass ( t , six . integer_types ) :
return _ ( u'Integer number' )
# Get name from the Type itself
return six . text_type ( t . __name__ ) . capitalize ( ) |
def admin_tools_render_menu_css ( context , menu = None ) :
"""Template tag that renders the menu css files , , it takes an optional
` ` Menu ` ` instance as unique argument , if not given , the menu will be
retrieved with the ` ` get _ admin _ menu ` ` function .""" | if menu is None :
menu = get_admin_menu ( context )
context . update ( { 'template' : 'admin_tools/menu/css.html' , 'css_files' : menu . Media . css , } )
return context |
def log_likelihood_of ( self , z ) :
"""log likelihood of the measurement ` z ` . This should only be called
after a call to update ( ) . Calling after predict ( ) will yield an
incorrect result .""" | if z is None :
return log ( sys . float_info . min )
return logpdf ( z , dot ( self . H , self . x ) , self . S ) |
def _match_serializers_by_query_arg ( self , serializers ) :
"""Match serializer by query arg .""" | # if the format query argument is present , match the serializer
arg_name = current_app . config . get ( 'REST_MIMETYPE_QUERY_ARG_NAME' )
if arg_name :
arg_value = request . args . get ( arg_name , None )
if arg_value is None :
return None
# Search for the serializer matching the format
try :
... |
def strip_command ( self , command_string , output ) :
"""Strip command _ string from output string .""" | output_list = output . split ( command_string )
return self . RESPONSE_RETURN . join ( output_list ) |
def dropSpans ( spans , text ) :
"""Drop from text the blocks identified in : param spans : , possibly nested .""" | spans . sort ( )
res = ''
offset = 0
for s , e in spans :
if offset <= s : # handle nesting
if offset < s :
res += text [ offset : s ]
offset = e
res += text [ offset : ]
return res |
def add ( self , name , value ) :
"""Adds a new entry to the table
We reduce the table size if the entry will make the
table size greater than maxsize .""" | # We just clear the table if the entry is too big
size = table_entry_size ( name , value )
if size > self . _maxsize :
self . dynamic_entries . clear ( )
self . _current_size = 0
# Add new entry if the table actually has a size
elif self . _maxsize > 0 :
self . dynamic_entries . appendleft ( ( name , value ... |
def parse_commandline ( argv ) :
"""Returns the arguments parsed from * argv * as a namespace .""" | ap = ArgumentParser ( prog = 'wdiffhtml' , description = DESCRIPTION , epilog = EPILOG , )
ap . add_argument ( '--version' , action = 'version' , version = 'wdiffhtml v{}' . format ( version ) , help = "shows version and exits" )
ap . add_argument ( 'org_file' , metavar = 'FILENAME' , help = "original file" )
ap . add_... |
def absdeg ( deg ) :
'''Change from signed degrees to 0-180 or 0-360 ranges
deg : ndarray
Movement data in pitch , roll , yaw ( degrees )
Returns
deg _ abs : ndarray
Movement translated from - 180:180 / - 90:90 degrees to 0:360/0:180 degrees
Example
deg = numpy . array ( [ - 170 , - 120 , 0 , 90 ] )
... | import numpy
d = numpy . copy ( deg )
if numpy . max ( numpy . abs ( deg ) ) > 90.0 :
d [ deg < 0 ] = 360 + deg [ deg < 0 ]
else :
d [ deg < 0 ] = 180 + deg [ deg < 0 ]
return d |
def getAnalysisKeywords ( self ) :
"""The analysis service keywords found""" | analyses = [ ]
for rows in self . getRawResults ( ) . values ( ) :
for row in rows :
analyses = list ( set ( analyses + row . keys ( ) ) )
return analyses |
def size_on_disk ( self , start_pos = 0 ) :
"""Returns the size of this instruction and its operands when
packed . ` start _ pos ` is required for the ` tableswitch ` and
` lookupswitch ` instruction as the padding depends on alignment .""" | # All instructions are at least 1 byte ( the opcode itself )
size = 1
fmts = opcode_table [ self . opcode ] [ 'operands' ]
if self . wide :
size += 2
# Special case for iinc which has a 2nd extended operand .
if self . opcode == 0x84 :
size += 2
elif fmts : # A simple opcode with simple operands .
... |
def suggest_pairs ( top_n = 10 , per_n = 3 , ignore_before = 300 ) :
"""Find the maximally interesting pairs of players to match up
First , sort the ratings by uncertainty .
Then , take the ten highest players with the highest uncertainty
For each of them , call them ` p1 `
Sort all the models by their dist... | db = sqlite3 . connect ( "ratings.db" )
data = db . execute ( "select model_winner, model_loser from wins" ) . fetchall ( )
bucket_ids = [ id [ 0 ] for id in db . execute ( "select id from models where bucket = ?" , ( fsdb . models_dir ( ) , ) ) . fetchall ( ) ]
bucket_ids . sort ( )
data = [ d for d in data if d [ 0 ]... |
def _parse_request ( self , enc_request , request_cls , service , binding ) :
"""Parse a Request
: param enc _ request : The request in its transport format
: param request _ cls : The type of requests I expect
: param service :
: param binding : Which binding that was used to transport the message
to thi... | _log_info = logger . info
_log_debug = logger . debug
# The addresses I should receive messages like this on
receiver_addresses = self . config . endpoint ( service , binding , self . entity_type )
if not receiver_addresses and self . entity_type == "idp" :
for typ in [ "aa" , "aq" , "pdp" ] :
receiver_addr... |
def portfolio ( weights , latest_prices , min_allocation = 0.01 , total_portfolio_value = 10000 ) :
"""For a long only portfolio , convert the continuous weights to a discrete allocation
in a greedy iterative approach . This can be thought of as a clever way to round
the continuous weights to an integer number ... | if not isinstance ( weights , dict ) :
raise TypeError ( "weights should be a dictionary of {ticker: weight}" )
if not isinstance ( latest_prices , ( pd . Series , dict ) ) :
raise TypeError ( "latest_prices should be a pd.Series" )
if min_allocation > 0.3 :
raise ValueError ( "min_allocation should be a sm... |
def _extract_zip ( archive , dest = None , members = None ) :
"""Extract the ZipInfo object to a real file on the path targetpath .""" | # Python 2.5 compatibility .
dest = dest or os . getcwd ( )
members = members or archive . infolist ( )
for member in members :
if isinstance ( member , basestring ) :
member = archive . getinfo ( member )
_extract_zip_member ( archive , member , dest ) |
def get_historical_output ( self , assessment , options ) :
"""To get output of a historical Assessment
: param assessment : string
: param options : dict""" | responseFormat = None
if options and 'format' in options and options [ 'format' ] is not None :
responseFormat = options [ 'format' ]
options [ 'format' ] = None
url = '/assessment/' + str ( assessment ) + '/output?' + urllib . parse . urlencode ( options )
response = self . http . downstream ( url , responseFo... |
def make_posix ( path ) : # type : ( str ) - > str
"""Convert a path with possible windows - style separators to a posix - style path
( with * * / * * separators instead of * * \\ * * separators ) .
: param Text path : A path to convert .
: return : A converted posix - style path
: rtype : Text
> > > make... | if not isinstance ( path , six . string_types ) :
raise TypeError ( "Expected a string for path, received {0!r}..." . format ( path ) )
starts_with_sep = path . startswith ( os . path . sep )
separated = normalize_path ( path ) . split ( os . path . sep )
if isinstance ( separated , ( list , tuple ) ) :
path = ... |
def users_create_token ( self , user_id = None , username = None , ** kwargs ) :
"""Create a user authentication token .""" | if user_id :
return self . __call_api_post ( 'users.createToken' , userId = user_id , kwargs = kwargs )
elif username :
return self . __call_api_post ( 'users.createToken' , username = username , kwargs = kwargs )
else :
raise RocketMissingParamException ( 'userID or username required' ) |
def _get_bin ( self , key ) :
'''Returns a binned dictionary based on redis zscore
@ return : The sorted dict''' | # keys based on score
sortedDict = { }
# this doesnt return them in order , need to bin first
for item in self . redis_conn . zscan_iter ( key ) :
my_item = ujson . loads ( item [ 0 ] )
# score is negated in redis
my_score = - item [ 1 ]
if my_score not in sortedDict :
sortedDict [ my_score ] = ... |
def check_input_files_for_variadic_seq ( headerDir , sourceDir ) :
"""Checks if files , used as input when pre - processing MPL - containers in their variadic form , need fixing .""" | # Check input files in include / source - directories .
files = glob . glob ( os . path . join ( headerDir , "*.hpp" ) )
files += glob . glob ( os . path . join ( headerDir , "aux_" , "*.hpp" ) )
files += glob . glob ( os . path . join ( sourceDir , "src" , "*" ) )
for currentFile in sorted ( files ) :
if check_hea... |
def setup_legacy_graph_extended ( pants_ignore_patterns , workdir , local_store_dir , build_file_imports_behavior , options_bootstrapper , build_configuration , build_root = None , native = None , glob_match_error_behavior = None , build_ignore_patterns = None , exclude_target_regexps = None , subproject_roots = None ,... | build_root = build_root or get_buildroot ( )
build_configuration = build_configuration or BuildConfigInitializer . get ( options_bootstrapper )
bootstrap_options = options_bootstrapper . bootstrap_options . for_global_scope ( )
build_file_aliases = build_configuration . registered_aliases ( )
rules = build_configuratio... |
def get_top_frame ( self , wb_url , wb_prefix , host_prefix , env , frame_mod , replay_mod , coll = '' , extra_params = None ) :
""": param rewrite . wburl . WbUrl wb _ url : The WbUrl for the request this template is being rendered for
: param str wb _ prefix : The URL prefix pywb is serving the content using ( ... | embed_url = wb_url . to_str ( mod = replay_mod )
if wb_url . timestamp :
timestamp = wb_url . timestamp
else :
timestamp = timestamp_now ( )
is_proxy = 'wsgiprox.proxy_host' in env
params = { 'host_prefix' : host_prefix , 'wb_prefix' : wb_prefix , 'wb_url' : wb_url , 'coll' : coll , 'options' : { 'frame_mod' : ... |
def GetCodeObjectAtLine ( module , line ) :
"""Searches for a code object at the specified line in the specified module .
Args :
module : module to explore .
line : 1 - based line number of the statement .
Returns :
( True , Code object ) on success or ( False , ( prev _ line , next _ line ) ) on
failur... | if not hasattr ( module , '__file__' ) :
return ( False , ( None , None ) )
prev_line = 0
next_line = six . MAXSIZE
for code_object in _GetModuleCodeObjects ( module ) :
for co_line_number in _GetLineNumbers ( code_object ) :
if co_line_number == line :
return ( True , code_object )
... |
def get_scissors_builder ( self ) :
"""Returns an instance of : class : ` ScissorsBuilder ` from the SIGRES file .
Raise :
` RuntimeError ` if SIGRES file is not found .""" | from abipy . electrons . scissors import ScissorsBuilder
if self . sigres_path :
return ScissorsBuilder . from_file ( self . sigres_path )
else :
raise RuntimeError ( "Cannot find SIGRES file!" ) |
async def system_bus_async ( loop = None , ** kwargs ) :
"returns a Connection object for the D - Bus system bus ." | return Connection ( await dbus . Connection . bus_get_async ( DBUS . BUS_SYSTEM , private = False , loop = loop ) ) . register_additional_standard ( ** kwargs ) |
def digits ( number , base = 10 ) :
"""Determines the number of digits of a number in a specific base .
Args :
number ( int ) : An integer number represented in base 10.
base ( int ) : The base to find the number of digits .
Returns :
Number of digits when represented in a particular base ( integer ) .
... | if number < 1 :
return 0
digits = 0
n = 1
while ( number >= 1 ) :
number //= base
digits += 1
return digits |
def sections ( self ) :
"""Returns a list of all media sections in this library . Library sections may be any of
: class : ` ~ plexapi . library . MovieSection ` , : class : ` ~ plexapi . library . ShowSection ` ,
: class : ` ~ plexapi . library . MusicSection ` , : class : ` ~ plexapi . library . PhotoSection ... | key = '/library/sections'
sections = [ ]
for elem in self . _server . query ( key ) :
for cls in ( MovieSection , ShowSection , MusicSection , PhotoSection ) :
if elem . attrib . get ( 'type' ) == cls . TYPE :
section = cls ( self . _server , elem , key )
self . _sectionsByID [ secti... |
def create_training_job ( self , TrainingJobName , AlgorithmSpecification , OutputDataConfig , ResourceConfig , InputDataConfig = None , ** kwargs ) :
"""Create a training job in Local Mode
Args :
TrainingJobName ( str ) : local training job name .
AlgorithmSpecification ( dict ) : Identifies the training alg... | InputDataConfig = InputDataConfig or { }
container = _SageMakerContainer ( ResourceConfig [ 'InstanceType' ] , ResourceConfig [ 'InstanceCount' ] , AlgorithmSpecification [ 'TrainingImage' ] , self . sagemaker_session )
training_job = _LocalTrainingJob ( container )
hyperparameters = kwargs [ 'HyperParameters' ] if 'Hy... |
def authorize ( self , scope = None , redirect_uri = None , state = None ) :
"""Redirect to GitHub and request access to a user ' s data .
: param scope : List of ` Scopes ` _ for which to request access , formatted
as a string or comma delimited list of scopes as a
string . Defaults to ` ` None ` ` , resulti... | _logger . debug ( "Called authorize()" )
params = { 'client_id' : self . client_id }
if scope :
params [ 'scope' ] = scope
if redirect_uri :
params [ 'redirect_uri' ] = redirect_uri
if state :
params [ 'state' ] = state
url = self . auth_url + 'authorize?' + urlencode ( params )
_logger . debug ( "Redirecti... |
def _chunk_query ( l , n , cn , conn , table , db_type ) :
"""Call for inserting SQL query in chunks based on n rows
Args :
l ( list ) : List of tuples
n ( int ) : Number of rows
cn ( str ) : Column names
conn ( connection object ) : Database connection object
table ( str ) : Table name
db _ type ( st... | # For item i in a range that is a length of l ,
[ insert_query_m ( l [ i : i + n ] , table , conn , cn , db_type ) for i in range ( 0 , len ( l ) , n ) ] |
def generic_add ( a , b ) :
print
"""Simple function to add two numbers""" | logger . info ( 'Called generic_add({}, {})' . format ( a , b ) )
return a + b |
def xml_request ( check_object = False , check_invalid_data_mover = False ) :
"""indicate the return value is a xml api request
: param check _ invalid _ data _ mover :
: param check _ object :
: return : the response of this request""" | def decorator ( f ) :
@ functools . wraps ( f )
def func_wrapper ( self , * argv , ** kwargs ) :
request = f ( self , * argv , ** kwargs )
return self . request ( request , check_object = check_object , check_invalid_data_mover = check_invalid_data_mover )
return func_wrapper
return decorato... |
def valid_project ( self ) :
"""Handle an invalid active project .""" | try :
path = self . projects . get_active_project_path ( )
except AttributeError :
return
if bool ( path ) :
if not self . projects . is_valid_project ( path ) :
if path :
QMessageBox . critical ( self , _ ( 'Error' ) , _ ( "<b>{}</b> is no longer a valid Spyder project! " "Since it is t... |
async def set_default_min_hwe_kernel ( cls , version : typing . Optional [ str ] ) :
"""See ` get _ default _ min _ hwe _ kernel ` .""" | await cls . set_config ( "default_min_hwe_kernel" , "" if version is None else version ) |
def _highlight_lines ( self , tokensource ) :
"""Highlighted the lines specified in the ` hl _ lines ` option by
post - processing the token stream coming from ` _ format _ lines ` .""" | hls = self . hl_lines
for i , ( t , value ) in enumerate ( tokensource ) :
if t != 1 :
yield t , value
if i + 1 in hls : # i + 1 because Python indexes start at 0
if self . noclasses :
style = ''
if self . style . highlight_color is not None :
style = ( ' ... |
def matrix ( df , filter = None , n = 0 , p = 0 , sort = None , figsize = ( 25 , 10 ) , width_ratios = ( 15 , 1 ) , color = ( 0.25 , 0.25 , 0.25 ) , fontsize = 16 , labels = None , sparkline = True , inline = False , freq = None ) :
"""A matrix visualization of the nullity of the given DataFrame .
For optimal per... | df = nullity_filter ( df , filter = filter , n = n , p = p )
df = nullity_sort ( df , sort = sort )
height = df . shape [ 0 ]
width = df . shape [ 1 ]
# z is the color - mask array , g is a NxNx3 matrix . Apply the z color - mask to set the RGB of each pixel .
z = df . notnull ( ) . values
g = np . zeros ( ( height , w... |
def getContactItems ( self , person ) :
"""Return a C { list } of the L { Notes } items associated with the given
person . If none exist , create one , wrap it in a list and return it .
@ type person : L { Person }""" | notes = list ( person . store . query ( Notes , Notes . person == person ) )
if not notes :
return [ Notes ( store = person . store , person = person , notes = u'' ) ]
return notes |
def patched_get_current ( self , request = None ) :
"""Monkey patched version of Django ' s SiteManager . get _ current ( ) function .
Returns the current Site based on a given request or the SITE _ ID in
the project ' s settings . If a request is given attempts to match a site
with domain matching request . ... | # Imported here to avoid circular import
from django . conf import settings
if request :
try :
return self . _get_site_by_request ( request )
# pylint : disable = protected - access
except Site . DoesNotExist :
pass
if getattr ( settings , 'SITE_ID' , '' ) :
return self . _get_site_b... |
def _update_data_dict ( self , data_dict , back_or_front ) :
"""Adds spct if relevant , adds service""" | data_dict [ 'back_or_front' ] = back_or_front
# The percentage of used sessions based on ' scur ' and ' slim '
if 'slim' in data_dict and 'scur' in data_dict :
try :
data_dict [ 'spct' ] = ( data_dict [ 'scur' ] / data_dict [ 'slim' ] ) * 100
except ( TypeError , ZeroDivisionError ) :
pass |
def getall ( fn , page = None , * args , ** kwargs ) :
"""Auto - iterate over the paginated results of various methods of the API .
Pass the GitLabAPI method as the first argument , followed by the
other parameters as normal . Include ` page ` to determine first page to poll .
Remaining kwargs are passed on t... | if not page :
page = 1
while True :
results = fn ( * args , page = page , ** kwargs )
if not results :
break
for x in results :
yield x
page += 1 |
def _posix_split_name ( self , name ) :
"""Split a name longer than 100 chars into a prefix
and a name part .""" | prefix = name [ : LENGTH_PREFIX + 1 ]
while prefix and prefix [ - 1 ] != "/" :
prefix = prefix [ : - 1 ]
name = name [ len ( prefix ) : ]
prefix = prefix [ : - 1 ]
if not prefix or len ( name ) > LENGTH_NAME :
raise ValueError ( "name is too long" )
return prefix , name |
def unparse_color ( r , g , b , a , type ) :
"""Take the r , g , b , a color values and give back
a type css color string . This is the inverse function of parse _ color""" | if type == '#rgb' : # Don ' t lose precision on rgb shortcut
if r % 17 == 0 and g % 17 == 0 and b % 17 == 0 :
return '#%x%x%x' % ( int ( r / 17 ) , int ( g / 17 ) , int ( b / 17 ) )
type = '#rrggbb'
if type == '#rgba' :
if r % 17 == 0 and g % 17 == 0 and b % 17 == 0 :
return '#%x%x%x%x' % ( ... |
def minify_js_files ( ) :
"""This command minified js files with UglifyJS""" | for k , v in JS_FILE_MAPPING . items ( ) :
input_files = " " . join ( v [ "input_files" ] )
output_file = v [ "output_file" ]
uglifyjs_command = "uglifyjs {input_files} -o {output_file}" . format ( input_files = input_files , output_file = output_file )
local ( uglifyjs_command ) |
def to_json ( self ) :
"""Return a ` dict ` representation of the resource , including all properties and tags
Returns :
` dict `""" | return { 'resourceType' : self . resource . resource_type_id , 'resourceId' : self . id , 'accountId' : self . resource . account_id , 'account' : self . account , 'location' : self . resource . location , 'properties' : { to_camelcase ( prop . name ) : prop . value for prop in self . resource . properties } , 'tags' :... |
def parse_argv ( ) :
"""Parse command line arguments . Settings will be stored in the global
variables declared above .""" | parser = argparse . ArgumentParser ( description = 'Find lyrics for a set of mp3' ' files and embed them as metadata' )
parser . add_argument ( '-j' , '--jobs' , help = 'Number of parallel processes' , type = int , metavar = 'N' , default = 1 )
parser . add_argument ( '-o' , '--overwrite' , help = 'Overwrite lyrics of ... |
def getid ( self , ref ) :
"""Obtain the reference number of the vgroup following the
vgroup with the given reference number .
Args : :
ref reference number of the vgroup after which to search ;
set to - 1 to start the search at the start of
the HDF file
Returns : :
reference number of the vgroup past... | num = _C . Vgetid ( self . _hdf_inst . _id , ref )
_checkErr ( 'getid' , num , "bad arguments or last vgroup reached" )
return num |
def get_trace_id ( ) :
"""Helper to get trace _ id from web application request header .
: rtype : str
: returns : TraceID in HTTP request headers .""" | checkers = ( get_trace_id_from_django , get_trace_id_from_flask , get_trace_id_from_webapp2 , )
for checker in checkers :
trace_id = checker ( )
if trace_id is not None :
return trace_id
return None |
def power ( base , exp ) :
"""Returns result of first array elements raised to powers from second array , element - wise
with broadcasting .
Equivalent to ` ` base * * exp ` ` and ` ` mx . nd . broadcast _ power ( lhs , rhs ) ` ` .
. . note : :
If the corresponding dimensions of two arrays have the same siz... | # pylint : disable = no - member , protected - access
return _ufunc_helper ( base , exp , op . broadcast_power , operator . pow , _internal . _power_scalar , _internal . _rpower_scalar ) |
def parse_friends ( self , friends_page ) :
"""Parses the DOM and returns user friends attributes .
: type friends _ page : : class : ` bs4 . BeautifulSoup `
: param friends _ page : MAL user friends page ' s DOM
: rtype : dict
: return : User friends attributes .""" | user_info = self . parse_sidebar ( friends_page )
second_col = friends_page . find ( u'div' , { u'id' : u'content' } ) . find ( u'table' ) . find ( u'tr' ) . find_all ( u'td' , recursive = False ) [ 1 ]
try :
user_info [ u'friends' ] = { }
friends = second_col . find_all ( u'div' , { u'class' : u'friendHolder' ... |
def find_additional_rels ( self , all_models ) :
"""Attempts to scan for additional relationship fields for this model based on all of the other models '
structures and relationships .""" | for model_name , model in iteritems ( all_models ) :
if model_name != self . name :
for field_name in model . field_names :
field = model . fields [ field_name ]
# if this field type references the current model
if field . field_type == self . name and field . back_popula... |
def get_hypo_location ( self , mesh_spacing , hypo_loc = None ) :
"""The method determines the location of the hypocentre within the rupture
: param mesh :
: class : ` ~ openquake . hazardlib . geo . mesh . Mesh ` of points
: param mesh _ spacing :
The desired distance between two adjacent points in source ... | mesh = self . mesh
centroid = mesh . get_middle_point ( )
if hypo_loc is None :
return centroid
total_len_y = ( len ( mesh . depths ) - 1 ) * mesh_spacing
y_distance = hypo_loc [ 1 ] * total_len_y
y_node = int ( numpy . round ( y_distance / mesh_spacing ) )
total_len_x = ( len ( mesh . lons [ y_node ] ) - 1 ) * mes... |
def unparse ( self , dn , record ) :
"""Write an entry or change record to the output file .
: type dn : string
: param dn : distinguished name
: type record : Union [ Dict [ string , List [ string ] ] , List [ Tuple ] ]
: param record : Either a dictionary holding an entry or a list of
additions ( 2 - tu... | self . _unparse_attr ( 'dn' , dn )
if isinstance ( record , dict ) :
self . _unparse_entry_record ( record )
elif isinstance ( record , list ) :
self . _unparse_change_record ( record )
else :
raise ValueError ( "Argument record must be dictionary or list" )
self . _output_file . write ( self . _line_sep )
... |
def open_and_reorient_image ( handle ) :
"""Load the image from the specified file and orient the image accordingly
to the Exif tag that the file might embed , which would indicate the
orientation of the camera relative to the captured scene .
@ param handle : a Python file object .
@ return : an instance r... | # Retrieve tags from the Exchangeable image file format ( Exif )
# included in the picture . If the orientation of the picture is not
# top left side , rotate it accordingly .
# @ deprecated
# exif _ tags = dict ( [ ( exif _ tag . tag , exif _ tag )
# for exif _ tag in exif . process _ file ( handle ) . itervalues ( )
... |
def copy ( self ) :
"""Returns a new copy of a C { ParseResults } object .""" | ret = ParseResults ( self . __toklist )
ret . __tokdict = self . __tokdict . copy ( )
ret . __parent = self . __parent
ret . __accumNames . update ( self . __accumNames )
ret . __name = self . __name
return ret |
def _Dispatch ( ps , server , SendResponse , SendFault , post , action , nsdict = { } , ** kw ) :
'''Send ParsedSoap instance to ServiceContainer , which dispatches to
appropriate service via post , and method via action . Response is a
self - describing pyobj , which is passed to a SoapWriter .
Call SendResp... | localURL = 'http://%s:%d%s' % ( server . server_name , server . server_port , post )
address = action
service = server . getNode ( post )
isWSResource = False
if isinstance ( service , WSAResource ) :
isWSResource = True
service . setServiceURL ( localURL )
address = Address ( )
try :
address . ... |
def generator ( name ) :
"""Return generator by its name
: param name : name of hash - generator
: return : WHashGeneratorProto class""" | name = name . upper ( )
if name not in WHash . __hash_map__ . keys ( ) :
raise ValueError ( 'Hash generator "%s" not available' % name )
return WHash . __hash_map__ [ name ] |
def _get_action ( self , action_meta ) :
'''Parse action and turn into a calling point .
: param action _ meta :
: return :''' | conf = { 'fun' : list ( action_meta . keys ( ) ) [ 0 ] , 'arg' : [ ] , 'kwargs' : { } , }
if not len ( conf [ 'fun' ] . split ( '.' ) ) - 1 :
conf [ 'salt.int.intfunc' ] = True
action_meta = action_meta [ conf [ 'fun' ] ]
info = action_meta . get ( 'info' , 'Action for {}' . format ( conf [ 'fun' ] ) )
for arg in a... |
def AQLQuery ( self , query , batchSize = 100 , rawResults = False , bindVars = { } , options = { } , count = False , fullCount = False , json_encoder = None , ** moreArgs ) :
"""Set rawResults = True if you want the query to return dictionnaries instead of Document objects .
You can use * * moreArgs to pass more... | return AQLQuery ( self , query , rawResults = rawResults , batchSize = batchSize , bindVars = bindVars , options = options , count = count , fullCount = fullCount , json_encoder = json_encoder , ** moreArgs ) |
def set_reference ( self , ref ) :
"""Set the reference sequence
: param ref : reference sequence
: type ref : string""" | self . _options = self . _options . _replace ( reference = ref ) |
def get_vbox_version ( config_kmk ) :
"Return the vbox config major , minor , build" | with open ( config_kmk , 'rb' ) as f :
config = f . read ( )
major = b"6"
# re . search ( b " VBOX _ VERSION _ MAJOR = ( ? P < major > [ \ d ] ) " , config ) . groupdict ( ) [ ' major ' ]
minor = b"0"
# re . search ( b " VBOX _ VERSION _ MINOR = ( ? P < minor > [ \ d ] ) " , config ) . groupdict ( ) [ ' minor ' ]
b... |
def export ( self , name , columns , points ) :
"""Write the points to the CouchDB server .""" | logger . debug ( "Export {} stats to CouchDB" . format ( name ) )
# Create DB input
data = dict ( zip ( columns , points ) )
# Set the type to the current stat name
data [ 'type' ] = name
data [ 'time' ] = couchdb . mapping . DateTimeField ( ) . _to_json ( datetime . now ( ) )
# Write input to the CouchDB database
# Re... |
def __log ( self , method_name ) :
"""Logs the deprecation message on first call , does nothing after
: param method _ name : Name of the deprecated method""" | if not self . __already_logged : # Print only if not already done
stack = "\n\t" . join ( traceback . format_stack ( ) )
logging . getLogger ( self . __logger ) . warning ( "%s: %s\n%s" , method_name , self . __message , stack )
self . __already_logged = True |
def plot_violin ( data , var_names = None , quartiles = True , credible_interval = 0.94 , shade = 0.35 , bw = 4.5 , sharey = True , figsize = None , textsize = None , ax = None , kwargs_shade = None , ) :
"""Plot posterior of traces as violin plot .
Notes
If multiple chains are provided for a variable they will... | data = convert_to_dataset ( data , group = "posterior" )
var_names = _var_names ( var_names , data )
plotters = list ( xarray_var_iter ( data , var_names = var_names , combined = True ) )
if kwargs_shade is None :
kwargs_shade = { }
( figsize , ax_labelsize , _ , xt_labelsize , linewidth , _ ) = _scale_fig_size ( f... |
def idx_num_to_name ( L ) :
"""Switch from index - by - number to index - by - name .
: param dict L : Metadata
: return dict L : Metadata""" | logger_jsons . info ( "enter idx_num_to_name" )
try :
if "paleoData" in L :
L [ "paleoData" ] = _import_data ( L [ "paleoData" ] , "paleo" )
if "chronData" in L :
L [ "chronData" ] = _import_data ( L [ "chronData" ] , "chron" )
except Exception as e :
logger_jsons . error ( "idx_num_to_name:... |
def get_referenced_object_as_list ( prev_obj , obj , dot_separated_name , desired_type = None ) :
"""Same as get _ referenced _ object , but always returns a list .
Args :
prev _ obj : see get _ referenced _ object
obj : see get _ referenced _ object
dot _ separated _ name : see get _ referenced _ object
... | res = get_referenced_object ( prev_obj , obj , dot_separated_name , desired_type )
if res is None :
return [ ]
elif type ( res ) is list :
return res
else :
return [ res ] |
def from_origin_axis_angle ( origin , axis , angle , angle_in_radians = False ) :
"""Generates a SymmOp for a rotation about a given axis through an
origin .
Args :
origin ( 3x1 array ) : The origin which the axis passes through .
axis ( 3x1 array ) : The axis of rotation in cartesian space . For
example ... | theta = angle * pi / 180 if not angle_in_radians else angle
a = origin [ 0 ]
b = origin [ 1 ]
c = origin [ 2 ]
u = axis [ 0 ]
v = axis [ 1 ]
w = axis [ 2 ]
# Set some intermediate values .
u2 = u * u
v2 = v * v
w2 = w * w
cos_t = cos ( theta )
sin_t = sin ( theta )
l2 = u2 + v2 + w2
l = sqrt ( l2 )
# Build the matrix e... |
def attribute ( self ) :
"""Attribute that serves as a reference getter""" | refs = re . findall ( "\@([a-zA-Z:]+)=\\\?[\'\"]\$" + str ( self . refsDecl . count ( "$" ) ) + "\\\?[\'\"]" , self . refsDecl )
return refs [ - 1 ] |
def _restore ( name , fields , value ) :
"""Restore an object of namedtuple""" | k = ( name , fields )
cls = __cls . get ( k )
if cls is None :
cls = collections . namedtuple ( name , fields )
__cls [ k ] = cls
return cls ( * value ) |
def unlock ( arguments ) :
"""Unlock the database .""" | import redis
u = coil . utils . ask ( "Redis URL" , "redis://localhost:6379/0" )
db = redis . StrictRedis . from_url ( u )
db . set ( 'site:lock' , 0 )
print ( "Database unlocked." )
return 0 |
def _detect ( self , min_length , max_length , tail = False ) :
"""Detect the head or tail within ` ` min _ length ` ` and ` ` max _ length ` ` duration .
If detecting the tail , the real wave MFCC and the query are reversed
so that the tail detection problem reduces to a head detection problem .
Return the d... | def _sanitize ( value , default , name ) :
if value is None :
value = default
try :
value = TimeValue ( value )
except ( TypeError , ValueError , InvalidOperation ) as exc :
self . log_exc ( u"The value of %s is not a number" % ( name ) , exc , True , TypeError )
if value < 0 :
... |
def run_script ( config , output_dir , accounts , tags , region , echo , serial , script_args ) :
"""run an aws script across accounts""" | # TODO count up on success / error / error list by account
accounts_config , custodian_config , executor = init ( config , None , serial , True , accounts , tags , ( ) , ( ) )
if echo :
print ( "command to run: `%s`" % ( " " . join ( script_args ) ) )
return
# Support fully quoted scripts , which are common to ... |
def changeHS ( self ) :
"""Change health system interventions
https : / / github . com / SwissTPH / openmalaria / wiki / GeneratedSchema32Doc # change - health - system
Returns : list of HealthSystems together with timestep when they are applied""" | health_systems = [ ]
change_hs = self . et . find ( "changeHS" )
if change_hs is None :
return health_systems
for health_system in change_hs . findall ( "timedDeployment" ) :
health_systems . append ( [ int ( health_system . attrib ( "time" ) ) , HealthSystem ( self . et ) ] )
return health_systems |
def _get_colors ( self , color_set , alpha , off_color , custom_colors = { } ) :
"""assign colors according to the surface energies of on _ wulff facets .
return :
( color _ list , color _ proxy , color _ proxy _ on _ wulff , miller _ on _ wulff ,
e _ surf _ on _ wulff _ list )""" | import matplotlib as mpl
import matplotlib . pyplot as plt
color_list = [ off_color ] * len ( self . hkl_list )
color_proxy_on_wulff = [ ]
miller_on_wulff = [ ]
e_surf_on_wulff = [ ( i , e_surf ) for i , e_surf in enumerate ( self . e_surf_list ) if self . on_wulff [ i ] ]
c_map = plt . get_cmap ( color_set )
e_surf_on... |
def get_self_uri ( self , content_type ) :
"return the first self uri with the content _ type" | try :
return [ self_uri for self_uri in self . self_uri_list if self_uri . content_type == content_type ] [ 0 ]
except IndexError :
return None |
def text_to_speech ( text , synthesizer , synth_args , sentence_break ) :
"""Converts given text to a pydub AudioSegment using a specified speech
synthesizer . At the moment , IBM Watson ' s text - to - speech API is the only
available synthesizer .
: param text :
The text that will be synthesized to audio ... | if len ( text . split ( ) ) < 50 :
if synthesizer == 'watson' :
with open ( '.temp.wav' , 'wb' ) as temp :
temp . write ( watson_request ( text = text , synth_args = synth_args ) . content )
response = AudioSegment . from_wav ( '.temp.wav' )
os . remove ( '.temp.wav' )
re... |
def check_need_install ( ) :
"""Check if installed package are exactly the same to this one .
By checking md5 value of all files .""" | need_install_flag = False
for root , _ , basename_list in os . walk ( SRC ) :
if os . path . basename ( root ) != "__pycache__" :
for basename in basename_list :
src = os . path . join ( root , basename )
dst = os . path . join ( root . replace ( SRC , DST ) , basename )
... |
def func_globals_inject ( func , ** overrides ) :
'''Override specific variables within a function ' s global context .''' | # recognize methods
if hasattr ( func , 'im_func' ) :
func = func . __func__
# Get a reference to the function globals dictionary
func_globals = func . __globals__
# Save the current function globals dictionary state values for the
# overridden objects
injected_func_globals = [ ]
overridden_func_globals = { }
for o... |
def zone_delete ( name , resource_group , ** kwargs ) :
'''. . versionadded : : Fluorine
Delete a DNS zone within a resource group .
: param name : The name of the DNS zone to delete .
: param resource _ group : The name of the resource group .
CLI Example :
. . code - block : : bash
salt - call azurear... | result = False
dnsconn = __utils__ [ 'azurearm.get_client' ] ( 'dns' , ** kwargs )
try :
zone = dnsconn . zones . delete ( zone_name = name , resource_group_name = resource_group , if_match = kwargs . get ( 'if_match' ) )
zone . wait ( )
result = True
except CloudError as exc :
__utils__ [ 'azurearm.log... |
def In ( self , * values ) :
"""Sets the type of the WHERE clause as " in " .
Args :
* values : The values to be used in the WHERE condition .
Returns :
The query builder that this WHERE builder links to .""" | self . _awql = self . _CreateMultipleValuesCondition ( values , 'IN' )
return self . _query_builder |
def createArgumentParser ( description ) :
"""Create an argument parser""" | parser = argparse . ArgumentParser ( description = description , formatter_class = SortedHelpFormatter )
return parser |
def call ( self , command , * args ) :
"""Passes an arbitrary command to the coin daemon .
Args :
command ( str ) : command to be sent to the coin daemon""" | return self . rpc . call ( str ( command ) , * args ) |
def store_password ( params , password ) :
"""Store the password for a database connection using : mod : ` keyring `
Use the ` ` user ` ` field as the user name and ` ` < host > : < driver > ` ` as service name .
Args :
params ( dict ) : database configuration , as defined in : mod : ` ozelot . config `
pas... | user_name = params [ 'user' ]
service_name = params [ 'host' ] + ':' + params [ 'driver' ]
keyring . set_password ( service_name = service_name , username = user_name , password = password ) |
def get_default ( self , section , option ) :
"""Get Default value for a given ( section , option )
- > useful for type checking in ' get ' method""" | section = self . _check_section_option ( section , option )
for sec , options in self . defaults :
if sec == section :
if option in options :
return options [ option ]
else :
return NoDefault |
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 : FlowContext for this FlowInstance
: rtype : twilio . rest . studio . v1 . flow . FlowContext""" | if self . _context is None :
self . _context = FlowContext ( self . _version , sid = self . _solution [ 'sid' ] , )
return self . _context |
def decode_tag ( stream ) :
"""Decode a tag value from a serialized stream .
: param stream : Source data stream
: type stream : io . BytesIO
: returns : Decoded tag
: rtype : bytes""" | ( reserved , tag ) = unpack_value ( ">cc" , stream )
if reserved != b"\x00" :
raise DeserializationError ( "Invalid tag: reserved byte is not null" )
return tag |
def add_kirbi ( self , krbcred , override_pp = True , include_expired = False ) :
c = Credential ( )
enc_credinfo = EncKrbCredPart . load ( krbcred [ 'enc-part' ] [ 'cipher' ] ) . native
ticket_info = enc_credinfo [ 'ticket-info' ] [ 0 ]
"""if ticket _ info [ ' endtime ' ] < datetime . datetime . now ( ... | c . client = CCACHEPrincipal . from_asn1 ( ticket_info [ 'pname' ] , ticket_info [ 'prealm' ] )
if override_pp == True :
self . primary_principal = c . client
# yaaaaay 4 additional weirdness ! ! ! !
# if sname name - string contains a realm as well htne impacket will crash miserably : (
if len ( ticket_info [ 'sna... |
def cmd_dhcp_starvation ( iface , timeout , sleeptime , verbose ) :
"""Send multiple DHCP requests from forged MAC addresses to
fill the DHCP server leases .
When all the available network addresses are assigned , the DHCP server don ' t send responses .
So , some attacks , like DHCP spoofing , can be made . ... | conf . verb = False
if iface :
conf . iface = iface
conf . checkIPaddr = False
ether = Ether ( dst = "ff:ff:ff:ff:ff:ff" )
ip = IP ( src = "0.0.0.0" , dst = "255.255.255.255" )
udp = UDP ( sport = 68 , dport = 67 )
dhcp = DHCP ( options = [ ( "message-type" , "discover" ) , "end" ] )
while True :
bootp = BOOTP ... |
def text_to_url ( self , text ) :
"""Convert text address into QUrl object""" | if text . startswith ( '/' ) :
text = text [ 1 : ]
return QUrl ( self . home_url . toString ( ) + text + '.html' ) |
def commit ( self , message , parent_commits = None , head = True , author = None , committer = None , author_date = None , commit_date = None , skip_hooks = False ) :
"""Commit the current default index file , creating a commit object .
For more information on the arguments , see tree . commit .
: note : If yo... | if not skip_hooks :
run_commit_hook ( 'pre-commit' , self )
self . _write_commit_editmsg ( message )
run_commit_hook ( 'commit-msg' , self , self . _commit_editmsg_filepath ( ) )
message = self . _read_commit_editmsg ( )
self . _remove_commit_editmsg ( )
tree = self . write_tree ( )
rval = Commit . ... |
def loadSettings ( self ) :
"""Load window state from self . settings""" | self . settings . beginGroup ( 'rampviewer' )
geometry = self . settings . value ( 'geometry' ) . toByteArray ( )
self . settings . endGroup ( )
self . restoreGeometry ( geometry ) |
def main ( ) :
"""Entry point when module is run from command line""" | parser = argparse . ArgumentParser ( description = 'Run the chaid algorithm on a' ' csv/sav file.' )
parser . add_argument ( 'file' )
parser . add_argument ( 'dependent_variable' , nargs = 1 )
parser . add_argument ( '--dependent-variable-type' , type = str )
var = parser . add_argument_group ( 'Independent Variable Sp... |
def update ( self , role_sid = values . unset , attributes = values . unset , friendly_name = values . unset ) :
"""Update the UserInstance
: param unicode role _ sid : The SID id of the Role assigned to this user
: param unicode attributes : A valid JSON string that contains application - specific data
: par... | return self . _proxy . update ( role_sid = role_sid , attributes = attributes , friendly_name = friendly_name , ) |
def scopes ( self , ** kwargs ) :
"""Scopes associated to the team .""" | return self . _client . scopes ( team = self . id , ** kwargs ) |
def element_should_exist ( self , json_string , expr ) :
"""Check the existence of one or more elements , matching [ http : / / jsonselect . org / | JSONSelect ] expression .
* DEPRECATED * JSON Select query language is outdated and not supported any more .
Use other keywords of this library to query JSON .
*... | value = self . select_elements ( json_string , expr )
if value is None :
raise JsonValidatorError ( 'Elements %s does not exist' % expr ) |
def generate ( organization , package , destination ) :
"""Generates the Sphinx configuration and Makefile .
Args :
organization ( str ) : the organization name .
package ( str ) : the package to be documented .
destination ( str ) : the destination directory .""" | gen = ResourceGenerator ( organization , package )
tmp = tempfile . NamedTemporaryFile ( mode = 'w+t' , delete = False )
try :
tmp . write ( gen . conf ( ) )
finally :
tmp . close ( )
shutil . copy ( tmp . name , os . path . join ( destination , 'conf.py' ) )
tmp = tempfile . NamedTemporaryFile ( mode = 'w+t' ,... |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'global_' ) and self . global_ is not None :
_dict [ 'global' ] = self . global_ . _to_dict ( )
if hasattr ( self , 'skills' ) and self . skills is not None :
_dict [ 'skills' ] = self . skills . _to_dict ( )
return _dict |
def _method_ ( name ) :
"""getter factory""" | def _getter_ ( self ) :
return getattr ( self , self . get_private_name ( name ) )
return _getter_ |
def get_data ( name , train_batch_size , test_batch_size ) :
"""Gets training and testing dataset iterators .
Args :
name : String . Name of dataset , either ' mnist ' or ' cifar10 ' .
train _ batch _ size : Integer . Batch size for training .
test _ batch _ size : Integer . Batch size for testing .
Retur... | if name not in [ 'mnist' , 'cifar10' ] :
raise ValueError ( 'Expected dataset \'mnist\' or \'cifar10\', but got %s' % name )
dataset = getattr ( tf . keras . datasets , name )
num_classes = 10
# Extract the raw data .
raw_data = dataset . load_data ( )
( images_train , labels_train ) , ( images_test , labels_test )... |
def _parse_array ( value ) :
"""Coerce value into an list .
: param str value : Value to parse .
: returns : list or None if the value is not a JSON array
: raises : TypeError or ValueError if value appears to be an array but can ' t
be parsed as JSON .""" | value = value . lstrip ( )
if not value or value [ 0 ] not in _bracket_strings :
return None
return json . loads ( value ) |
def add_backend ( self , backend ) :
"Add a RapidSMS backend to this tenant" | if backend in self . get_backends ( ) :
return
backend_link , created = BackendLink . all_tenants . get_or_create ( backend = backend )
self . backendlink_set . add ( backend_link ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.