signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def save_notebook ( self , body ) :
"""Save notebook depending on user provided output path .""" | directory = os . path . dirname ( self . output_path )
full_path = os . path . join ( directory , self . notebook_name )
try :
with open ( full_path , 'w' ) as fh :
fh . write ( json . dumps ( body , indent = 2 ) )
except ValueError :
print ( 'ERROR: Could not save executed notebook to path: ' + self . ... |
async def stdout_writer ( ) :
"""This is a bit complex , as stdout can be a pipe or a file .
If it is a file , we cannot use
: meth : ` asycnio . BaseEventLoop . connect _ write _ pipe ` .""" | if sys . stdout . seekable ( ) : # it ’ s a file
return sys . stdout . buffer . raw
if os . isatty ( sys . stdin . fileno ( ) ) : # it ’ s a tty , use fd 0
fd_to_use = 0
else :
fd_to_use = 1
twrite , pwrite = await loop . connect_write_pipe ( asyncio . streams . FlowControlMixin , os . fdopen ( fd_to_use , ... |
def get_time ( ) :
'''Get the current system time .
: return : The current time in 24 hour format
: rtype : str
CLI Example :
. . code - block : : bash
salt ' * ' timezone . get _ time''' | ret = salt . utils . mac_utils . execute_return_result ( 'systemsetup -gettime' )
return salt . utils . mac_utils . parse_return ( ret ) |
def urljoin ( * parts ) :
"""Join terms together with forward slashes
Parameters
parts
Returns
str""" | # first strip extra forward slashes ( except http : / / and the likes ) and
# create list
part_list = [ ]
for part in parts :
p = str ( part )
if p . endswith ( '//' ) :
p = p [ 0 : - 1 ]
else :
p = p . strip ( '/' )
part_list . append ( p )
# join everything together
url = '/' . join ( ... |
def slices ( src_path ) :
'''Return slices as a flat list''' | pages = list_slices ( src_path )
slices = [ ]
for page in pages :
slices . extend ( page . slices )
return slices |
def get_all_incoming_properties ( self , params = None ) :
"""Get all incoming properties
This will iterate over all pages until it gets all elements .
So if the rate limit exceeded it will throw an Exception and you will get nothing
: param params : search params
: return : list""" | if not params :
params = { }
return self . _iterate_through_pages ( self . get_incoming_properties_per_page , resource = INCOMING_PROPERTIES , ** { 'params' : params } ) |
def check_pep8 ( filename , ** kwargs ) :
"""Perform static analysis on the given file .
: param filename : path of file to check .
: type filename : str
: param ignore : codes to ignore , e . g . ` ` ( ' E111 ' , ' E123 ' ) ` `
: type ignore : ` list `
: param select : codes to explicitly select .
: ty... | options = { "ignore" : kwargs . get ( "ignore" ) , "select" : kwargs . get ( "select" ) , }
if not _registered_pyflakes_check and kwargs . get ( "pyflakes" , True ) :
_register_pyflakes_check ( )
checker = pep8 . Checker ( filename , reporter = _Report , ** options )
checker . check_all ( )
errors = [ ]
for error i... |
def experiments_predictions_attachments_create ( self , experiment_id , run_id , resource_id , filename , mime_type = None ) :
"""Attach a given data file with a model run . The attached file is
identified by the resource identifier . If a resource with the given
identifier already exists it will be overwritten... | # Get experiment to ensure that it exists
if self . experiments_get ( experiment_id ) is None :
return None
return self . predictions . create_data_file_attachment ( run_id , resource_id , filename , mime_type = mime_type ) |
def normalize_layout ( layout , min_percentile = 1 , max_percentile = 99 , relative_margin = 0.1 ) :
"""Removes outliers and scales layout to between [ 0,1 ] .""" | # compute percentiles
mins = np . percentile ( layout , min_percentile , axis = ( 0 ) )
maxs = np . percentile ( layout , max_percentile , axis = ( 0 ) )
# add margins
mins -= relative_margin * ( maxs - mins )
maxs += relative_margin * ( maxs - mins )
# ` clip ` broadcasts , ` [ None ] ` s added only for readability
cl... |
def Get ( self , attribute , default = None ) :
"""Gets the attribute from this object .""" | if attribute is None :
return default
# Allow the user to specify the attribute by name .
elif isinstance ( attribute , str ) :
attribute = Attribute . GetAttributeByName ( attribute )
# We can ' t read attributes from the data _ store unless read mode was
# specified . It is ok to read new attributes though .
... |
def _update_offset_value ( self , f , offset , size , value ) :
'''Writes " value " into location " offset " in file " f " .''' | f . seek ( offset , 0 )
if ( size == 8 ) :
f . write ( struct . pack ( '>q' , value ) )
else :
f . write ( struct . pack ( '>i' , value ) ) |
def extend ( self , contents = None , optional_keys = None , allow_extra_keys = None , description = None , replace_optional_keys = False , ) :
"""This method allows you to create a new ` Dictionary ` that extends the current ` Dictionary ` with additional
contents and / or optional keys , and / or replaces the `... | optional_keys = set ( optional_keys or [ ] )
return Dictionary ( contents = type ( self . contents ) ( ( k , v ) for d in ( self . contents , contents ) for k , v in six . iteritems ( d ) ) if contents else self . contents , optional_keys = optional_keys if replace_optional_keys else self . optional_keys | optional_key... |
def cli ( ctx , dname , site ) :
"""Enable the < site > under the specified < domain >""" | assert isinstance ( ctx , Context )
dname = domain_parse ( dname ) . hostname
domain = Session . query ( Domain ) . filter ( Domain . name == dname ) . first ( )
if not domain :
click . secho ( 'No such domain: {dn}' . format ( dn = dname ) , fg = 'red' , bold = True , err = True )
return
site_name = site
site ... |
def filter_kwargs ( keys , kwargs ) :
""": param keys : A iterable key names to select items
: param kwargs : A dict or dict - like object reprensents keyword args
> > > list ( filter _ kwargs ( ( " a " , " b " ) , dict ( a = 1 , b = 2 , c = 3 , d = 4 ) ) )
[ ( ' a ' , 1 ) , ( ' b ' , 2 ) ]""" | for k in keys :
if k in kwargs :
yield ( k , kwargs [ k ] ) |
def list ( self ) :
"""List the users you have blocked .
: return : a list of : class : ` ~ groupy . api . blocks . Block ` ' s
: rtype : : class : ` list `""" | params = { 'user' : self . user_id }
response = self . session . get ( self . url , params = params )
blocks = response . data [ 'blocks' ]
return [ Block ( self , ** block ) for block in blocks ] |
def debug_reduce ( self , rule , tokens , parent , last_token_pos ) :
"""Customized format and print for our kind of tokens
which gets called in debugging grammar reduce rules""" | def fix ( c ) :
s = str ( c )
last_token_pos = s . find ( '_' )
if last_token_pos == - 1 :
return s
else :
return s [ : last_token_pos ]
prefix = ''
if parent and tokens :
p_token = tokens [ parent ]
if hasattr ( p_token , 'linestart' ) and p_token . linestart :
prefix = ... |
def glyph_metrics_stats ( ttFont ) :
"""Returns a dict containing whether the font seems _ monospaced ,
what ' s the maximum glyph width and what ' s the most common width .
For a font to be considered monospaced , at least 80 % of
the ascii glyphs must have the same width .""" | glyph_metrics = ttFont [ 'hmtx' ] . metrics
ascii_glyph_names = [ ttFont . getBestCmap ( ) [ c ] for c in range ( 32 , 128 ) if c in ttFont . getBestCmap ( ) ]
ascii_widths = [ adv for name , ( adv , lsb ) in glyph_metrics . items ( ) if name in ascii_glyph_names ]
ascii_width_count = Counter ( ascii_widths )
ascii_mos... |
def snmp_server_v3host_severity_level ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
snmp_server = ET . SubElement ( config , "snmp-server" , xmlns = "urn:brocade.com:mgmt:brocade-snmp" )
v3host = ET . SubElement ( snmp_server , "v3host" )
hostip_key = ET . SubElement ( v3host , "hostip" )
hostip_key . text = kwargs . pop ( 'hostip' )
username_key = ET . SubElement ( ... |
def wait_for_property ( self , name , cond = lambda val : val , level_sensitive = True ) :
"""Waits until ` ` cond ` ` evaluates to a truthy value on the named property . This can be used to wait for
properties such as ` ` idle _ active ` ` indicating the player is done with regular playback and just idling aroun... | sema = threading . Semaphore ( value = 0 )
def observer ( name , val ) :
if cond ( val ) :
sema . release ( )
self . observe_property ( name , observer )
if not level_sensitive or not cond ( getattr ( self , name . replace ( '-' , '_' ) ) ) :
sema . acquire ( )
self . unobserve_property ( name , observe... |
def check_nonstandard_section_name ( self ) :
'''Checking for an non - standard section name''' | std_sections = [ '.text' , '.bss' , '.rdata' , '.data' , '.rsrc' , '.edata' , '.idata' , '.pdata' , '.debug' , '.reloc' , '.stab' , '.stabstr' , '.tls' , '.crt' , '.gnu_deb' , '.eh_fram' , '.exptbl' , '.rodata' ]
for i in range ( 200 ) :
std_sections . append ( '/' + str ( i ) )
non_std_sections = [ ]
for section i... |
def purge_scenario ( scenario_id , ** kwargs ) :
"""Set the status of a scenario .""" | _check_can_edit_scenario ( scenario_id , kwargs [ 'user_id' ] )
user_id = kwargs . get ( 'user_id' )
scenario_i = _get_scenario ( scenario_id , user_id )
db . DBSession . delete ( scenario_i )
db . DBSession . flush ( )
return 'OK' |
def git_fetch ( repo_dir , remote = None , refspec = None , verbose = False , tags = True ) :
"""Do a git fetch of ` refspec ` in ` repo _ dir ` .
If ' remote ' is None , all remotes will be fetched .""" | command = [ 'git' , 'fetch' ]
if not remote :
command . append ( '--all' )
else :
remote = pipes . quote ( remote )
command . extend ( [ '--update-head-ok' ] )
if tags :
command . append ( '--tags' )
if verbose :
command . append ( '--verbose' )
if remote :
command . append ( remote )
if refspec :
... |
def _compute_shallow_site_response ( self , C , sites , pga1100 ) :
"""Returns the shallow site response term ( equation 11 , page 146)""" | stiff_factor = C [ 'c10' ] + ( C [ 'k2' ] * C [ 'n' ] )
# Initially default all sites to intermediate rock value
fsite = stiff_factor * np . log ( sites . vs30 / C [ 'k1' ] )
# Check for soft soil sites
idx = sites . vs30 < C [ 'k1' ]
if np . any ( idx ) :
pga_scale = np . log ( pga1100 [ idx ] + ( C [ 'c' ] * ( ( ... |
def population_analysis_summary_report ( feature , parent ) :
"""Retrieve an HTML population analysis table report from a multi exposure
analysis .""" | _ = feature , parent
# NOQA
analysis_dir = get_analysis_dir ( exposure_population [ 'key' ] )
if analysis_dir :
return get_impact_report_as_string ( analysis_dir )
return None |
def create ( cls , receiver_id , user_id = None ) :
"""Create an event instance .""" | event = cls ( id = uuid . uuid4 ( ) , receiver_id = receiver_id , user_id = user_id )
event . payload = event . receiver . extract_payload ( )
return event |
def calculate_sum ( n : int ) -> int :
"""This function computes the sum of integers from 1 up to and including n .
> > > calculate _ sum ( 30)
465
> > > calculate _ sum ( 100)
5050
> > > calculate _ sum ( 5)
15
> > > calculate _ sum ( 10)
55
> > > calculate _ sum ( 1)""" | return sum ( range ( 1 , n + 1 ) ) |
def get_formset ( self , request , obj = None , ** kwargs ) :
"""Load Synchronizer schema to display specific fields in admin""" | if obj is not None :
try : # this is enough to load the new schema
obj . external
except LayerExternal . DoesNotExist :
pass
return super ( LayerExternalInline , self ) . get_formset ( request , obj = None , ** kwargs ) |
def lookup_profiles ( self , provider , lookup ) :
'''Return a dictionary describing the configured profiles''' | if provider is None :
provider = 'all'
if lookup is None :
lookup = 'all'
if lookup == 'all' :
profiles = set ( )
provider_profiles = set ( )
for alias , info in six . iteritems ( self . opts [ 'profiles' ] ) :
providers = info . get ( 'provider' )
if providers :
given_pr... |
def newton_update ( x , a , c , step = 1.0 ) :
"""Given a value of x , return a better x
using newton - gauss""" | return x - step * np . linalg . inv ( hessian ( x , a ) ) . dot ( gradient ( x , a , c ) ) |
def run ( filename : 'python file generated by `rbnf` command, or rbnf sour file' , opt : 'optimize switch' = False ) :
"""You can apply immediate tests on your parser .
P . S : use ` - - opt ` option takes longer starting time .""" | from rbnf . easy import build_parser
import importlib . util
import traceback
full_path = Path ( filename )
base , ext = os . path . splitext ( str ( full_path ) )
full_path_str = str ( full_path )
if not ext :
if full_path . into ( '.py' ) . exists ( ) :
full_path_str = base + '.py'
elif Path ( base ) ... |
def reraise ( self , cause_cls_finder = None ) :
"""Re - raise captured exception ( possibly trying to recreate ) .""" | if self . _exc_info :
six . reraise ( * self . _exc_info )
else : # Attempt to regenerate the full chain ( and then raise
# from the root ) ; without a traceback , oh well . . .
root = None
parent = None
for cause in itertools . chain ( [ self ] , self . iter_causes ( ) ) :
if cause_cls_finder i... |
def to_string ( self , value ) :
"""String gets serialized and deserialized without quote marks .""" | if isinstance ( value , six . binary_type ) :
value = value . decode ( 'utf-8' )
return self . to_json ( value ) |
def search ( self , query_string , ** kwargs ) :
"""The main search method
: param query _ string : The string to pass to Elasticsearch . e . g . ' * : * '
: param kwargs : start _ offset , end _ offset , result _ class
: return : result _ class instance""" | self . index_name = self . _index_name_for_language ( translation . get_language ( ) )
# self . log . debug ( ' search method called ( % s ) : % s ' %
# ( translation . get _ language ( ) , query _ string ) )
return super ( ElasticsearchMultilingualSearchBackend , self ) . search ( query_string , ** kwargs ) |
def _map_relations ( relations , p , language = 'any' ) :
''': param : : class : ` list ` relations : Relations to be mapped . These are
concept or collection id ' s .
: param : : class : ` skosprovider . providers . VocabularyProvider ` p : Provider
to look up id ' s .
: param string language : Language to... | ret = [ ]
for r in relations :
c = p . get_by_id ( r )
if c :
ret . append ( _map_relation ( c , language ) )
else :
log . warning ( 'A relation references a concept or collection %d in provider %s that can not be found. Please check the integrity of your data.' % ( r , p . get_vocabulary_id... |
def add_summary_stats_to_table ( table_in , table_out , colnames ) :
"""Collect summary statisitics from an input table and add them to an output table
Parameters
table _ in : ` astropy . table . Table `
Table with the input data .
table _ out : ` astropy . table . Table `
Table with the output data .
c... | for col in colnames :
col_in = table_in [ col ]
stats = collect_summary_stats ( col_in . data )
for k , v in stats . items ( ) :
out_name = "%s_%s" % ( col , k )
col_out = Column ( data = np . vstack ( [ v ] ) , name = out_name , dtype = col_in . dtype , shape = v . shape , unit = col_in . u... |
def add_source_get_correlated ( gta , name , src_dict , correl_thresh = 0.25 , non_null_src = False ) :
"""Add a source and get the set of correlated sources
Parameters
gta : ` fermipy . gtaanalysis . GTAnalysis `
The analysis object
name : str
Name of the source we are adding
src _ dict : dict
Dictio... | if gta . roi . has_source ( name ) :
gta . zero_source ( name )
gta . update_source ( name )
test_src_name = "%s_test" % name
else :
test_src_name = name
gta . add_source ( test_src_name , src_dict )
gta . free_norm ( test_src_name )
gta . free_shape ( test_src_name , free = False )
fit_result = gta . f... |
async def check_user ( self , request , func = None , location = None , ** kwargs ) :
"""Check for user is logged and pass the given func .
: param func : user checker function , defaults to default _ user _ checker
: param location : where to redirect if user is not logged in .
May be either string ( URL ) o... | user = await self . load_user ( request )
func = func or self . cfg . default_user_checker
if not func ( user ) :
location = location or self . cfg . login_url
while callable ( location ) :
location = location ( request )
while asyncio . iscoroutine ( location ) :
location = await lo... |
def future_then_immediate ( future , func ) :
"""Returns a future that maps the result of ` future ` by ` func ` .
If ` future ` succeeds , sets the result of the returned future to ` func ( future . result ( ) ) ` . If
` future ` fails or ` func ` raises an exception , the exception is stored in the returned f... | result = concurrent . futures . Future ( )
def on_done ( f ) :
try :
result . set_result ( func ( f . result ( ) ) )
except Exception as e :
result . set_exception ( e )
future . add_done_callback ( on_done )
return result |
def attach_temporary_file ( self , service_desk_id , filename ) :
"""Create temporary attachment , which can later be converted into permanent attachment
: param service _ desk _ id : str
: param filename : str
: return : Temporary Attachment ID""" | headers = { 'X-Atlassian-Token' : 'no-check' , 'X-ExperimentalApi' : 'opt-in' }
url = 'rest/servicedeskapi/servicedesk/{}/attachTemporaryFile' . format ( service_desk_id )
with open ( filename , 'rb' ) as file :
result = self . post ( url , headers = headers , files = { 'file' : file } ) . get ( 'temporaryAttachmen... |
def clean ( ctx ) :
"""Clean Sphinx build products .
Use this command to clean out build products after a failed build , or
in preparation for running a build from a clean state .
This command removes the following directories from the
` ` pipelines _ lsst _ io ` ` directory :
- ` ` _ build ` ` ( the Sphi... | logger = logging . getLogger ( __name__ )
dirnames = [ 'py-api' , '_build' , 'modules' , 'packages' ]
dirnames = [ os . path . join ( ctx . obj [ 'root_project_dir' ] , dirname ) for dirname in dirnames ]
for dirname in dirnames :
if os . path . isdir ( dirname ) :
shutil . rmtree ( dirname )
logger... |
def add_subnet ( self , subnet , sync = True ) :
"""add a subnet to this OS instance .
: param subnet : the subnet to add on this OS instance
: param sync : If sync = True ( default ) synchronize with Ariane server . If sync = False ,
add the subnet object on list to be added on next save ( ) .
: return :""... | LOGGER . debug ( "OSInstance.add_subnet" )
if not sync :
self . subnets_2_add . append ( subnet )
else :
if subnet . id is None :
subnet . save ( )
if self . id is not None and subnet . id is not None :
params = { 'id' : self . id , 'subnetID' : subnet . id }
args = { 'http_operation... |
def extend_selection ( ) :
"""Checks is the selection is to be extended
The selection is to be extended , if a special modifier key ( typically < Ctrl > ) is being pressed .
: return : If to extend the selection
: rtype : True""" | from rafcon . gui . singleton import main_window_controller
currently_pressed_keys = main_window_controller . currently_pressed_keys if main_window_controller else set ( )
if any ( key in currently_pressed_keys for key in [ constants . EXTEND_SELECTION_KEY , constants . EXTEND_SELECTION_KEY_ALT ] ) :
return True
re... |
def _post ( url , headers = { } , data = None , files = None ) :
"""Tries to POST data to an endpoint""" | try :
response = requests . post ( url , headers = headers , data = data , files = files , verify = VERIFY_SSL )
return _process_response ( response )
except requests . exceptions . RequestException as e :
_log_and_raise_exception ( 'Error connecting with foursquare API' , e ) |
def calculate_grid ( self ) :
"""Calculates and stores grid structure""" | if self . grid is None :
self . grid = self . get_wellseries ( self . get_grid ( ) )
if self . grid_transposed is None :
self . grid_transposed = self . get_wellseries ( self . transpose ( self . get_grid ( ) ) ) |
def _small_mrca ( self , ts ) :
"""Find a MRCA using query parameters .
This only supports a limited number of tax _ ids ; ` ` _ large _ mrca ` ` will
support an arbitrary number .""" | cursor = self . db . cursor ( )
qmarks = ', ' . join ( '?' * len ( ts ) )
cursor . execute ( """
SELECT parent
FROM parents
JOIN taxa
ON parent = taxa.tax_id
JOIN ranks USING (rank)
WHERE child IN (%s)
GROUP B... |
def slas_policies_reorder ( self , data , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / core / sla _ policies # reorder - sla - policies" | api_path = "/api/v2/slas/policies/reorder.json"
return self . call ( api_path , method = "PUT" , data = data , ** kwargs ) |
def _bisect_kmeans ( X , n_clusters , n_trials , max_iter , tol ) :
"""Apply Bisecting Kmeans clustering
to reach n _ clusters number of clusters""" | membs = np . empty ( shape = X . shape [ 0 ] , dtype = int )
centers = dict ( )
# np . empty ( shape = ( n _ clusters , X . shape [ 1 ] ) , dtype = float )
sse_arr = dict ( )
# -1.0 * np . ones ( shape = n _ clusters , dtype = float )
# # data structure to store cluster hierarchies
tree = treelib . Tree ( )
tree = _add... |
def header ( self ) :
'''Provide PLY - formatted metadata for the instance .''' | lines = [ 'ply' ]
if self . text :
lines . append ( 'format ascii 1.0' )
else :
lines . append ( 'format ' + _byte_order_reverse [ self . byte_order ] + ' 1.0' )
# Some information is lost here , since all comments are placed
# between the ' format ' line and the first element .
for c in self . comments :
l... |
def merge ( self ) :
"""Merge contained schemas into one .
@ return : The merged schema .
@ rtype : L { Schema }""" | if self . children :
schema = self . children [ 0 ]
for s in self . children [ 1 : ] :
schema . merge ( s )
return schema |
def get_data ( self , * , save_data = False , data_filter = None , redownload = False , max_threads = None , raise_download_errors = True ) :
"""Get requested data either by downloading it or by reading it from the disk ( if it
was previously downloaded and saved ) .
: param save _ data : flag to turn on / off ... | self . _preprocess_request ( save_data , True )
data_list = self . _execute_data_download ( data_filter , redownload , max_threads , raise_download_errors )
return self . _add_saved_data ( data_list , data_filter , raise_download_errors ) |
def update_device ( name , ** kwargs ) :
'''. . versionadded : : 2019.2.0
Add attributes to an existing device , identified by name .
name
The name of the device , e . g . , ` ` edge _ router ` `
kwargs
Arguments to change in device , e . g . , ` ` serial = JN2932930 ` `
CLI Example :
. . code - block... | kwargs = __utils__ [ 'args.clean_kwargs' ] ( ** kwargs )
nb_device = _get ( 'dcim' , 'devices' , auth_required = True , name = name )
for k , v in kwargs . items ( ) :
setattr ( nb_device , k , v )
try :
nb_device . save ( )
return { 'dcim' : { 'devices' : kwargs } }
except RequestError as e :
log . err... |
def check_unknown_fields ( self , data , original_data ) :
"""Check for unknown keys .""" | if isinstance ( original_data , list ) :
for elem in original_data :
self . check_unknown_fields ( data , elem )
else :
for key in original_data :
if key not in [ self . fields [ field ] . attribute or field for field in self . fields ] :
raise ValidationError ( 'Unknown field name {... |
def checksum_identity_card_number ( characters ) :
"""Calculates and returns a control digit for given list of characters basing on Identity Card Number standards .""" | weights_for_check_digit = [ 7 , 3 , 1 , 0 , 7 , 3 , 1 , 7 , 3 ]
check_digit = 0
for i in range ( 3 ) :
check_digit += weights_for_check_digit [ i ] * ( ord ( characters [ i ] ) - 55 )
for i in range ( 4 , 9 ) :
check_digit += weights_for_check_digit [ i ] * characters [ i ]
check_digit %= 10
return check_digit |
def using_hg ( cwd ) :
"""Test whether the directory cwd is contained in a mercurial
repository .""" | try :
hg_log = shell_out ( [ "hg" , "log" ] , cwd = cwd )
return True
except ( CalledProcessError , OSError ) :
return False |
def _do_upgrade ( self ) :
"""open websocket connection""" | self . current . output [ 'cmd' ] = 'upgrade'
self . current . output [ 'user_id' ] = self . current . user_id
self . terminate_existing_login ( )
self . current . user . bind_private_channel ( self . current . session . sess_id )
user_sess = UserSessionID ( self . current . user_id )
user_sess . set ( self . current .... |
def line ( self , x_0 , y_0 , x_1 , y_1 , color ) : # pylint : disable = too - many - arguments
"""Bresenham ' s line algorithm""" | d_x = abs ( x_1 - x_0 )
d_y = abs ( y_1 - y_0 )
x , y = x_0 , y_0
s_x = - 1 if x_0 > x_1 else 1
s_y = - 1 if y_0 > y_1 else 1
if d_x > d_y :
err = d_x / 2.0
while x != x_1 :
self . pixel ( x , y , color )
err -= d_y
if err < 0 :
y += s_y
err += d_x
x += s_... |
def get_assessment_offered_admin_session ( self , proxy ) :
"""Gets the ` ` OsidSession ` ` associated with the assessment offered administration service .
arg : proxy ( osid . proxy . Proxy ) : a proxy
return : ( osid . assessment . AssessmentOfferedAdminSession ) - an
` ` AssessmentOfferedAdminSession ` `
... | if not self . supports_assessment_offered_admin ( ) :
raise errors . Unimplemented ( )
# pylint : disable = no - member
return sessions . AssessmentOfferedAdminSession ( proxy = proxy , runtime = self . _runtime ) |
async def _watchdog ( self , timeout ) :
"""Trigger and cancel the watchdog after timeout . Call callback .""" | await asyncio . sleep ( timeout , loop = self . loop )
_LOGGER . debug ( "Watchdog triggered!" )
await self . cancel_watchdog ( )
await self . _watchdog_cb ( ) |
def CopyToDateTimeString ( self ) :
"""Copies the time elements to a date and time string .
Returns :
str : date and time value formatted as : " YYYY - MM - DD hh : mm : ss " or None
if time elements are missing .""" | if self . _number_of_seconds is None :
return None
return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}' . format ( self . _time_elements_tuple [ 0 ] , self . _time_elements_tuple [ 1 ] , self . _time_elements_tuple [ 2 ] , self . _time_elements_tuple [ 3 ] , self . _time_elements_tuple [ 4 ] , self . _time_elem... |
def send_message ( self , subject_or_message : Optional [ Union [ Message , str ] ] = None , to : Optional [ Union [ str , List [ str ] ] ] = None , ** kwargs ) :
"""Send an email using the send function as configured by
: attr : ` ~ flask _ unchained . bundles . mail . config . Config . MAIL _ SEND _ FN ` .
: ... | to = to or kwargs . pop ( 'recipients' , [ ] )
return self . send ( subject_or_message , to , ** kwargs ) |
def list_wallet_names ( api_key , is_hd_wallet = False , coin_symbol = 'btc' ) :
'''Get all the wallets belonging to an API key''' | assert is_valid_coin_symbol ( coin_symbol ) , coin_symbol
assert api_key
params = { 'token' : api_key }
kwargs = dict ( wallets = 'hd' if is_hd_wallet else '' )
url = make_url ( coin_symbol , ** kwargs )
r = requests . get ( url , params = params , verify = True , timeout = TIMEOUT_IN_SECONDS )
return get_valid_json ( ... |
def doDelete ( self , WHAT = { } ) :
"""This function will perform the command - delete .""" | if hasattr ( WHAT , '_modified' ) :
self . _addDBParam ( 'RECORDID' , WHAT . RECORDID )
self . _addDBParam ( 'MODID' , WHAT . MODID )
elif type ( WHAT ) == dict and WHAT . has_key ( 'RECORDID' ) :
self . _addDBParam ( 'RECORDID' , WHAT [ 'RECORDID' ] )
else :
raise FMError , 'Python Runtime: Object type... |
def post ( self , request , * args , ** kwargs ) :
"""Post a service request ( requires authentication )""" | service_code = request . data [ 'service_code' ]
if service_code not in SERVICES . keys ( ) :
return Response ( { 'detail' : _ ( 'Service not found' ) } , status = 404 )
serializers = { 'node' : NodeRequestSerializer , 'vote' : VoteRequestSerializer , 'comment' : CommentRequestSerializer , 'rate' : RatingRequestSer... |
def PackageVariable ( key , help , default , searchfunc = None ) : # NB : searchfunc is currently undocumented and unsupported
"""The input parameters describe a ' package list ' option , thus they
are returned with the correct converter and validator appended . The
result is usable for input to opts . Add ( ) ... | help = '\n ' . join ( ( help , '( yes | no | /path/to/%s )' % key ) )
return ( key , help , default , lambda k , v , e : _validator ( k , v , e , searchfunc ) , _converter ) |
def usufyToJsonExport ( d , fPath ) :
"""Workaround to export to a json file .
Args :
d : Data to export .
fPath : File path for the output file .""" | oldData = [ ]
try :
with open ( fPath ) as iF :
oldText = iF . read ( )
if oldText != "" :
oldData = json . loads ( oldText )
except : # No file found , so we will create it . . .
pass
jsonText = json . dumps ( oldData + d , indent = 2 , sort_keys = True )
with open ( fPath , "w" ) a... |
async def put_annotations ( self , annotation ) :
"""PUT / api / annotations / { annotation } . { _ format }
Updates an annotation .
: param annotation \ w + string The annotation ID
Will returns annotation for this entry
: return data related to the ext""" | params = { 'access_token' : self . token }
url = '/api/annotations/{annotation}.{ext}' . format ( annotation = annotation , ext = self . format )
return await self . query ( url , "put" , ** params ) |
def refs ( self , multihash , ** kwargs ) :
"""Returns a list of hashes of objects referenced by the given hash .
. . code - block : : python
> > > c . refs ( ' QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D ' )
[ { ' Ref ' : ' Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7 . . . cNMV ' , ' Err ' : ' ' } ,
{ ' Ref ' ... | args = ( multihash , )
return self . _client . request ( '/refs' , args , decoder = 'json' , ** kwargs ) |
def lookup_matching ( self , urls ) :
"""Get matching hosts for the given URLs .
: param urls : an iterable containing URLs
: returns : instances of AddressListItem representing listed
hosts matching the ones used by the given URLs
: raises InvalidURLError : if there are any invalid URLs in
the sequence""... | hosts = ( urlparse ( u ) . hostname for u in urls )
for val in hosts :
item = self . lookup ( val )
if item is not None :
yield item |
def from_frequency ( cls , freq ) :
"""Construct a : class : ` Tone ` from a frequency specified in ` Hz ` _ which
must be a positive floating - point value in the range 0 < freq < = 20000.
. . _ Hz : https : / / en . wikipedia . org / wiki / Hertz""" | if 0 < freq <= 20000 :
return super ( Tone , cls ) . __new__ ( cls , freq )
raise ValueError ( 'invalid frequency: %.2f' % freq ) |
def assims ( self , mot ) :
"""Cherche si la chaîne a peut subir une assimilation , renvoie cette chaîne éventuellement assimilée .
: param mot : Mot pour lequel on doit vérifier des assimilations
: type mot : str
: return : Mot assimilé
: rtype : str""" | for replaced , replacement in self . _assimsq . items ( ) :
if mot . startswith ( replaced ) :
mot = mot . replace ( replaced , replacement )
return mot
return mot |
def from_hising ( cls , h , J , offset = None ) :
"""Construct a binary polynomial from a higher - order Ising problem .
Args :
h ( dict ) :
The linear biases .
J ( dict ) :
The higher - order biases .
offset ( optional , default = 0.0 ) :
Constant offset applied to the model .
Returns :
: obj : `... | poly = { ( k , ) : v for k , v in h . items ( ) }
poly . update ( J )
if offset is not None :
poly [ frozenset ( [ ] ) ] = offset
return cls ( poly , Vartype . SPIN ) |
def create_app ( ) :
"""Flask application factory""" | # Setup Flask app and app . config
app = Flask ( __name__ )
app . config . from_object ( __name__ + '.ConfigClass' )
# Initialize Flask extensions
db = Flywheel ( app )
# Initialize Flask - Flywheel
mail = Mail ( app )
# Initialize Flask - Mail
# Define the User data model . Make sure to add flask _ user UserMixin ! ! ... |
def notes_to_positions ( notes , root ) :
"""Get notes positions .
ex ) notes _ to _ positions ( [ " C " , " E " , " G " ] , " C " ) - > [ 0 , 4 , 7]
: param list [ str ] notes : list of notes
: param str root : the root note
: rtype : list [ int ]
: return : list of note positions""" | root_pos = note_to_val ( root )
current_pos = root_pos
positions = [ ]
for note in notes :
note_pos = note_to_val ( note )
if note_pos < current_pos :
note_pos += 12 * ( ( current_pos - note_pos ) // 12 + 1 )
positions . append ( note_pos - root_pos )
current_pos = note_pos
return positions |
def ng_get_scope_property ( self , element , prop ) :
""": Description : Will return value of property of element ' s scope .
: Warning : This will only work for angular . js 1 . x .
: Warning : Requires angular debugging to be enabled .
: param element : Element for browser instance to target .
: param pro... | return self . browser . execute_script ( 'return angular.element(arguments[0]).scope()%s;' % self . __d2b_notation ( prop = prop ) , element ) |
def list ( self , end = values . unset , start = values . unset , limit = None , page_size = None ) :
"""Lists DataSessionInstance records from the API as a list .
Unlike stream ( ) , this operation is eager and will load ` limit ` records into
memory before returning .
: param datetime end : The end
: para... | return list ( self . stream ( end = end , start = start , limit = limit , page_size = page_size , ) ) |
def to_frequencyseries ( self , delta_f = None ) :
"""Return the Fourier transform of this time series
Parameters
delta _ f : { None , float } , optional
The frequency resolution of the returned frequency series . By
default the resolution is determined by the duration of the timeseries .
Returns
Freque... | from pycbc . fft import fft
if not delta_f :
delta_f = 1.0 / self . duration
# add 0.5 to round integer
tlen = int ( 1.0 / delta_f / self . delta_t + 0.5 )
flen = int ( tlen / 2 + 1 )
if tlen < len ( self ) :
raise ValueError ( "The value of delta_f (%s) would be " "undersampled. Maximum delta_f " "is %s." % ( ... |
def rellink_to ( self , target , force = False ) :
"""Make this path a symlink pointing to the given * target * , generating the
proper relative path using : meth : ` make _ relative ` . This gives different
behavior than : meth : ` symlink _ to ` . For instance , ` ` Path
( ' a / b ' ) . symlink _ to ( ' c '... | target = self . __class__ ( target )
if force :
self . try_unlink ( )
if self . is_absolute ( ) :
target = target . absolute ( )
# force absolute link
return self . symlink_to ( target . make_relative ( self . parent ) ) |
def _register_with_pkg_resources ( cls ) :
"""Ensure package resources can be loaded from this loader . May be called
multiple times , as the operation is idempotent .""" | try :
import pkg_resources
# access an attribute in case a deferred importer is present
pkg_resources . __name__
except ImportError :
return
# Since pytest tests are always located in the file system , the
# DefaultProvider is appropriate .
pkg_resources . register_loader_type ( cls , pkg_resources . De... |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'text' ) and self . text is not None :
_dict [ 'text' ] = self . text
if hasattr ( self , 'keywords' ) and self . keywords is not None :
_dict [ 'keywords' ] = [ x . _to_dict ( ) for x in self . keywords ]
return _dict |
def accept ( self ) :
"""Get the Accept option of a request .
: return : the Accept value or None if not specified by the request
: rtype : String""" | for option in self . options :
if option . number == defines . OptionRegistry . ACCEPT . number :
return option . value
return None |
def defer ( self , opres ) :
"""Converts a raw : class : ` couchbase . results . AsyncResult ` object
into a : class : ` Deferred ` .
This is shorthand for the following " non - idiom " : :
d = Deferred ( )
opres = cb . upsert ( " foo " , " bar " )
opres . callback = d . callback
def d _ err ( res , ex ... | d = Deferred ( )
opres . callback = d . callback
def _on_err ( mres , ex_type , ex_val , ex_tb ) :
try :
raise ex_type ( ex_val )
except CouchbaseError :
d . errback ( )
opres . errback = _on_err
return d |
def gen_oui_str ( self , oui_list ) :
"""Generate the OUI string for vdptool .""" | oui_str = [ ]
for oui in oui_list :
oui_str . append ( '-c' )
oui_str . append ( oui )
return oui_str |
def venv ( ) :
"""Install venv + deps .""" | try :
import virtualenv
# NOQA
except ImportError :
sh ( "%s -m pip install virtualenv" % PYTHON )
if not os . path . isdir ( "venv" ) :
sh ( "%s -m virtualenv venv" % PYTHON )
sh ( "venv\\Scripts\\pip install -r %s" % ( REQUIREMENTS_TXT ) ) |
def run_commands_from_slack_async ( self , message_generator , fire_all , tag , control , interval = 1 ) :
'''Pull any pending messages from the message _ generator , sending each
one to either the event bus , the command _ async or both , depending on
the values of fire _ all and command''' | outstanding = { }
# set of job _ id that we need to check for
while True :
log . trace ( 'Sleeping for interval of %s' , interval )
time . sleep ( interval )
# Drain the slack messages , up to 10 messages at a clip
count = 0
for msg in message_generator : # The message _ generator yields dicts . Lea... |
def detach ( self , sync = True ) :
"""Detach this result from its parent session by fetching the
remainder of this result from the network into the buffer .
: returns : number of records fetched""" | if self . attached ( ) :
return self . _session . detach ( self , sync = sync )
else :
return 0 |
def spkaps ( targ , et , ref , abcorr , stobs , accobs ) :
"""Given the state and acceleration of an observer relative to the
solar system barycenter , return the state ( position and velocity )
of a target body relative to the observer , optionally corrected
for light time and stellar aberration . All input ... | targ = ctypes . c_int ( targ )
et = ctypes . c_double ( et )
ref = stypes . stringToCharP ( ref )
abcorr = stypes . stringToCharP ( abcorr )
stobs = stypes . toDoubleVector ( stobs )
accobs = stypes . toDoubleVector ( accobs )
starg = stypes . emptyDoubleVector ( 6 )
lt = ctypes . c_double ( )
dlt = ctypes . c_double (... |
def delete_rule ( self , rule_name ) :
"""Delete a CWE rule .
This deletes them , but they will still show up in the AWS console .
Annoying .""" | logger . debug ( 'Deleting existing rule {}' . format ( rule_name ) )
# All targets must be removed before
# we can actually delete the rule .
try :
targets = self . events_client . list_targets_by_rule ( Rule = rule_name )
except botocore . exceptions . ClientError as e : # This avoids misbehavior if low permissio... |
def dst ( self , dt ) :
"""Calculate delta for daylight saving .""" | # Daylight saving starts on the second Sunday of March at 2AM standard
dst_start_date = self . first_sunday ( dt . year , 3 ) + timedelta ( days = 7 ) + timedelta ( hours = 2 )
# Daylight saving ends on the first Sunday of November at 2AM standard
dst_end_date = self . first_sunday ( dt . year , 11 ) + timedelta ( hour... |
def ensure_auth_scope ( self , instance ) :
"""Guarantees a valid auth scope for this instance , and returns it
Communicates with the identity server and initializes a new scope when one is absent , or has been forcibly
removed due to token expiry""" | instance_scope = None
custom_tags = instance . get ( 'tags' , [ ] )
if custom_tags is None :
custom_tags = [ ]
try :
instance_scope = self . get_scope_for_instance ( instance )
except KeyError : # We ' re missing a project scope for this instance
# Let ' s populate it now
try :
if 'auth_scope' in in... |
def _normalize_codec ( codec , _cache = { } ) :
"""Raises LookupError""" | try :
return _cache [ codec ]
except KeyError :
_cache [ codec ] = codecs . lookup ( codec ) . name
return _cache [ codec ] |
def _draw_outer_connector ( context , width , height ) :
"""Draw the outer connector for container states
Connector for container states can be connected from the inside and the outside . Thus the connector is split
in two parts : A rectangle on the inside and an arrow on the outside . This method draws the out... | c = context
# Current pos is center
# Arrow is drawn upright
arrow_height = height / 2.5
gap = height / 6.
connector_height = ( height - gap ) / 2.
# Move to bottom left corner of outer connector
c . rel_move_to ( - width / 2. , - gap / 2. )
# Draw line to bottom right corner
c . rel_line_to ( width , 0 )
# Draw line t... |
def getShocks ( self ) :
'''Gets permanent and transitory income shocks for this period . Samples from IncomeDstn for
each period in the cycle . This is a copy - paste from IndShockConsumerType , with the
addition of the Markov macroeconomic state . Unfortunately , the getShocks method for
MarkovConsumerType ... | PermShkNow = np . zeros ( self . AgentCount )
# Initialize shock arrays
TranShkNow = np . zeros ( self . AgentCount )
newborn = self . t_age == 0
for t in range ( self . T_cycle ) :
these = t == self . t_cycle
N = np . sum ( these )
if N > 0 :
IncomeDstnNow = self . IncomeDstn [ t - 1 ] [ self . Mrk... |
def all ( self ) :
"""Returns list with all indexed identifiers .""" | identifiers = [ ]
query = text ( """
SELECT identifier, type, name
FROM identifier_index;""" )
for result in self . backend . library . database . connection . execute ( query ) :
vid , type_ , name = result
res = IdentifierSearchResult ( score = 1 , vid = vid , type = type_ , name = nam... |
def show ( self ) :
"""Display the information ( with a pretty print ) about the field""" | bytecode . _PrintSubBanner ( "Field Information" )
bytecode . _PrintDefault ( "{}->{} {} [access_flags={}]\n" . format ( self . get_class_name ( ) , self . get_name ( ) , self . get_descriptor ( ) , self . get_access_flags_string ( ) ) )
init_value = self . get_init_value ( )
if init_value is not None :
bytecode . ... |
def unique ( values ) :
'''Removes duplicates from a list .
. . code - block : : jinja
{ % set my _ list = [ ' a ' , ' b ' , ' c ' , ' a ' , ' b ' ] - % }
{ { my _ list | unique } }
will be rendered as :
. . code - block : : text
[ ' a ' , ' b ' , ' c ' ]''' | ret = None
if isinstance ( values , collections . Hashable ) :
ret = set ( values )
else :
ret = [ ]
for value in values :
if value not in ret :
ret . append ( value )
return ret |
def CreateEvent ( self , EventId , Caption , Hint ) :
"""Creates a custom event displayed in Skype client ' s events pane .
: Parameters :
EventId : unicode
Unique identifier for the event .
Caption : unicode
Caption text .
Hint : unicode
Hint text . Shown when mouse hoovers over the event .
: retur... | self . _Skype . _DoCommand ( 'CREATE EVENT %s CAPTION %s HINT %s' % ( tounicode ( EventId ) , quote ( tounicode ( Caption ) ) , quote ( tounicode ( Hint ) ) ) )
return PluginEvent ( self . _Skype , EventId ) |
def search ( self , CorpNum , DType , SDate , EDate , State , ItemCode , Page , PerPage , Order , UserID = None , QString = None ) :
"""목록 조회
args
CorpNum : 팝빌회원 사업자번호
DType : 일자유형 , R - 등록일시 , W - 작성일자 , I - 발행일시 중 택 1
SDate : 시작일자 , 표시형식 ( yyy... | if DType == None or DType == '' :
raise PopbillException ( - 99999999 , "일자유형이 입력되지 않았습니다." )
if SDate == None or SDate == '' :
raise PopbillException ( - 99999999 , "시작일자가 입력되지 않았습니다." )
if EDate == None or EDate == '' :
raise PopbillException ( - 99999999 , "종료일자가 입력되지 않았습니다." )
uri = '/Statement/Search'
... |
def get_unit_by_name ( self , unit_name : str ) -> typing . Optional [ 'BaseUnit' ] :
"""Gets a unit from its name
Args :
unit _ name : unit name
Returns :""" | VALID_STR . validate ( unit_name , 'get_unit_by_name' )
for unit in self . units :
if unit . unit_name == unit_name :
return unit
return None |
def login ( self , username , password ) :
"""Log into a user .
Parameters
username : str
The username .
password : str
The password .
Returns
bool
True if the login is successful , False otherwise .
result
A dict containing the authentication secret with the key AUTH _ KEY
if the login is suc... | result = { pytwis_constants . ERROR_KEY : None }
# Get the user - id based on the username .
userid = self . _rc . hget ( pytwis_constants . USERS_KEY , username )
if userid is None :
result [ pytwis_constants . ERROR_KEY ] = pytwis_constants . ERROR_USERNAME_NOT_EXIST_FORMAT . format ( username )
return ( Fals... |
def comments ( self ) :
"""Returns a queryset of the published comments .""" | return self . discussions . filter ( Q ( flags = None ) | Q ( flags__flag = CommentFlag . MODERATOR_APPROVAL ) ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.