signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _u0Eq ( logu , delta , pot , E , Lz22 ) :
"""The equation that needs to be minimized to find u0""" | u = numpy . exp ( logu )
sinh2u = numpy . sinh ( u ) ** 2.
cosh2u = numpy . cosh ( u ) ** 2.
dU = cosh2u * actionAngleStaeckel . potentialStaeckel ( u , numpy . pi / 2. , pot , delta )
return - ( E * sinh2u - dU - Lz22 / delta ** 2. / sinh2u ) |
def write ( self , data , echo = None ) :
"""Write data to channel .
Args :
data ( bytes ) : The data to write to the channel .
echo ( bool ) : Whether to echo the written data to stdout .
Raises :
EOFError : If the channel was closed before all data was sent .""" | if echo or ( echo is None and self . echo ) :
sys . stdout . write ( data . decode ( 'latin1' ) )
sys . stdout . flush ( )
self . channel . write ( data ) |
def _compute_results ( self ) :
"""Computes the optimum and its value .""" | self . Y_best = best_value ( self . Y )
self . x_opt = self . X [ np . argmin ( self . Y ) , : ]
self . fx_opt = np . min ( self . Y ) |
def clean_path ( path ) :
"""Clean the path""" | path = path . replace ( os . sep , '/' )
if path . startswith ( './' ) :
path = path [ 2 : ]
return path |
def emit ( self , span_datas ) :
""": type span _ datas : list of : class :
` ~ opencensus . trace . span _ data . SpanData `
: param list of opencensus . trace . span _ data . SpanData span _ datas :
SpanData tuples to emit""" | with open ( self . file_name , self . file_mode ) as file : # convert to the legacy trace json for easier refactoring
# TODO : refactor this to use the span data directly
legacy_trace_json = span_data . format_legacy_trace_json ( span_datas )
trace_str = json . dumps ( legacy_trace_json )
file . write ( tra... |
def get_enabled ( name , app ) :
'''Get ( and load ) entrypoints registered on name
and enabled for the given app .''' | plugins = app . config [ 'PLUGINS' ]
return dict ( _ep_to_kv ( e ) for e in iter_all ( name ) if e . name in plugins ) |
def _calculateXi ( self , r ) :
"""NAME :
_ calculateXi
PURPOSE :
Calculate xi given r
INPUT :
r - Evaluate at radius r
OUTPUT :
xi
HISTORY :
2016-05-18 - Written - Aladdin""" | a = self . _a
return ( r - a ) / ( r + a ) |
def invoke_contract_fn ( self , contract_hash , operation , params = None , id = None , endpoint = None ) :
"""Invokes a contract
Args :
contract _ hash : ( str ) hash of the contract , for example ' d7678dd97c000be3f33e9362e673101bac4ca654'
operation : ( str ) the operation to call on the contract
params :... | return self . _call_endpoint ( INVOKE_FUNCTION , params = [ contract_hash , operation , params if params else [ ] ] , id = id , endpoint = endpoint ) |
def package_contents ( package , with_pkg = False , with_mod = True , ignore_prefix = [ ] , ignore_suffix = [ ] ) :
r"""References :
http : / / stackoverflow . com / questions / 1707709 / list - all - the - modules - that - are - part - of - a - python - package
Args :
package ( ? ) :
with _ pkg ( bool ) : ... | import pkgutil
if not hasattr ( package , '__path__' ) :
return [ package . __name__ ]
# pass
print ( 'package = %r' % ( package , ) )
walker = pkgutil . walk_packages ( package . __path__ , prefix = package . __name__ + '.' , onerror = lambda x : None )
module_list = [ ]
for importer , modname , ispkg in walker :
... |
def searchInAleph ( base , phrase , considerSimilar , field ) :
"""Send request to the aleph search engine .
Request itself is pretty useless , but it can be later used as parameter
for : func : ` getDocumentIDs ` , which can fetch records from Aleph .
Args :
base ( str ) : which database you want to use
... | downer = Downloader ( )
if field . lower ( ) not in VALID_ALEPH_FIELDS :
raise InvalidAlephFieldException ( "Unknown field '" + field + "'!" )
param_url = Template ( SEARCH_URL_TEMPLATE ) . substitute ( PHRASE = quote_plus ( phrase ) , # urlencode phrase
BASE = base , FIELD = field , SIMILAR = "Y" if considerSimila... |
def _get_account_policy ( name ) :
'''Get the entire accountPolicy and return it as a dictionary . For use by this
module only
: param str name : The user name
: return : a dictionary containing all values for the accountPolicy
: rtype : dict
: raises : CommandExecutionError on user not found or any other... | cmd = 'pwpolicy -u {0} -getpolicy' . format ( name )
try :
ret = salt . utils . mac_utils . execute_return_result ( cmd )
except CommandExecutionError as exc :
if 'Error: user <{0}> not found' . format ( name ) in exc . strerror :
raise CommandExecutionError ( 'User not found: {0}' . format ( name ) )
... |
def features ( self ) :
"""A ` ` set ` ` of implementation features specified in this signature , if any . Otherwise , an empty ` ` set ` ` .""" | if 'Features' in self . _signature . subpackets :
return next ( iter ( self . _signature . subpackets [ 'Features' ] ) ) . flags
return set ( ) |
def _DeleteClientActionRequest ( self , to_delete , cursor = None ) :
"""Builds deletes for client messages .""" | query = "DELETE FROM client_action_requests WHERE "
conditions = [ ]
args = [ ]
for client_id , flow_id , request_id in to_delete :
conditions . append ( "(client_id=%s AND flow_id=%s AND request_id=%s)" )
args . append ( db_utils . ClientIDToInt ( client_id ) )
args . append ( db_utils . FlowIDToInt ( flow... |
def peering_connection_pending_from_vpc ( conn_id = None , conn_name = None , vpc_id = None , vpc_name = None , region = None , key = None , keyid = None , profile = None ) :
'''Check if a VPC peering connection is in the pending state , and requested from the given VPC .
. . versionadded : : 2016.11.0
conn _ i... | if not _exactly_one ( ( conn_id , conn_name ) ) :
raise SaltInvocationError ( 'Exactly one of conn_id or conn_name must be provided.' )
if not _exactly_one ( ( vpc_id , vpc_name ) ) :
raise SaltInvocationError ( 'Exactly one of vpc_id or vpc_name must be provided.' )
if vpc_name :
vpc_id = check_vpc ( vpc_n... |
def _std_tuple_of ( var = None , std = None , interval = None ) :
"""Convienence function for plotting . Given one of var , standard
deviation , or interval , return the std . Any of the three can be an
iterable list .
Examples
> > > _ std _ tuple _ of ( var = [ 1 , 3 , 9 ] )
(1 , 2 , 3)""" | if std is not None :
if np . isscalar ( std ) :
std = ( std , )
return std
if interval is not None :
if np . isscalar ( interval ) :
interval = ( interval , )
return norm . interval ( interval ) [ 1 ]
if var is None :
raise ValueError ( "no inputs were provided" )
if np . isscalar ( ... |
def create_db ( ) :
"Create database ." | from . . ext import db
db . create_all ( )
# Evolution support
from flask import current_app
from flaskext . evolution import db as evolution_db
evolution_db . init_app ( current_app )
evolution_db . create_all ( )
print "Database created successfuly" |
def get_instance ( self , payload ) :
"""Build an instance of FieldValueInstance
: param dict payload : Payload response from the API
: returns : twilio . rest . autopilot . v1 . assistant . field _ type . field _ value . FieldValueInstance
: rtype : twilio . rest . autopilot . v1 . assistant . field _ type .... | return FieldValueInstance ( self . _version , payload , assistant_sid = self . _solution [ 'assistant_sid' ] , field_type_sid = self . _solution [ 'field_type_sid' ] , ) |
def from_version ( self , version , require_https = False ) :
"""Create a Hive object based on the information in the object
and the version passed into the method .""" | if version is None or self . version ( ) == version :
return self
else :
return Hive . from_url ( self . get_version_url ( version ) , require_https = require_https ) |
def load ( self , refobj ) :
"""Load the given refobject
Load in this case means , that a reference is already in the scene
but it is not in a loaded state .
Loading the reference means , that the actual data will be read .
This will call : meth : ` ReftypeInterface . load ` .
: param refobj : the refobje... | inter = self . get_typ_interface ( self . get_typ ( refobj ) )
ref = self . get_reference ( refobj )
inter . load ( refobj , ref ) |
def toSet ( self , flags ) :
"""Generates a flag value based on the given set of values .
: param values : < set >
: return : < int >""" | return { key for key , value in self . items ( ) if value & flags } |
def flip_alleles ( genotypes ) :
"""Flip the alleles of an Genotypes instance .""" | warnings . warn ( "deprecated: use 'Genotypes.flip_coded'" , DeprecationWarning )
genotypes . reference , genotypes . coded = ( genotypes . coded , genotypes . reference )
genotypes . genotypes = 2 - genotypes . genotypes
return genotypes |
def delete ( self , kwargs ) :
"""Delete an item
Parameters
kwargs : dict
The primary key of the item to delete""" | self . _to_delete . append ( kwargs )
if self . should_flush ( ) :
self . flush ( ) |
def get_application_logo_label ( self ) :
"""Provides the default * * Application _ Logo _ label * * widget .
: return : Application logo label .
: rtype : QLabel""" | logo_label = QLabel ( )
logo_label . setObjectName ( "Application_Logo_label" )
logo_label . setPixmap ( QPixmap ( umbra . ui . common . get_resource_path ( UiConstants . logo_image ) ) )
return logo_label |
def _is_version_range ( req ) :
"""Returns true if requirements specify a version range .""" | assert len ( req . specifier ) > 0
specs = list ( req . specifier )
if len ( specs ) == 1 : # " foo > 2.0 " or " foo = = 2.4.3"
return specs [ 0 ] . operator != '=='
else : # " foo > 2.0 , < 3.0"
return True |
def Reset ( self ) :
"""Reset the value in the control back to its starting value .
* Must Override *""" | try :
self . _tc . SetValue ( self . startValue )
except TypeError : # Start value was None
pass
self . _tc . SetInsertionPointEnd ( )
# Update the Entry Line
post_command_event ( self . main_window , self . TableChangedMsg , updated_cell = self . startValue ) |
def resolve_parameters ( value , parameters , date_time = datetime . datetime . now ( ) , macros = False ) :
"""Resolve a format modifier with the corresponding value .
Args :
value : The string ( path , table , or any other artifact in a cell _ body ) which may have format
modifiers . E . g . a table name co... | merged_parameters = Query . merge_parameters ( parameters , date_time = date_time , macros = macros , types_and_values = False )
return Query . _resolve_parameters ( value , merged_parameters ) |
def format_atomic ( value ) :
"""Format atomic value
This function also takes care of escaping the value in case one of the
reserved characters occurs in the value .""" | # Perform escaping
if isinstance ( value , str ) :
if any ( r in value for r in record . RESERVED_CHARS ) :
for k , v in record . ESCAPE_MAPPING :
value = value . replace ( k , v )
# String - format the given value
if value is None :
return "."
else :
return str ( value ) |
def Lab_to_LCHab ( cobj , * args , ** kwargs ) :
"""Convert from CIE Lab to LCH ( ab ) .""" | lch_l = cobj . lab_l
lch_c = math . sqrt ( math . pow ( float ( cobj . lab_a ) , 2 ) + math . pow ( float ( cobj . lab_b ) , 2 ) )
lch_h = math . atan2 ( float ( cobj . lab_b ) , float ( cobj . lab_a ) )
if lch_h > 0 :
lch_h = ( lch_h / math . pi ) * 180
else :
lch_h = 360 - ( math . fabs ( lch_h ) / math . pi ... |
def get_policy_config ( self , lint_context ) :
"""Returns a config of the concrete policy . For example , a config of ProhibitSomethingEvil is located on
config . policies . ProhibitSomethingEvil .""" | policy_config = lint_context [ 'config' ] . get ( 'policies' , { } ) . get ( self . __class__ . __name__ , { } )
return policy_config |
def recalculate_psd ( self ) :
"""Recalculate the psd""" | seg_len = self . sample_rate * self . psd_segment_length
e = len ( self . strain )
s = e - ( ( self . psd_samples + 1 ) * self . psd_segment_length / 2 ) * self . sample_rate
psd = pycbc . psd . welch ( self . strain [ s : e ] , seg_len = seg_len , seg_stride = seg_len / 2 )
psd . dist = spa_distance ( psd , 1.4 , 1.4 ... |
def template ( self ) :
"""Create a rules file in iptables - restore format""" | s = Template ( self . _IPTABLES_TEMPLATE )
return s . substitute ( filtertable = '\n' . join ( self . filters ) , rawtable = '\n' . join ( self . raw ) , mangletable = '\n' . join ( self . mangle ) , nattable = '\n' . join ( self . nat ) , date = datetime . today ( ) ) |
def validate_term ( usr , pwd , hpo_term ) :
"""Validate if the HPO term exists .
Check if there are any result when querying phenomizer .
Arguments :
usr ( str ) : A username for phenomizer
pwd ( str ) : A password for phenomizer
hpo _ term ( string ) : Represents the hpo term
Returns :
result ( bool... | result = True
try :
for line in query ( usr , pwd , hpo_term ) :
pass
except RuntimeError as err :
raise err
return result |
def stream ( input , encoding = None , errors = 'strict' ) :
"""Safely iterate a template generator , ignoring ` ` None ` ` values and optionally stream encoding .
Used internally by ` ` cinje . flatten ` ` , this allows for easy use of a template generator as a WSGI body .""" | input = ( i for i in input if i )
# Omits ` None ` ( empty wrappers ) and empty chunks .
if encoding : # Automatically , and iteratively , encode the text if requested .
input = iterencode ( input , encoding , errors = errors )
return input |
def lpc ( blk , order = None ) :
"""Find the Linear Predictive Coding ( LPC ) coefficients as a ZFilter object ,
the analysis whitening filter . This implementation is based on the
covariance method , assuming a zero - mean stochastic process , finding
the coefficients iteratively and greedily like the lattic... | # Calculate the covariance for each lag pair
phi = lag_matrix ( blk , order )
order = len ( phi ) - 1
# Inner product for filters based on above statistics
def inner ( a , b ) :
return sum ( phi [ i ] [ j ] * ai * bj for i , ai in enumerate ( a . numlist ) for j , bj in enumerate ( b . numlist ) )
A = ZFilter ( 1 )... |
def _get_checksum ( ) :
"""Get the checksum of the RPM Database .
Returns :
hexdigest""" | digest = hashlib . sha256 ( )
with open ( RPM_PATH , "rb" ) as rpm_db_fh :
while True :
buff = rpm_db_fh . read ( 0x1000 )
if not buff :
break
digest . update ( buff )
return digest . hexdigest ( ) |
def add_packages ( packages ) :
"""Add external packages to the pyspark interpreter .
Set the PYSPARK _ SUBMIT _ ARGS properly .
Parameters
packages : list of package names in string format""" | # if the parameter is a string , convert to a single element list
if isinstance ( packages , str ) :
packages = [ packages ]
_add_to_submit_args ( "--packages " + "," . join ( packages ) + " pyspark-shell" ) |
def get_intro_prompt ( self ) :
'''Print cabin mode message''' | sys_status = open ( self . help_path + 'cabin.txt' , 'r' )
server_msg = sys_status . read ( )
return server_msg + colorize ( 'psiTurk version ' + version_number + '\nType "help" for more information.' , 'green' , False ) |
def meth_delete ( args ) :
"""Remove ( redact ) a method from the method repository""" | message = "WARNING: this will delete workflow \n\t{0}/{1}:{2}" . format ( args . namespace , args . method , args . snapshot_id )
if not args . yes and not _confirm_prompt ( message ) :
return
r = fapi . delete_repository_method ( args . namespace , args . method , args . snapshot_id )
fapi . _check_response_code (... |
def _get_images_dir ( ) :
'''Extract the images dir from the configuration . First attempts to
find legacy virt . images , then tries virt : images .''' | img_dir = __salt__ [ 'config.option' ] ( 'virt.images' )
if img_dir :
salt . utils . versions . warn_until ( 'Sodium' , '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.' )
else :
img_dir = __salt__ [ 'config.get' ] ( 'virt:images' )
log .... |
def update_mute ( self , data ) :
"""Update mute .""" | self . _group [ 'muted' ] = data [ 'mute' ]
self . callback ( )
_LOGGER . info ( 'updated mute on %s' , self . friendly_name ) |
def minimise_tables ( routing_tables , target_lengths , methods = ( remove_default_entries , ordered_covering ) ) :
"""Utility function which attempts to minimises routing tables for multiple
chips .
For each routing table supplied , this function will attempt to use the
minimisation algorithms given ( or som... | # Coerce the target lengths into the correct forms
if not isinstance ( target_lengths , dict ) :
lengths = collections . defaultdict ( lambda : target_lengths )
else :
lengths = target_lengths
# Minimise the routing tables
new_tables = dict ( )
for chip , table in iteritems ( routing_tables ) : # Try to minimis... |
def delete_event ( self , id , ** kwargs ) : # noqa : E501
"""Delete a specific event # noqa : E501
# noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . delete _ event ( id , async _ req = True )
... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . delete_event_with_http_info ( id , ** kwargs )
# noqa : E501
else :
( data ) = self . delete_event_with_http_info ( id , ** kwargs )
# noqa : E501
return data |
def light ( cls ) :
"Make the current foreground color light ." | wAttributes = cls . _get_text_attributes ( )
wAttributes |= win32 . FOREGROUND_INTENSITY
cls . _set_text_attributes ( wAttributes ) |
def centroid ( self ) :
'''Return the geometric center .''' | if self . v is None :
raise ValueError ( 'Mesh has no vertices; centroid is not defined' )
return np . mean ( self . v , axis = 0 ) |
def get_variable_str ( self ) :
"""Utility method to get the variable value or ' var _ name = value ' if name is not None .
Note that values with large string representations will not get printed
: return :""" | if self . var_name is None :
prefix = ''
else :
prefix = self . var_name
suffix = str ( self . var_value )
if len ( suffix ) == 0 :
suffix = "''"
elif len ( suffix ) > self . __max_str_length_displayed__ :
suffix = ''
if len ( prefix ) > 0 and len ( suffix ) > 0 :
return prefix + '=' + suffix
else :... |
def cli ( env , identifier ) :
"""Cancel all virtual guests of the dedicated host immediately .
Use the ' slcli vs cancel ' command to cancel an specific guest""" | dh_mgr = SoftLayer . DedicatedHostManager ( env . client )
host_id = helpers . resolve_id ( dh_mgr . resolve_ids , identifier , 'dedicated host' )
if not ( env . skip_confirmations or formatting . no_going_back ( host_id ) ) :
raise exceptions . CLIAbort ( 'Aborted' )
table = formatting . Table ( [ 'id' , 'server n... |
def removeTextAll ( self , text ) :
'''removeTextAll - Removes ALL occuraces of given text in a text node ( i . e . not part of a tag )
@ param text < str > - text to remove
@ return list < str > - All text node containing # text BEFORE the text was removed .
Empty list if no text removed
NOTE : To remove a... | # TODO : This would be a good candidate for the refactor of text blocks
removedBlocks = [ ]
blocks = self . blocks
for i in range ( len ( blocks ) ) :
block = blocks [ i ]
# We only care about text blocks
if issubclass ( block . __class__ , AdvancedTag ) :
continue
if text in block : # Got a mat... |
def process_nxml ( nxml_filename , pmid = None , extra_annotations = None , cleanup = True , add_grounding = True ) :
"""Process an NXML file using the ISI reader
First converts NXML to plain text and preprocesses it , then runs the ISI
reader , and processes the output to extract INDRA Statements .
Parameter... | if extra_annotations is None :
extra_annotations = { }
# Create a temporary directory to store the proprocessed input
pp_dir = tempfile . mkdtemp ( 'indra_isi_pp_output' )
pp = IsiPreprocessor ( pp_dir )
extra_annotations = { }
pp . preprocess_nxml_file ( nxml_filename , pmid , extra_annotations )
# Run the ISI rea... |
def name ( self , name = None ) :
'''api name , default is module . _ _ name _ _''' | if name :
self . _name = name
return self
return self . _name |
def from_mapping ( cls , mapping ) :
"""Create a bag from a dict of elem - > count .
Each key in the dict is added if the value is > 0.
Raises :
ValueError : If any count is < 0.""" | out = cls ( )
for elem , count in mapping . items ( ) :
out . _set_count ( elem , count )
return out |
def _strip_empty_keys ( self , params ) :
"""Added because the Dropbox OAuth2 flow doesn ' t
work when scope is passed in , which is empty .""" | keys = [ k for k , v in params . items ( ) if v == '' ]
for key in keys :
del params [ key ] |
def get_status_updates ( self , startup_id ) :
"""Get status updates of a startup""" | return _get_request ( _STATUS_U . format ( c_api = _C_API_BEGINNING , api = _API_VERSION , startup_id = startup_id , at = self . access_token ) ) |
async def unset_lock ( self , resource , lock_identifier ) :
"""Unlock this instance
: param resource : redis key to set
: param lock _ identifier : uniquie id of lock
: raises : LockError if the lock resource acquired with different lock _ identifier""" | try :
with await self . connect ( ) as redis :
await redis . eval ( self . unset_lock_script , keys = [ resource ] , args = [ lock_identifier ] )
except aioredis . errors . ReplyError as exc : # script fault
self . log . debug ( 'Can not unset lock "%s" on %s' , resource , repr ( self ) )
raise Lock... |
def return_self_updater ( func ) :
'''Run func , but still return v . Useful for using knowledge . update with operates like append , extend , etc .
e . g . return _ self ( lambda k , v : v . append ( ' newobj ' ) )''' | @ functools . wraps ( func )
def decorator ( k , v ) :
func ( k , v )
return v
return decorator |
def _initialize_stretching_matrix ( self ) :
"""Set up the stretching matrix""" | self . S = np . zeros ( ( self . nz , self . nz ) )
if ( self . nz == 2 ) and ( self . rd ) and ( self . delta ) :
self . del1 = self . delta / ( self . delta + 1. )
self . del2 = ( self . delta + 1. ) ** - 1
self . Us = self . Ubg [ 0 ] - self . Ubg [ 1 ]
self . F1 = self . rd ** - 2 / ( 1. + self . de... |
def T2 ( word , rules ) :
'''Split any VV sequence that is not a genuine diphthong or long vowel .
E . g . , [ ta . e ] , [ ko . et . taa ] . This rule can apply within VVV + sequences .''' | WORD = word
offset = 0
for vv in vv_sequences ( WORD ) :
seq = vv . group ( 1 )
if not phon . is_diphthong ( seq ) and not phon . is_long ( seq ) :
i = vv . start ( 1 ) + 1 + offset
WORD = WORD [ : i ] + '.' + WORD [ i : ]
offset += 1
rules += ' T2' if word != WORD else ''
return WORD , ... |
def actions ( self , s ) :
'''Possible actions from a state .''' | # we try to generate every possible state and then filter those
# states that are valid
return [ a for a in self . _actions if self . _is_valid ( self . result ( s , a ) ) ] |
def disable_code_breakpoint ( self , dwProcessId , address ) :
"""Disables the code breakpoint at the given address .
@ see :
L { define _ code _ breakpoint } ,
L { has _ code _ breakpoint } ,
L { get _ code _ breakpoint } ,
L { enable _ code _ breakpoint }
L { enable _ one _ shot _ code _ breakpoint } ... | p = self . system . get_process ( dwProcessId )
bp = self . get_code_breakpoint ( dwProcessId , address )
if bp . is_running ( ) :
self . __del_running_bp_from_all_threads ( bp )
bp . disable ( p , None ) |
def unmount_process ( self , process ) :
"""Unmount a process from the http server to stop receiving message
callbacks .""" | # There is no remove _ handlers , but . handlers is public so why not . server . handlers is a list of
# 2 - tuples of the form ( host _ pattern , [ list of RequestHandler ] ) objects . We filter out all
# handlers matching our process from the RequestHandler list for each host pattern .
def nonmatching ( handler ) :
... |
def has_local_as ( self , local_as , max_count = 0 ) :
"""Check if * local _ as * is already present on path list .""" | _count = 0
for as_path_seg in self . value :
_count += list ( as_path_seg ) . count ( local_as )
return _count > max_count |
def _byteify ( data ) :
"""Convert unicode to bytes""" | # Unicode
if isinstance ( data , six . text_type ) :
return data . encode ( "utf-8" )
# Members of lists
if isinstance ( data , list ) :
return [ _byteify ( item ) for item in data ]
# Members of dicts
if isinstance ( data , dict ) :
return { _byteify ( key ) : _byteify ( value ) for key , value in data . i... |
def _reseed ( self ) :
"""Randomly create a new snowflake once this one is finished .""" | self . _char = choice ( self . _snow_chars )
self . _rate = randint ( 1 , 3 )
self . _x = randint ( 0 , self . _screen . width - 1 )
self . _y = self . _screen . start_line + randint ( 0 , self . _rate ) |
def isCommaList ( inputFilelist ) :
"""Return True if the input is a comma separated list of names .""" | if isinstance ( inputFilelist , int ) or isinstance ( inputFilelist , np . int32 ) :
ilist = str ( inputFilelist )
else :
ilist = inputFilelist
if "," in ilist :
return True
return False |
def add_option ( self , block , name , * values ) :
"""Adds an option to the AST , either as a non - block option or for an
existing block .
` block `
Block name . Set to ` ` None ` ` for non - block option .
` name `
Option name .
` * values `
String values for the option .
* Raises a ` ` ValueErro... | if not self . RE_NAME . match ( name ) :
raise ValueError ( u"Invalid option name '{0}'" . format ( common . from_utf8 ( name ) ) )
if not values :
raise ValueError ( u"Must provide a value" )
else :
values = list ( values )
if block : # block doesn ' t exist
if not block in self . _block_map :
... |
def format_date ( cls , timestamp ) :
"""Creates a string representing the date information provided by the
given ` timestamp ` object .""" | if not timestamp :
raise DateTimeFormatterException ( 'timestamp must a valid string {}' . format ( timestamp ) )
return timestamp . strftime ( cls . DATE_FORMAT ) |
def organization_field_create ( self , data , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / core / organization _ fields # create - organization - fields" | api_path = "/api/v2/organization_fields.json"
return self . call ( api_path , method = "POST" , data = data , ** kwargs ) |
def sendAsync ( self , query , * parameters , ** options ) :
'''Performs an asynchronous query and returns * * without * * retrieving of
the response .
In typical use case , ` query ` is the name of the function to call and
` parameters ` are its parameters . When ` parameters ` list is empty , the
query ca... | self . query ( MessageType . ASYNC , query , * parameters , ** options ) |
def _crossings ( self ) :
"""counts ( inefficently but at least accurately ) the number of
crossing edges between layer l and l + dirv .
P [ i ] [ j ] counts the number of crossings from j - th edge of vertex i .
The total count of crossings is the sum of flattened P :
x = sum ( sum ( P , [ ] ) )""" | g = self . layout . grx
P = [ ]
for v in self :
P . append ( [ g [ x ] . pos for x in self . _neighbors ( v ) ] )
for i , p in enumerate ( P ) :
candidates = sum ( P [ i + 1 : ] , [ ] )
for j , e in enumerate ( p ) :
p [ j ] = len ( filter ( ( lambda nx : nx < e ) , candidates ) )
del candidates... |
def _get_val ( other ) :
"""Given a Number , a Numeric Constant or a python number return its value""" | assert isinstance ( other , ( numbers . Number , SymbolNUMBER , SymbolCONST ) )
if isinstance ( other , SymbolNUMBER ) :
return other . value
if isinstance ( other , SymbolCONST ) :
return other . expr . value
return other |
def optimise_partition ( self , partition , n_iterations = 2 ) :
"""Optimise the given partition .
Parameters
partition
The : class : ` ~ VertexPartition . MutableVertexPartition ` to optimise .
n _ iterations : int
Number of iterations to run the Leiden algorithm . By default , 2 iterations
are run . I... | itr = 0
diff = 0
continue_iteration = itr < n_iterations or n_iterations < 0
while continue_iteration :
diff_inc = _c_leiden . _Optimiser_optimise_partition ( self . _optimiser , partition . _partition )
diff += diff_inc
itr += 1
if n_iterations < 0 :
continue_iteration = ( diff_inc > 0 )
el... |
def hull_points ( obj , qhull_options = 'QbB Pp' ) :
"""Try to extract a convex set of points from multiple input formats .
Parameters
obj : Trimesh object
( n , d ) points
( m , ) Trimesh objects
Returns
points : ( o , d ) convex set of points""" | if hasattr ( obj , 'convex_hull' ) :
return obj . convex_hull . vertices
initial = np . asanyarray ( obj , dtype = np . float64 )
if len ( initial . shape ) != 2 :
raise ValueError ( 'points must be (n, dimension)!' )
hull = spatial . ConvexHull ( initial , qhull_options = qhull_options )
points = hull . points... |
def schema_list ( dbname , user = None , db_user = None , db_password = None , db_host = None , db_port = None ) :
'''Return a dict with information about schemas in a Postgres database .
CLI Example :
. . code - block : : bash
salt ' * ' postgres . schema _ list dbname
dbname
Database name we query on
... | ret = { }
query = ( '' . join ( [ 'SELECT ' 'pg_namespace.nspname as "name",' 'pg_namespace.nspacl as "acl", ' 'pg_roles.rolname as "owner" ' 'FROM pg_namespace ' 'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner ' ] ) )
rows = psql_query ( query , runas = user , host = db_host , user = db_user , port = db_po... |
def word_starts ( self ) :
"""The list of start positions representing ` ` words ` ` layer elements .""" | if not self . is_tagged ( WORDS ) :
self . tokenize_words ( )
return self . starts ( WORDS ) |
def set_contents_from_stream ( self , fp , headers = None , replace = True , cb = None , num_cb = 10 , policy = None , reduced_redundancy = False , query_args = None , size = None ) :
"""Store an object using the name of the Key object as the key in
cloud and the contents of the data stream pointed to by ' fp ' a... | provider = self . bucket . connection . provider
if not provider . supports_chunked_transfer ( ) :
raise BotoClientError ( '%s does not support chunked transfer' % provider . get_provider_name ( ) )
# Name of the Object should be specified explicitly for Streams .
if not self . name or self . name == '' :
raise... |
def extract_trios ( family ) :
"""Identify all trios / duos inside a family , where a family contains dictionary
of relationship : individual , for example :
" ChildSelf " : " 176531498 " ,
" DzTwin " : " 176531497 " ,
" Parent " : " 176449143" """ | self_key = [ "ChildSelf" ]
keys = family . keys ( )
spouse_key = [ x for x in keys if ( "spouse" in x . lower ( ) ) ]
assert len ( spouse_key ) <= 1
parent_keys = [ x for x in keys if ( "parent" in x . lower ( ) ) and ( "grand" not in x . lower ( ) ) ]
sib_keys = [ x for x in keys if ( "sibling" in x . lower ( ) ) or (... |
async def get_capability_report ( self ) :
"""This method retrieves the Firmata capability report .
Refer to http : / / firmata . org / wiki / Protocol # Capability _ Query
The command format is : { " method " : " get _ capability _ report " , " params " : [ " null " ] }
: returns : { " method " : " capabilit... | value = await self . core . get_capability_report ( )
await asyncio . sleep ( .1 )
if value :
reply = json . dumps ( { "method" : "capability_report_reply" , "params" : value } )
else :
reply = json . dumps ( { "method" : "capability_report_reply" , "params" : "None" } )
await self . websocket . send ( reply ) |
def emit_containers ( self , containers , verbose = True ) :
"""Emits the applications and sorts containers by name
: param containers : List of the container definitions
: type containers : list of dict
: param verbose : Print out newlines and indented JSON
: type verbose : bool
: returns : The text outp... | containers = sorted ( containers , key = lambda c : c . get ( 'name' ) )
output = { 'kind' : 'Deployment' , 'apiVersion' : 'extensions/v1beta1' , 'metadata' : { 'name' : None , 'namespace' : 'default' , 'labels' : { 'app' : None , 'version' : 'latest' , } , } , 'spec' : { 'replicas' : 1 , 'selector' : { 'matchLabels' :... |
def ipn ( request ) :
"""PayPal IPN endpoint ( notify _ url ) .
Used by both PayPal Payments Pro and Payments Standard to confirm transactions .
http : / / tinyurl . com / d9vu9d
PayPal IPN Simulator :
https : / / developer . paypal . com / cgi - bin / devscr ? cmd = _ ipn - link - session""" | # TODO : Clean up code so that we don ' t need to set None here and have a lot
# of if checks just to determine if flag is set .
flag = None
ipn_obj = None
# Avoid the RawPostDataException . See original issue for details :
# https : / / github . com / spookylukey / django - paypal / issues / 79
if not request . META .... |
def prune ( self ) :
"""Prune the scenario ephemeral directory files and returns None .
" safe files " will not be pruned , including the ansible configuration
and inventory used by this scenario , the scenario state file , and
files declared as " safe _ files " in the ` ` driver ` ` configuration
declared ... | LOG . info ( 'Pruning extra files from scenario ephemeral directory' )
safe_files = [ self . config . provisioner . config_file , self . config . provisioner . inventory_file , self . config . state . state_file , ] + self . config . driver . safe_files
files = util . os_walk ( self . ephemeral_directory , '*' )
for f ... |
def get_bboxes ( img , mask , nb_boxes = 100 , score_thresh = 0.5 , iou_thresh = 0.2 , prop_size = 0.09 , prop_scale = 1.2 , ) :
"""Uses selective search to generate candidate bounding boxes and keeps the
ones that have the largest iou with the predicted mask .
: param img : original image
: param mask : pred... | min_size = int ( img . shape [ 0 ] * prop_size * img . shape [ 1 ] * prop_size )
scale = int ( img . shape [ 0 ] * prop_scale )
# TODO : cross validate for multiple values of prop _ size , prop _ scale , and nb _ bboxes
img_lbl , regions = selectivesearch . selective_search ( img , scale = scale , sigma = 0.8 , min_siz... |
def resolve_object_property ( obj , path : str ) :
"""Resolves the value of a property on an object .
Is able to resolve nested properties . For example ,
a path can be specified :
' other . beer . name '
Raises :
AttributeError :
In case the property could not be resolved .
Returns :
The value of t... | value = obj
for path_part in path . split ( '.' ) :
value = getattr ( value , path_part )
return value |
def to_identifier ( s ) :
"""Convert snake _ case to camel _ case .""" | if s . startswith ( 'GPS' ) :
s = 'Gps' + s [ 3 : ]
return '' . join ( [ i . capitalize ( ) for i in s . split ( '_' ) ] ) if '_' in s else s |
def _get_batches ( self , items ) :
"""given a list yield list at most self . max _ batch _ size in size""" | for i in xrange ( 0 , len ( items ) , self . max_batch_size ) :
yield items [ i : i + self . max_batch_size ] |
def get_scene_suggestions ( self , refobjinter ) :
"""Return a list of suggested Reftracks for the current scene , that are not already
in this root .
A suggestion is a combination of type and element .
: param refobjinter : a programm specific reftrack object interface
: type refobjinter : : class : ` Refo... | sugs = [ ]
cur = refobjinter . get_current_element ( )
if not cur :
return sugs
for typ in refobjinter . types :
inter = refobjinter . get_typ_interface ( typ )
elements = inter . get_scene_suggestions ( cur )
for e in elements :
for r in self . _reftracks :
if not r . get_parent ( )... |
def update_network_postcommit ( self , context ) :
"""Send network updates to CVX :
- Update the network name
- Add new segments
- Delete stale segments""" | network = context . current
orig_network = context . original
log_context ( "update_network_postcommit: network" , network )
log_context ( "update_network_postcommit: orig" , orig_network )
segments = context . network_segments
self . create_network ( network )
# New segments may have been added
self . create_segments ... |
def get_instance ( self , payload ) :
"""Build an instance of BindingInstance
: param dict payload : Payload response from the API
: returns : twilio . rest . notify . v1 . service . binding . BindingInstance
: rtype : twilio . rest . notify . v1 . service . binding . BindingInstance""" | return BindingInstance ( self . _version , payload , service_sid = self . _solution [ 'service_sid' ] , ) |
def split_hosts ( hosts , default_port = DEFAULT_PORT ) :
"""Takes a string of the form host1 [ : port ] , host2 [ : port ] . . . and
splits it into ( host , port ) tuples . If [ : port ] isn ' t present the
default _ port is used .
Returns a set of 2 - tuples containing the host name ( or IP ) followed by
... | nodes = [ ]
for entity in hosts . split ( ',' ) :
if not entity :
raise ConfigurationError ( "Empty host " "(or extra comma in host list)." )
port = default_port
# Unix socket entities don ' t have ports
if entity . endswith ( '.sock' ) :
port = None
nodes . append ( parse_host ( ent... |
def run_deferred ( self , deferred ) :
"""Run the callables in deferred using their associated scope stack .""" | for handler , scope , offset in deferred :
self . scope_stack = scope
self . offset = offset
handler ( ) |
def import_header ( self , header : BlockHeader ) -> Tuple [ Tuple [ BlockHeader , ... ] , Tuple [ BlockHeader , ... ] ] :
"""Direct passthrough to ` headerdb `
Also updates the local ` header ` property to be the latest canonical head .
Returns an iterable of headers representing the headers that are newly
p... | new_canonical_headers = self . headerdb . persist_header ( header )
self . header = self . get_canonical_head ( )
return new_canonical_headers |
def extract_only_content ( self , path = None , payload = None , objectInput = None ) :
"""Return only the text content of passed file .
These parameters are in OR . Only one of them can be analyzed .
Args :
path ( string ) : Path of file to analyze
payload ( string ) : Payload base64 to analyze
objectInp... | if objectInput :
switches = [ "-t" ]
result = self . _command_template ( switches , objectInput )
return result , True , None
else :
f = file_path ( path , payload )
switches = [ "-t" , f ]
result = self . _command_template ( switches )
return result , path , f |
def logpowspec ( frames , NFFT , norm = 1 ) :
"""Compute the log power spectrum of each frame in frames . If frames is an NxD matrix , output will be Nx ( NFFT / 2 + 1 ) .
: param frames : the array of frames . Each row is a frame .
: param NFFT : the FFT length to use . If NFFT > frame _ len , the frames are z... | ps = powspec ( frames , NFFT ) ;
ps [ ps <= 1e-30 ] = 1e-30
lps = 10 * numpy . log10 ( ps )
if norm :
return lps - numpy . max ( lps )
else :
return lps |
def get_included_databases ( self ) :
"""Return the databases we want to include , or empty list for all .""" | databases = set ( )
databases . update ( self . _plain_db . keys ( ) )
for _ , namespace in self . _regex_map :
database_name , _ = namespace . source_name . split ( "." , 1 )
if "*" in database_name :
return [ ]
databases . add ( database_name )
return list ( databases ) |
def p_OptionalOrRequiredArgument ( p ) :
"""OptionalOrRequiredArgument : Type Ellipsis IDENTIFIER""" | p [ 0 ] = model . OperationArgument ( type = p [ 1 ] , ellipsis = p [ 2 ] , name = p [ 3 ] ) |
def update_detector ( self , detector_id , detector ) :
"""Update an existing detector .
Args :
detector _ id ( string ) : the ID of the detector .
detector ( object ) : the detector model object . Will be serialized as
JSON .
Returns :
dictionary of the response ( updated detector model ) .""" | resp = self . _put ( self . _u ( self . _DETECTOR_ENDPOINT_SUFFIX , detector_id ) , data = detector )
resp . raise_for_status ( )
return resp . json ( ) |
def render ( self , context , nodelist , box_type ) :
"Render the position ." | if not self . target :
if self . target_ct : # broken Generic FK :
log . warning ( 'Broken target for position with pk %r' , self . pk )
return ''
try :
return Template ( self . text , name = "position-%s" % self . name ) . render ( context )
except TemplateSyntaxError :
log ... |
def numberofsamples ( self ) :
"""Count the number of samples is the samplesheet""" | # Initialise variables to store line data
idline = 0
linenumber = 0
# Parse the sample sheet to find the number of samples
with open ( self . samplesheet , "rb" ) as ssheet : # Use enumerate to iterate through the lines in the sample sheet to retrieve the line number and the data
for linenumber , entry in enumerate... |
def create_module_file ( package , module , opts ) : # type : ( unicode , unicode , Any ) - > None
"""Generate RST for a top - level module ( i . e . , not part of a package )""" | if not opts . noheadings :
text = format_heading ( 1 , '%s module' % module )
else :
text = ''
# text + = format _ heading ( 2 , ' : mod : ` % s ` Module ' % module )
text += format_directive ( module , package )
if opts . templates :
template_loader = FileSystemLoader ( opts . templates )
template_env ... |
def workflows ( self ) :
"""Access the workflows
: returns : twilio . rest . taskrouter . v1 . workspace . workflow . WorkflowList
: rtype : twilio . rest . taskrouter . v1 . workspace . workflow . WorkflowList""" | if self . _workflows is None :
self . _workflows = WorkflowList ( self . _version , workspace_sid = self . _solution [ 'sid' ] , )
return self . _workflows |
def append ( args ) :
"""% prog append csvfile [ tag ]
Append a column with fixed value . If tag is missing then just append the
filename .""" | p = OptionParser ( append . __doc__ )
p . set_sep ( )
p . set_outfile ( )
opts , args = p . parse_args ( args )
nargs = len ( args )
if nargs not in ( 1 , 2 ) :
sys . exit ( not p . print_help ( ) )
csvfile = args [ 0 ]
tag = args [ 1 ] if nargs == 2 else csvfile
fp = must_open ( csvfile )
fw = must_open ( opts . o... |
def xloss ( logits , labels , ignore = None ) :
"""Cross entropy loss""" | return F . cross_entropy ( logits , Variable ( labels ) , ignore_index = 255 ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.