signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def save_related ( self , request , form , formsets , change ) :
"""Given the ` ` HttpRequest ` ` , the parent ` ` ModelForm ` ` instance , the
list of inline formsets and a boolean value based on whether the
parent is being added or changed , save the related objects to the
database . Note that at this point... | form . save_m2m ( )
for formset in formsets :
self . save_formset ( request , form , formset , change = change ) |
def _FormatMessage ( template , parameters ) :
"""Formats the message . Unescapes ' $ $ ' with ' $ ' .
Args :
template : message template ( e . g . ' a = $ 0 , b = $ 1 ' ) .
parameters : substitution parameters for the format .
Returns :
Formatted message with parameters embedded in template placeholders ... | def GetParameter ( m ) :
try :
return parameters [ int ( m . group ( 0 ) [ 1 : ] ) ]
except IndexError :
return INVALID_EXPRESSION_INDEX
parts = template . split ( '$$' )
return '$' . join ( re . sub ( r'\$\d+' , GetParameter , part ) for part in parts ) |
def put ( self , device_id : int ) -> Device :
"""Updates the Device Resource with the
name .""" | device = self . _get_or_abort ( device_id )
self . update ( device )
session . commit ( )
session . add ( device )
return device |
def normalize_pts ( pts , ymax , scaler = 2 ) :
"""scales all coordinates and flip y axis due to different
origin coordinates ( top left vs . bottom left )""" | return [ ( x * scaler , ymax - ( y * scaler ) ) for x , y in pts ] |
def rfft2d_freqs ( h , w ) :
"""Computes 2D spectrum frequencies .""" | fy = np . fft . fftfreq ( h ) [ : , None ]
# when we have an odd input dimension we need to keep one additional
# frequency and later cut off 1 pixel
if w % 2 == 1 :
fx = np . fft . fftfreq ( w ) [ : w // 2 + 2 ]
else :
fx = np . fft . fftfreq ( w ) [ : w // 2 + 1 ]
return np . sqrt ( fx * fx + fy * fy ) |
def samples ( self , nsamples , rstate = None ) :
"""Draw ` nsamples ` samples randomly distributed within the unit cube .
Returns
x : ` ~ numpy . ndarray ` with shape ( nsamples , ndim )
A collection of coordinates within the unit cube .""" | if rstate is None :
rstate = np . random
xs = np . array ( [ self . sample ( rstate = rstate ) for i in range ( nsamples ) ] )
return xs |
def hist ( self , dimension = None , num_bins = 20 , bin_range = None , adjoin = True , ** kwargs ) :
"""Computes and adjoins histogram along specified dimension ( s ) .
Defaults to first value dimension if present otherwise falls
back to first key dimension .
Args :
dimension : Dimension ( s ) to compute h... | from . . operation import histogram
if not isinstance ( dimension , list ) :
dimension = [ dimension ]
hists = [ ]
for d in dimension [ : : - 1 ] :
hist = histogram ( self , num_bins = num_bins , bin_range = bin_range , dimension = d , ** kwargs )
hists . append ( hist )
if adjoin :
layout = self
fo... |
def certificate ( self , certificate ) :
"""Sets the certificate of this V1beta1CertificateSigningRequestStatus .
If request was approved , the controller will place the issued certificate here . # noqa : E501
: param certificate : The certificate of this V1beta1CertificateSigningRequestStatus . # noqa : E501
... | if certificate is not None and not re . search ( r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$' , certificate ) : # noqa : E501
raise ValueError ( r"Invalid value for `certificate`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`" ... |
def _set_site ( self , v , load = False ) :
"""Setter method for site , mapped from YANG variable / overlay _ gateway / site ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ site is considered as a private
method . Backends looking to populate this variable sh... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "name" , site . site , yang_name = "site" , rest_name = "site" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys = 'name' , extensions = { u'tailf-co... |
def is45 ( msg ) :
"""Check if a message is likely to be BDS code 4,5.
Meteorological hazard report
Args :
msg ( String ) : 28 bytes hexadecimal message string
Returns :
bool : True or False""" | if allzeros ( msg ) :
return False
d = hex2bin ( data ( msg ) )
# status bit 1 , 4 , 7 , 10 , 13 , 16 , 27 , 39
if wrongstatus ( d , 1 , 2 , 3 ) :
return False
if wrongstatus ( d , 4 , 5 , 6 ) :
return False
if wrongstatus ( d , 7 , 8 , 9 ) :
return False
if wrongstatus ( d , 10 , 11 , 12 ) :
return... |
def content_ids ( params ) :
"""does the same this as ` pageviews ` , except it includes content ids and then optionally filters
the response by a list of content ids passed as query params - note , this load can be a little
heavy and could take a minute""" | # set up default values
default_from , default_to , yesterday , _ = make_default_times ( )
# get params
try :
series = params . get ( "site" , [ DEFAULT_SERIES ] ) [ 0 ]
from_date = params . get ( "from" , [ default_from ] ) [ 0 ]
to_date = params . get ( "to" , [ default_to ] ) [ 0 ]
group_by = params ... |
def should_run_now ( self , force = False ) :
from django_cron . models import CronJobLog
cron_job = self . cron_job
"""Returns a boolean determining whether this cron should run now or not !""" | self . user_time = None
self . previously_ran_successful_cron = None
# If we pass - - force options , we force cron run
if force :
return True
if cron_job . schedule . run_every_mins is not None : # We check last job - success or not
last_job = None
try :
last_job = CronJobLog . objects . filter ( c... |
def _readPPN ( self , fname , sldir ) :
'''Private method that reads in and organizes the . ppn file
Loads the data of the . ppn file into the variable cols .''' | if sldir . endswith ( os . sep ) : # Making sure fname will be formatted correctly
fname = str ( sldir ) + str ( fname )
else :
fname = str ( sldir ) + os . sep + str ( fname )
self . sldir += os . sep
f = open ( fname , 'r' )
lines = f . readlines ( )
for i in range ( len ( lines ) ) :
lines [ i ] = li... |
def next_channel_from_routes ( available_routes : List [ 'RouteState' ] , channelidentifiers_to_channels : Dict , transfer_amount : PaymentWithFeeAmount , lock_timeout : BlockTimeout , ) -> Optional [ NettingChannelState ] :
"""Returns the first route that may be used to mediated the transfer .
The routing servic... | for route in available_routes :
channel_state = channelidentifiers_to_channels . get ( route . channel_identifier )
if not channel_state :
continue
if is_channel_usable ( channel_state , transfer_amount , lock_timeout ) :
return channel_state
return None |
def insert_into_last_element ( html , element ) :
"""function to insert an html element into another html fragment
example :
html = ' < p > paragraph1 < / p > < p > paragraph2 . . . < / p > '
element = ' < a href = " / read - more / " > read more < / a > '
- - - > ' < p > paragraph1 < / p > < p > paragraph2... | try :
item = fragment_fromstring ( element )
except ( ParserError , TypeError ) as e :
item = fragment_fromstring ( '<span></span>' )
try :
doc = fragments_fromstring ( html )
doc [ - 1 ] . append ( item )
return '' . join ( tostring ( e ) for e in doc )
except ( ParserError , TypeError ) as e :
... |
def interpolate ( self , factor , minGlyph , maxGlyph , round = True , suppressError = True ) :
"""Interpolate the contents of this glyph at location ` ` factor ` `
in a linear interpolation between ` ` minGlyph ` ` and ` ` maxGlyph ` ` .
> > > glyph . interpolate ( 0.5 , otherGlyph1 , otherGlyph2)
` ` factor... | factor = normalizers . normalizeInterpolationFactor ( factor )
if not isinstance ( minGlyph , BaseGlyph ) :
raise TypeError ( ( "Interpolation to an instance of %r can not be " "performed from an instance of %r." ) % ( self . __class__ . __name__ , minGlyph . __class__ . __name__ ) )
if not isinstance ( maxGlyph , ... |
def list_all_variants ( cls , ** kwargs ) :
"""List Variants
Return a list of Variants
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . list _ all _ variants ( async = True )
> > > result = thread . get ( )
: p... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _list_all_variants_with_http_info ( ** kwargs )
else :
( data ) = cls . _list_all_variants_with_http_info ( ** kwargs )
return data |
def choose_meas_file ( self , event = None ) :
"""Opens a dialog allowing the user to pick a measurement file""" | dlg = wx . FileDialog ( self , message = "Please choose a measurement file" , defaultDir = self . WD , defaultFile = "measurements.txt" , wildcard = "measurement files (*.magic,*.txt)|*.magic;*.txt" , style = wx . FD_OPEN | wx . FD_CHANGE_DIR )
if self . show_dlg ( dlg ) == wx . ID_OK :
meas_file = dlg . GetPath ( ... |
def capture_url_missing_namespace ( self , node ) :
"""Capture missing namespace in url include .""" | for arg in node . args :
if not ( isinstance ( arg , ast . Call ) and isinstance ( arg . func , ast . Name ) ) :
continue
if arg . func . id != 'include' :
continue
for keyword in arg . keywords :
if keyword . arg == 'namespace' :
return
return DJ05 ( lineno = node . ... |
def get_attribute ( self , colourmode , mode , name , part = None ) :
"""returns requested attribute
: param mode : ui - mode ( e . g . ` search ` , ` thread ` . . . )
: type mode : str
: param name : of the atttribute
: type name : str
: param colourmode : colour mode ; in [ 1 , 16 , 256]
: type colour... | thmble = self . _config [ mode ] [ name ]
if part is not None :
thmble = thmble [ part ]
thmble = thmble or DUMMYDEFAULT
return thmble [ self . _colours . index ( colourmode ) ] |
def create_missing ( self ) :
"""Automatically populate additional instance attributes .
When a new lifecycle environment is created , it must either :
* Reference a parent lifecycle environment in the tree of lifecycle
environments via the ` ` prior ` ` field , or
* have a name of " Library " .
Within a ... | # We call ` super ` first b / c it populates ` self . organization ` , and we
# need that field to perform a search a little later .
super ( LifecycleEnvironment , self ) . create_missing ( )
if ( self . name != 'Library' and # pylint : disable = no - member
not hasattr ( self , 'prior' ) ) :
results = self . searc... |
def get_airmass ( self , times = None , solar_position = None , model = 'kastenyoung1989' ) :
"""Calculate the relative and absolute airmass .
Automatically chooses zenith or apparant zenith
depending on the selected model .
Parameters
times : None or DatetimeIndex , default None
Only used if solar _ posi... | if solar_position is None :
solar_position = self . get_solarposition ( times )
if model in atmosphere . APPARENT_ZENITH_MODELS :
zenith = solar_position [ 'apparent_zenith' ]
elif model in atmosphere . TRUE_ZENITH_MODELS :
zenith = solar_position [ 'zenith' ]
else :
raise ValueError ( '{} is not a vali... |
def reload ( self ) :
"""Reload the metadata for this instance .
For example :
. . literalinclude : : snippets . py
: start - after : [ START bigtable _ reload _ instance ]
: end - before : [ END bigtable _ reload _ instance ]""" | instance_pb = self . _client . instance_admin_client . get_instance ( self . name )
# NOTE : _ update _ from _ pb does not check that the project and
# instance ID on the response match the request .
self . _update_from_pb ( instance_pb ) |
def write_warning ( self , url_data ) :
"""Write url _ data . warning .""" | self . write ( self . part ( "warning" ) + self . spaces ( "warning" ) )
warning_msgs = [ u"[%s] %s" % x for x in url_data . warnings ]
self . writeln ( self . wrap ( warning_msgs , 65 ) , color = self . colorwarning ) |
def obj_update ( obj , data : dict , * , update_fields = UNSET , save : bool = True ) -> bool :
"""Fancy way to update ` obj ` with ` data ` dict .
Parameters
obj : Django model instance
data
The data to update ` ` obj ` ` with
update _ fields
Use your ` ` update _ fields ` ` instead of our generated on... | for field_name , value in data . items ( ) :
set_field ( obj , field_name , value )
dirty_data = getattr ( obj , DIRTY , None )
if not dirty_data :
return False
logger . debug ( human_log_formatter ( dirty_data ) , extra = { 'model' : obj . _meta . object_name , 'pk' : obj . pk , 'changes' : json_log_formatter ... |
def snap_momentum_by_name ( self , name , velocity , at = None ) :
"""Changes the velocity of a momentum named ` name ` .
: param name : the momentum name .
: param velocity : a new velocity .
: param at : the time to snap . ( default : now )
: returns : a momentum updated .
: raises TypeError : ` name ` ... | at = now_or ( at )
self . forget_past ( at = at )
return self . update_momentum_by_name ( name , velocity = velocity , since = at ) |
def as_binary ( self , content , encoding = 'utf8' ) :
'''Perform content encoding for binary write''' | if hasattr ( content , 'read' ) :
return content . read ( )
elif isinstance ( content , six . text_type ) :
return content . encode ( encoding )
else :
return content |
def hsetnx ( self , key , field , value ) :
"""Set the value of a hash field , only if the field does not exist .""" | return self . execute ( b'HSETNX' , key , field , value ) |
def dumper ( args , config , transform_func = None ) :
"""Dumper main function .""" | args = process_args ( args )
submit_args = get_submit_args ( args )
submit_outcome = submit_if_ready ( args , submit_args , config )
if submit_outcome is not None : # submitted , nothing more to do
return submit_outcome
import_time = datetime . datetime . utcnow ( )
try :
records = dump2polarion . import_result... |
def _lstrip_word ( word , prefix ) :
'''Return a copy of the string after the specified prefix was removed
from the beginning of the string''' | if six . text_type ( word ) . startswith ( prefix ) :
return six . text_type ( word ) [ len ( prefix ) : ]
return word |
def _buildNewKeyname ( self , key , prepend ) :
"""Builds a new keyword based on original keyword name and
a prepend string .""" | if len ( prepend + key ) <= 8 :
_new_key = prepend + key
else :
_new_key = str ( prepend + key ) [ : 8 ]
return _new_key |
def get_group ( value ) :
"""group = display - name " : " [ group - list ] " ; " [ CFWS ]""" | group = Group ( )
token , value = get_display_name ( value )
if not value or value [ 0 ] != ':' :
raise errors . HeaderParseError ( "expected ':' at end of group " "display name but found '{}'" . format ( value ) )
group . append ( token )
group . append ( ValueTerminal ( ':' , 'group-display-name-terminator' ) )
v... |
def identify ( self , token ) :
"""Identifies to the websocket endpoint
Args :
token ( string ) : Discord bot token""" | payload = { 'op' : 2 , 'd' : { 'token' : self . token , 'properties' : { '$os' : sys . platform , '$browser' : 'legobot' , '$device' : 'legobot' } , 'compress' : False , 'large_threshold' : 250 } }
payload [ 'd' ] [ 'synced_guilds' ] = [ ]
logger . info ( "Identifying with the following message: \
{... |
def decode_to_pixbuf ( image_data , width = None , height = None ) :
"""Decode an image from memory with GDK - PixBuf .
The file format is detected automatically .
: param image _ data : A byte string
: param width : Integer width in pixels or None
: param height : Integer height in pixels or None
: retur... | loader = ffi . gc ( gdk_pixbuf . gdk_pixbuf_loader_new ( ) , gobject . g_object_unref )
error = ffi . new ( 'GError **' )
if width and height :
gdk_pixbuf . gdk_pixbuf_loader_set_size ( loader , width , height )
handle_g_error ( error , gdk_pixbuf . gdk_pixbuf_loader_write ( loader , ffi . new ( 'guchar[]' , image_... |
async def parseform ( self , limit = 67108864 , tostr = True , safename = True ) :
'''Parse form - data with multipart / form - data or application / x - www - form - urlencoded
In Python3 , the keys of form and files are unicode , but values are bytes
If the key ends with ' [ ] ' , it is considered to be a lis... | if tostr :
def _str ( s ) :
try :
if not isinstance ( s , str ) :
return s . decode ( self . encoding )
else :
return s
except Exception :
raise HttpInputException ( 'Invalid encoding in post data: ' + repr ( s ) )
else :
def _s... |
def send ( self ) :
"""Sends the broadcast message .
: returns : tuple of ( : class : ` adnpy . models . Message ` , : class : ` adnpy . models . APIMeta ` )""" | parse_links = self . parse_links or self . parse_markdown_links
message = { 'annotations' : [ ] , 'entities' : { 'parse_links' : parse_links , 'parse_markdown_links' : self . parse_markdown_links , } }
if self . photo :
photo , photo_meta = _upload_file ( self . api , self . photo )
message [ 'annotations' ] . ... |
def calculate ( self , token_list_x , token_list_y ) :
'''Calculate similarity with the so - called Cosine similarity of Tf - Idf vectors .
Concrete method .
Args :
token _ list _ x : [ token , token , token , . . . ]
token _ list _ y : [ token , token , token , . . . ]
Returns :
Similarity .''' | if len ( token_list_x ) == 0 or len ( token_list_y ) == 0 :
return 0.0
document_list = token_list_x . copy ( )
[ document_list . append ( v ) for v in token_list_y ]
document_list = list ( set ( document_list ) )
tfidf_vectorizer = TfidfVectorizer ( document_list )
vector_list_x = tfidf_vectorizer . vectorize ( tok... |
def RgbToHsl ( r , g , b ) :
'''Convert the color from RGB coordinates to HSL .
Parameters :
The Red component value [ 0 . . . 1]
The Green component value [ 0 . . . 1]
The Blue component value [ 0 . . . 1]
Returns :
The color as an ( h , s , l ) tuple in the range :
h [ 0 . . . 360 ] ,
s [ 0 . . . ... | minVal = min ( r , g , b )
# min RGB value
maxVal = max ( r , g , b )
# max RGB value
l = ( maxVal + minVal ) / 2.0
if minVal == maxVal :
return ( 0.0 , 0.0 , l )
# achromatic ( gray )
d = maxVal - minVal
# delta RGB value
if l < 0.5 :
s = d / ( maxVal + minVal )
else :
s = d / ( 2.0 - maxVal - minVal )
dr ... |
def address_inline ( request , prefix = "" , country_code = None , template_name = "postal/form.html" ) :
"""Displays postal address with localized fields""" | country_prefix = "country"
prefix = request . POST . get ( 'prefix' , prefix )
if prefix :
country_prefix = prefix + '-country'
country_code = request . POST . get ( country_prefix , country_code )
form_class = form_factory ( country_code = country_code )
if request . method == "POST" :
data = { }
for ( key... |
def _extract_table ( table_data , current , pc , ts , tt ) :
"""Use the given table data to create a time series entry for each column in the table .
: param dict table _ data : Table data
: param dict current : LiPD root data
: param str pc : paleoData or chronData
: param list ts : Time series ( so far ) ... | current [ "tableType" ] = tt
# Get root items for this table
current = _extract_table_root ( table_data , current , pc )
# Add in modelNumber and tableNumber if this is " ens " or " summ " table
current = _extract_table_model ( table_data , current , tt )
# Add age , depth , and year columns to root if available
_table... |
def _merge_layout_objs ( obj , subobj ) :
"""Merge layout objects recursively
Note : This function mutates the input obj dict , but it does not mutate
the subobj dict
Parameters
obj : dict
dict into which the sub - figure dict will be merged
subobj : dict
dict that sill be copied and merged into ` obj... | for prop , val in subobj . items ( ) :
if isinstance ( val , dict ) and prop in obj : # recursion
_merge_layout_objs ( obj [ prop ] , val )
elif ( isinstance ( val , list ) and obj . get ( prop , None ) and isinstance ( obj [ prop ] [ 0 ] , dict ) ) : # append
obj [ prop ] . extend ( val )
e... |
def make_thematic_png ( self , outpath = None ) :
"""Convert a thematic map into png format with a legend
: param outpath : if specified , will save the image instead of showing it""" | from matplotlib . patches import Patch
fig , previewax = plt . subplots ( )
shape = self . thmap . shape
previewax . imshow ( self . thmap , origin = 'lower' , interpolation = 'nearest' , cmap = self . config . solar_cmap , vmin = - 1 , vmax = len ( self . config . solar_classes ) - 1 )
legend_elements = [ Patch ( face... |
def table_row ( text_array , pad = - 1 ) :
"""Return a single table row .
Keyword arguments :
pad - - The pad should be an array of the same size as the input text array .
It will be used to format the row ' s padding .
> > > table _ row ( [ " First column " , " Second " , " Third " ] )
' | First column |... | if pad == - 1 :
pad = [ 0 ] * len ( text_array )
row = "|"
for column_number in range ( len ( text_array ) ) :
padding = pad [ column_number ] + 1
row += ( " " + esc_format ( text_array [ column_number ] ) ) . ljust ( padding ) + " |"
return row |
def max_send_data_size ( self ) :
"""The maximum number of octets that can be send with the
: meth : ` exchange ` method in the established operating mode .""" | with self . lock :
if self . device is None :
raise IOError ( errno . ENODEV , os . strerror ( errno . ENODEV ) )
else :
return self . device . get_max_send_data_size ( self . target ) |
def _Close ( self ) :
"""Closes the file - like object .
If the file - like object was passed in the init function
the encoded stream file - like object does not control
the file - like object and should not actually close it .""" | if not self . _file_object_set_in_init :
self . _file_object . close ( )
self . _file_object = None
self . _decoder = None
self . _decoded_data = b''
self . _encoded_data = b'' |
def require ( * args , ** kwargs ) :
'''Install a set of packages using pip
This is designed to be an interface for IPython notebooks that
replicates the requirements . txt pip format . This lets notebooks
specify which versions of packages they need inside the notebook
itself .
This function is the gener... | # If called with no arguments , returns requirements list
if not args and not kwargs :
return freeze ( )
# Construct array of requirements
requirements = list ( args )
extra = [ '{}{}' . format ( kw , kwargs [ kw ] ) for kw in kwargs ]
requirements . extend ( extra )
args = [ 'install' , '-q' ]
args . extend ( requ... |
def build_props ( self ) :
"""Build the props dictionary .""" | props = { }
if self . filters :
props [ "filters" ] = { }
for grp in self . filters :
props [ "filters" ] [ grp ] = [ f . params for f in self . filters [ grp ] ]
if self . charts :
props [ "charts" ] = [ c . params for c in self . charts ]
props [ "type" ] = self . layout
return props |
def get_if_raw_addr6 ( iff ) :
"""Returns the main global unicast address associated with provided
interface , in network format . If no global address is found , None
is returned .""" | # r = filter ( lambda x : x [ 2 ] = = iff and x [ 1 ] = = IPV6 _ ADDR _ GLOBAL , in6 _ getifaddr ( ) )
r = [ x for x in in6_getifaddr ( ) if x [ 2 ] == iff and x [ 1 ] == IPV6_ADDR_GLOBAL ]
if len ( r ) == 0 :
return None
else :
r = r [ 0 ] [ 0 ]
return inet_pton ( socket . AF_INET6 , r ) |
def get_sof_term ( self , C , rup ) :
"""In the case of the upper mantle events separate coefficients
are considered for normal , reverse and strike - slip""" | if rup . rake <= - 45.0 and rup . rake >= - 135.0 : # Normal faulting
return C [ "FN_UM" ]
elif rup . rake > 45.0 and rup . rake < 135.0 : # Reverse faulting
return C [ "FRV_UM" ]
else : # No adjustment for strike - slip faulting
return 0.0 |
async def scroll ( self , value , mode = 'relative' ) :
"""Scroll the cursor in the result set to a new position
according to mode . Same as : meth : ` Cursor . scroll ` , but move cursor
on server side one by one row . If you want to move 20 rows forward
scroll will make 20 queries to move cursor . Currently... | self . _check_executed ( )
if mode == 'relative' :
if value < 0 :
raise NotSupportedError ( "Backwards scrolling not supported " "by this cursor" )
for _ in range ( value ) :
await self . _read_next ( )
self . _rownumber += value
elif mode == 'absolute' :
if value < self . _rownumber :
... |
def async_new_device_callback ( self , device ) :
"""Log that our new device callback worked .""" | _LOGGING . info ( 'New Device: %s cat: 0x%02x subcat: 0x%02x desc: %s, model: %s' , device . id , device . cat , device . subcat , device . description , device . model )
for state in device . states :
device . states [ state ] . register_updates ( self . async_state_change_callback ) |
def get_default_image_build_conf ( self ) :
"""Create a default image build config
: rtype : ConfigParser
: return : Initialized config with defaults""" | target = self . koji_target
vcs_info = self . workflow . source . get_vcs_info ( )
ksurl = '{}#{}' . format ( vcs_info . vcs_url , vcs_info . vcs_ref )
base_urls = [ ]
for repo in self . repos :
for url in self . extract_base_url ( repo ) : # Imagefactory only supports $ arch variable .
url = url . replace ... |
def export_project ( project , temporary_dir , include_images = False , keep_compute_id = False , allow_all_nodes = False , ignore_prefixes = None ) :
"""Export the project as zip . It ' s a ZipStream object .
The file will be read chunk by chunk when you iterate on
the zip .
It will ignore some files like sn... | # To avoid issue with data not saved we disallow the export of a running topologie
if project . is_running ( ) :
raise aiohttp . web . HTTPConflict ( text = "Running topology could not be exported" )
# Make sure we save the project
project . dump ( )
z = zipstream . ZipFile ( allowZip64 = True )
if not os . path . ... |
def _build_trigram_indices ( trigram_index ) :
"""Build a dictionary of trigrams and their indices from a csv""" | result = { }
trigram_count = 0
for key , val in csv . reader ( open ( trigram_index ) ) :
result [ key ] = int ( val )
trigram_count += 1
return result , trigram_count |
def box ( self , x0 , y0 , width , height ) :
"""Create a box on ASCII canvas .
Args :
x0 ( int ) : x coordinate of the box corner .
y0 ( int ) : y coordinate of the box corner .
width ( int ) : box width .
height ( int ) : box height .""" | assert width > 1
assert height > 1
width -= 1
height -= 1
for x in range ( x0 , x0 + width ) :
self . point ( x , y0 , "-" )
self . point ( x , y0 + height , "-" )
for y in range ( y0 , y0 + height ) :
self . point ( x0 , y , "|" )
self . point ( x0 + width , y , "|" )
self . point ( x0 , y0 , "+" )
sel... |
def _get_runner ( classpath , main , jvm_options , args , executor , cwd , distribution , create_synthetic_jar , synthetic_jar_dir ) :
"""Gets the java runner for execute _ java and execute _ java _ async .""" | executor = executor or SubprocessExecutor ( distribution )
safe_cp = classpath
if create_synthetic_jar :
safe_cp = safe_classpath ( classpath , synthetic_jar_dir )
logger . debug ( 'Bundling classpath {} into {}' . format ( ':' . join ( classpath ) , safe_cp ) )
return executor . runner ( safe_cp , main , args ... |
def _parse_tmx ( path ) :
"""Generates examples from TMX file .""" | def _get_tuv_lang ( tuv ) :
for k , v in tuv . items ( ) :
if k . endswith ( "}lang" ) :
return v
raise AssertionError ( "Language not found in `tuv` attributes." )
def _get_tuv_seg ( tuv ) :
segs = tuv . findall ( "seg" )
assert len ( segs ) == 1 , "Invalid number of segments: %d" %... |
def format_v1_score_response ( response , limit_to_model = None ) :
"""The response format looks like this : :
" < rev _ id > " : {
" < model _ name > " : < score >
" < model _ name > " : < score >
" < rev _ id > " : {
" < model _ name > " : < score >
" < model _ name > " : < score >""" | response_doc = defaultdict ( dict )
for rev_id , rev_scores in response . scores . items ( ) :
for model_name , score in rev_scores . items ( ) :
response_doc [ rev_id ] [ model_name ] = score
for rev_id , rev_errors in response . errors . items ( ) :
for model_name , error in rev_errors . items ( ) :
... |
def load ( self , data , many = None , partial = None ) :
"""Deserialize a data structure to an object .""" | result = super ( ResumptionTokenSchema , self ) . load ( data , many = many , partial = partial )
result . data . update ( result . data . get ( 'resumptionToken' , { } ) . get ( 'kwargs' , { } ) )
return result |
def serve ( files , immutable , host , port , debug , reload , cors , sqlite_extensions , inspect_file , metadata , template_dir , plugins_dir , static , memory , config , version_note , help_config , ) :
"""Serve up specified SQLite database files with a web UI""" | if help_config :
formatter = formatting . HelpFormatter ( )
with formatter . section ( "Config options" ) :
formatter . write_dl ( [ ( option . name , '{} (default={})' . format ( option . help , option . default ) ) for option in CONFIG_OPTIONS ] )
click . echo ( formatter . getvalue ( ) )
sys ... |
def _get_demand_array_construct ( self ) :
"""Returns a construct for an array of power demand data .""" | bus_no = integer . setResultsName ( "bus_no" )
s_rating = real . setResultsName ( "s_rating" )
# MVA
p_direction = real . setResultsName ( "p_direction" )
# p . u .
q_direction = real . setResultsName ( "q_direction" )
# p . u .
p_bid_max = real . setResultsName ( "p_bid_max" )
# p . u .
p_bid_min = real . setResultsNa... |
def run_cgmlst ( blast_runner , full = False ) :
"""Perform in silico cgMLST on an input genome
Args :
blast _ runner ( sistr . src . blast _ wrapper . BlastRunner ) : blastn runner object with genome fasta initialized
Returns :
dict : cgMLST ref genome match , distance to closest ref genome , subspecies an... | from sistr . src . serovar_prediction . constants import genomes_to_serovar
df_cgmlst_profiles = ref_cgmlst_profiles ( )
logging . debug ( '{} distinct cgMLST330 profiles' . format ( df_cgmlst_profiles . shape [ 0 ] ) )
logging . info ( 'Running BLAST on serovar predictive cgMLST330 alleles' )
cgmlst_fasta_path = CGMLS... |
def cnst_A1 ( self , X , Xf = None ) :
r"""Compute : math : ` A _ 1 \ mathbf { x } ` component of ADMM problem
constraint . In this case : math : ` A _ 1 \ mathbf { x } = ( \ Gamma _ 0 ^ T \ ; \ ;
\ Gamma _ 1 ^ T \ ; \ ; \ ldots ) ^ T \ mathbf { x } ` .""" | if Xf is None :
Xf = sl . rfftn ( X , axes = self . cri . axisN )
return sl . irfftn ( sl . inner ( self . GDf , Xf [ ... , np . newaxis ] , axis = self . cri . axisM ) , self . cri . Nv , self . cri . axisN ) |
def update_trainer ( self , trainer , username = None , start_date = None , has_cheated = None , last_cheated = None , currently_cheats = None , statistics = None , daily_goal = None , total_goal = None , prefered = None ) :
"""Update parts of a trainer in a database""" | args = locals ( )
if not isinstance ( trainer , Trainer ) :
raise ValueError
url = api_url + 'trainers/' + str ( trainer . id ) + '/'
payload = { 'last_modified' : maya . now ( ) . iso8601 ( ) }
for i in args :
if args [ i ] is not None and i not in [ 'self' , 'trainer' , 'start_date' ] :
payload [ i ] ... |
def _line_opt ( self ) :
"""Perform a line search along the current direction""" | direction = self . search_direction . direction
if self . constraints is not None :
try :
direction = self . constraints . project ( self . x , direction )
except ConstraintError :
self . _screen ( "CONSTRAINT PROJECT FAILED" , newline = True )
return False
direction_norm = np . linalg .... |
def _genenare_callmap_sif ( self , filepath ) :
"""Generate a sif file from the call map .
: param filepath : Path of the sif file
: return : None""" | with open ( filepath , "wb" ) as f :
for src , dst in self . callgraph . edges ( ) :
f . write ( "%#x\tDirectEdge\t%#x\n" % ( src , dst ) ) |
def list ( self , end_date = values . unset , friendly_name = values . unset , minutes = values . unset , start_date = values . unset , task_channel = values . unset , split_by_wait_time = values . unset , limit = None , page_size = None ) :
"""Lists TaskQueuesStatisticsInstance records from the API as a list .
U... | return list ( self . stream ( end_date = end_date , friendly_name = friendly_name , minutes = minutes , start_date = start_date , task_channel = task_channel , split_by_wait_time = split_by_wait_time , limit = limit , page_size = page_size , ) ) |
def js ( self , name = None ) :
"""Returns all needed Javascript filepaths for given config name ( if
given ) or every registred config instead ( if no name is given ) .
Keyword Arguments :
name ( string ) : Specific config name to use instead of all .
Returns :
list : List of Javascript file paths .""" | filepaths = copy . copy ( settings . CODEMIRROR_BASE_JS )
configs = self . get_configs ( name )
names = sorted ( configs )
# Addons first
for name in names :
opts = configs [ name ]
for item in opts . get ( 'addons' , [ ] ) :
if item not in filepaths :
filepaths . append ( item )
# Process m... |
def _get_inference_input ( self , trans_inputs : List [ TranslatorInput ] ) -> Tuple [ mx . nd . NDArray , int , Optional [ lexicon . TopKLexicon ] , List [ Optional [ constrained . RawConstraintList ] ] , List [ Optional [ constrained . RawConstraintList ] ] , mx . nd . NDArray ] :
"""Assembles the numerical data ... | batch_size = len ( trans_inputs )
bucket_key = data_io . get_bucket ( max ( len ( inp . tokens ) for inp in trans_inputs ) , self . buckets_source )
source = mx . nd . zeros ( ( batch_size , bucket_key , self . num_source_factors ) , ctx = self . context )
restrict_lexicon = None
# type : Optional [ lexicon . TopKLexic... |
def verify_signature ( self , signature ) :
"""Verifies signature""" | devices = [ DeviceRegistration . wrap ( device ) for device in self . __get_u2f_devices ( ) ]
challenge = session . pop ( '_u2f_challenge_' )
try :
counter , touch = verify_authenticate ( devices , challenge , signature , self . __facets_list )
except Exception as e :
if self . __call_fail_sign :
self .... |
def errback ( self , failure ) :
"""Errbacks the deferreds previously produced by this object .
@ param failure : The object which will be passed to the
C { errback } method of all C { Deferred } s previously produced by
this object ' s C { tee } method .
@ raise AlreadyCalledError : If L { callback } or L ... | self . _setResult ( failure )
self . _isFailure = True
for d in self . _deferreds :
d . errback ( failure ) |
async def _write_to_container_stdin ( self , write_stream , message ) :
"""Send a message to the stdin of a container , with the right data
: param write _ stream : asyncio write stream to the stdin of the container
: param message : dict to be msgpacked and sent""" | msg = msgpack . dumps ( message , encoding = "utf8" , use_bin_type = True )
self . _logger . debug ( "Sending %i bytes to container" , len ( msg ) )
write_stream . write ( struct . pack ( 'I' , len ( msg ) ) )
write_stream . write ( msg )
await write_stream . drain ( ) |
def get_cache_subnet_group ( name , region = None , key = None , keyid = None , profile = None ) :
'''Get information about a cache subnet group .
CLI example : :
salt myminion boto _ elasticache . get _ cache _ subnet _ group mycache _ subnet _ group''' | conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
try :
csg = conn . describe_cache_subnet_groups ( name )
csg = csg [ 'DescribeCacheSubnetGroupsResponse' ]
csg = csg [ 'DescribeCacheSubnetGroupsResult' ] [ 'CacheSubnetGroups' ] [ 0 ]
except boto . exception . BotoServerEr... |
def verification_add ( self , domain_resource_id , port , is_ssl ) :
"""Sends a POST to / 1.0 / verifications / using this post - data :
{ " domain _ href " : " / 1.0 / domains / 2 " ,
" port " : 80,
" ssl " : false }
: param domain _ resource _ id : The domain id to verify
: param port : The TCP port
:... | data = { "domain_href" : self . build_api_path ( 'domains' , domain_resource_id ) , "port" : port , "ssl" : 'true' if is_ssl else 'false' }
url = self . build_full_url ( self . VERIFICATIONS )
return self . create_resource ( url , data ) |
def _print_lines ( self , lines , start , breaks = ( ) , frame = None ) :
"""Print a range of lines .""" | if frame :
current_lineno = frame . f_lineno
exc_lineno = self . tb_lineno . get ( frame , - 1 )
else :
current_lineno = exc_lineno = - 1
for lineno , line in enumerate ( lines , start ) :
s = str ( lineno ) . rjust ( 3 )
if len ( s ) < 4 :
s += ' '
if lineno in breaks :
s += 'B'... |
def dict_to_path ( as_dict ) :
"""Turn a pure dict into a dict containing entity objects that
can be sent directly to a Path constructor .
Parameters
as _ dict : dict
Has keys : ' vertices ' , ' entities '
Returns
kwargs : dict
Has keys : ' vertices ' , ' entities '""" | # start kwargs with initial value
result = as_dict . copy ( )
# map of constructors
loaders = { 'Arc' : Arc , 'Line' : Line }
# pre - allocate entity array
entities = [ None ] * len ( as_dict [ 'entities' ] )
# run constructor for dict kwargs
for entity_index , entity in enumerate ( as_dict [ 'entities' ] ) :
entit... |
def request ( self , path , args = [ ] , files = [ ] , opts = { } , stream = False , decoder = None , headers = { } , data = None ) :
"""Makes an HTTP request to the IPFS daemon .
This function returns the contents of the HTTP response from the IPFS
daemon .
Raises
~ ipfsapi . exceptions . ErrorResponse
~... | url = self . base + path
params = [ ]
params . append ( ( 'stream-channels' , 'true' ) )
for opt in opts . items ( ) :
params . append ( opt )
for arg in args :
params . append ( ( 'arg' , arg ) )
method = 'post' if ( files or data ) else 'get'
parser = encoding . get_encoding ( decoder if decoder else "none" )... |
def process ( self , items_block ) :
"""Return items as they come , updating their metadata _ _ enriched _ on field .
: param items _ block :
: return : hits blocks as they come , updating their metadata _ _ enriched _ on field . Namedtuple containing :
- processed : number of processed hits
- out _ items :... | out_items = [ ]
for hit in items_block :
if __name__ == '__main__' :
hit [ '_source' ] [ 'metadata__enriched_on' ] = datetime . datetime_utcnow ( ) . isoformat ( )
out_items . append ( hit )
return self . ProcessResults ( processed = 0 , out_items = out_items ) |
def read_data ( self , variable_instance ) :
"""read values from the device""" | if self . inst is None :
return
if variable_instance . visavariable . device_property . upper ( ) == 'PRESENT_VALUE' :
return self . parse_value ( self . inst . query ( '?U6P0' ) )
elif variable_instance . visavariable . device_property . upper ( ) == 'PRESENT_VALUE_MANUAL_C_FREQ' :
freq = VariableProperty ... |
def fetcher ( date = datetime . today ( ) , url_pattern = URL_PATTERN ) :
"""Fetch json data from n . pl
Args :
date ( date ) - default today
url _ patter ( string ) - default URL _ PATTERN
Returns :
dict - data from api""" | api_url = url_pattern % date . strftime ( '%Y-%m-%d' )
headers = { 'Referer' : 'http://n.pl/program-tv' }
raw_result = requests . get ( api_url , headers = headers ) . json ( )
return raw_result |
def get_shape ( self ) :
"""Return a tuple of this array ' s dimensions . This is done by
querying the Dim children . Note that once it has been
created , it is also possible to examine an Array object ' s
. array attribute directly , and doing that is much faster .""" | return tuple ( int ( c . pcdata ) for c in self . getElementsByTagName ( ligolw . Dim . tagName ) ) [ : : - 1 ] |
def _cholesky ( self , A , ** kwargs ) :
"""method to handle potential problems with the cholesky decomposition .
will try to increase L2 regularization of the penalty matrix to
do away with non - positive - definite errors
Parameters
A : np . array
Returns
np . array""" | # create appropriate - size diagonal matrix
if sp . sparse . issparse ( A ) :
diag = sp . sparse . eye ( A . shape [ 0 ] )
else :
diag = np . eye ( A . shape [ 0 ] )
constraint_l2 = self . _constraint_l2
while constraint_l2 <= self . _constraint_l2_max :
try :
L = cholesky ( A , ** kwargs )
... |
def clearSelection ( self ) :
"""Clears the selected text for this edit .""" | first = None
editors = self . editors ( )
for editor in editors :
if not editor . selectedText ( ) :
continue
first = first or editor
editor . backspace ( )
for editor in editors :
editor . setFocus ( )
if first :
first . setFocus ( ) |
def create_plane ( width = 1 , height = 1 , width_segments = 1 , height_segments = 1 , direction = '+z' ) :
"""Generate vertices & indices for a filled and outlined plane .
Parameters
width : float
Plane width .
height : float
Plane height .
width _ segments : int
Plane segments count along the width ... | x_grid = width_segments
y_grid = height_segments
x_grid1 = x_grid + 1
y_grid1 = y_grid + 1
# Positions , normals and texcoords .
positions = np . zeros ( x_grid1 * y_grid1 * 3 )
normals = np . zeros ( x_grid1 * y_grid1 * 3 )
texcoords = np . zeros ( x_grid1 * y_grid1 * 2 )
y = np . arange ( y_grid1 ) * height / y_grid ... |
def gpg_version ( sp = subprocess ) :
"""Get a keygrip of the primary GPG key of the specified user .""" | args = gpg_command ( [ '--version' ] )
output = check_output ( args = args , sp = sp )
line = output . split ( b'\n' ) [ 0 ]
# b ' gpg ( GnuPG ) 2.1.11'
line = line . split ( b' ' ) [ - 1 ]
# b ' 2.1.11'
line = line . split ( b'-' ) [ 0 ]
# remove trailing version parts
return line . split ( b'v' ) [ - 1 ] |
def set_url ( self ) :
'''打开豆瓣网页''' | import webbrowser
url = "http://music.douban.com" + self . data . playingsong [ 'album' ] . replace ( '\/' , '/' )
webbrowser . open ( url ) |
def write_assoc ( self , assoc ) :
"""Write a single association to a line in the output file""" | if assoc . get ( "header" , False ) :
return
subj = assoc [ 'subject' ]
db , db_object_id = self . _split_prefix ( subj )
rel = assoc [ 'relation' ]
qualifier = rel [ 'id' ]
if assoc [ 'negated' ] :
qualifier = 'NOT|' + qualifier
goid = assoc [ 'object' ] [ 'id' ]
ev = assoc [ 'evidence' ]
evidence = self . eco... |
def xnormpath ( path ) :
"""Cross - platform version of os . path . normpath""" | # replace escapes and Windows slashes
normalized = posixpath . normpath ( path ) . replace ( b'\\' , b'/' )
# fold the result
return posixpath . normpath ( normalized ) |
def claim ( self , owner , access ) :
"""Claim the lock ( lock must be available )""" | debuglog ( "%s claim(%s, %s)" % ( self , owner , access . mode ) )
assert owner is not None
assert self . isAvailable ( owner , access ) , "ask for isAvailable() first"
assert isinstance ( access , LockAccess )
assert access . mode in [ 'counting' , 'exclusive' ]
self . waiting = [ w for w in self . waiting if w [ 0 ] ... |
def infer_devices ( devices = None ) :
"""Returns the list of devices that multi - replica code should use .
: param devices : list of string device names , e . g . [ " / GPU : 0 " ]
If the user specifies this , ` infer _ devices ` checks that it is
valid , and then uses this user - specified list .
If the ... | if devices is None :
devices = get_available_gpus ( )
if len ( devices ) == 0 :
warnings . warn ( "No GPUS, running on CPU" )
# Set device to empy string , tf will figure out whether to use
# XLA or not , etc . , automatically
devices = [ "" ]
else :
assert len ( devices ) > ... |
def walk ( self , head = None ) :
"""Do a breadth - first walk of the graph , yielding on each node ,
starting at ` head ` .""" | head = head or self . _root_node
queue = [ ]
queue . insert ( 0 , head )
while queue :
node = queue . pop ( )
yield node . num , node . previous , node . siblings
for child in node . siblings :
if child in self . _graph :
queue . insert ( 0 , self . _graph [ child ] ) |
def _parse_reports_by_type ( self ) :
"""Returns a data dictionary
Goes through logs and parses them based on ' No errors found ' , VERBOSE or SUMMARY type .""" | data = dict ( )
for file_meta in self . find_log_files ( 'picard/sam_file_validation' , filehandles = True ) :
sample = file_meta [ 's_name' ]
if sample in data :
log . debug ( "Duplicate sample name found! Overwriting: {}" . format ( sample ) )
filehandle = file_meta [ 'f' ]
first_line = fileha... |
def AddSerializedFile ( self , serialized_file_desc_proto ) :
"""Adds the FileDescriptorProto and its types to this pool .
Args :
serialized _ file _ desc _ proto : A bytes string , serialization of the
FileDescriptorProto to add .""" | # pylint : disable = g - import - not - at - top
from google . protobuf import descriptor_pb2
file_desc_proto = descriptor_pb2 . FileDescriptorProto . FromString ( serialized_file_desc_proto )
self . Add ( file_desc_proto ) |
def unique_everseen ( iterable , filterfalse_ = itertools . filterfalse ) :
"""Unique elements , preserving order .""" | # Itertools recipes :
# https : / / docs . python . org / 3 / library / itertools . html # itertools - recipes
seen = set ( )
seen_add = seen . add
for element in filterfalse_ ( seen . __contains__ , iterable ) :
seen_add ( element )
yield element |
def load_model_data ( self , path , model ) :
"""Loads the data for the specified model from the given path .""" | if os . path . isdir ( path ) : # try find a model data collection
if os . path . isfile ( os . path . join ( path , '_all.yml' ) ) :
self . load_model_data_collection ( path , model )
self . load_model_data_from_files ( path , model )
self . session . commit ( ) |
def shelf_from_config ( config , ** default_init ) :
"""Get a ` Shelf ` instance dynamically based on config .
` config ` is a dictionary containing ` ` shelf _ * ` ` keys as defined in
: mod : ` birding . config ` .""" | shelf_cls = import_name ( config [ 'shelf_class' ] , default_ns = 'birding.shelf' )
init = { }
init . update ( default_init )
init . update ( config [ 'shelf_init' ] )
shelf = shelf_cls ( ** init )
if hasattr ( shelf , 'set_expiration' ) and 'shelf_expiration' in config :
shelf . set_expiration ( config [ 'shelf_ex... |
def build_rrule ( count = None , interval = None , bysecond = None , byminute = None , byhour = None , byweekno = None , bymonthday = None , byyearday = None , bymonth = None , until = None , bysetpos = None , wkst = None , byday = None , freq = None ) :
"""Build rrule dictionary for vRecur class .
: param count ... | result = { }
if count is not None :
result [ 'COUNT' ] = count
if interval is not None :
result [ 'INTERVAL' ] = interval
if bysecond is not None :
result [ 'BYSECOND' ] = bysecond
if byminute is not None :
result [ 'BYMINUTE' ] = byminute
if byhour is not None :
result [ 'BYHOUR' ] = byhour
if bywe... |
def discover_by_directory ( self , start_directory , top_level_directory = None , pattern = 'test*.py' ) :
"""Run test discovery in a directory .
Parameters
start _ directory : str
The package directory in which to start test discovery .
top _ level _ directory : str
The path to the top - level directoy o... | start_directory = os . path . abspath ( start_directory )
if top_level_directory is None :
top_level_directory = find_top_level_directory ( start_directory )
logger . debug ( 'Discovering tests in directory: start_directory=%r, ' 'top_level_directory=%r, pattern=%r' , start_directory , top_level_directory , pattern... |
def _restore_clipboard_text ( self , backup : str ) :
"""Restore the clipboard content .""" | # Pasting takes some time , so wait a bit before restoring the content . Otherwise the restore is done before
# the pasting happens , causing the backup to be pasted instead of the desired clipboard content .
time . sleep ( 0.2 )
self . clipboard . text = backup if backup is not None else "" |
def _calc_eta ( self ) :
"""Calculates estimated time left until completion .""" | elapsed = self . _elapsed ( )
if self . cnt == 0 or elapsed < 0.001 :
return None
rate = float ( self . cnt ) / elapsed
self . eta = ( float ( self . max_iter ) - float ( self . cnt ) ) / rate |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.