signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def stderr ( self ) :
"""The job stderr
: return : string or None""" | streams = self . _payload . get ( 'streams' , None )
return streams [ 1 ] if streams is not None and len ( streams ) >= 2 else '' |
def _internal_set ( self , obj , value , hint = None , setter = None ) :
'''Internal implementation to set property values , that is used
by _ _ set _ _ , set _ from _ json , etc .
Delegate to the | Property | instance to prepare the value appropriately ,
then ` set .
Args :
obj ( HasProps )
The object ... | value = self . property . prepare_value ( obj , self . name , value )
old = self . __get__ ( obj , obj . __class__ )
self . _real_set ( obj , old , value , hint = hint , setter = setter ) |
def workflow_overwrite ( object_id , input_params = { } , always_retry = True , ** kwargs ) :
"""Invokes the / workflow - xxxx / overwrite API method .
For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Workflows - and - Analyses # API - method % 3A - % 2Fworkflow - xxxx % 2F... | return DXHTTPRequest ( '/%s/overwrite' % object_id , input_params , always_retry = always_retry , ** kwargs ) |
def do_ams_post ( endpoint , path , body , access_token , rformat = "json" , ds_min_version = "3.0;NetFx" ) :
'''Do a AMS HTTP POST request and return JSON .
Args :
endpoint ( str ) : Azure Media Services Initial Endpoint .
path ( str ) : Azure Media Services Endpoint Path .
body ( str ) : Azure Media Servi... | min_ds = dsversion_min
content_acceptformat = json_acceptformat
acceptformat = json_acceptformat
if rformat == "json_only" :
min_ds = ds_min_version
content_acceptformat = json_only_acceptformat
if rformat == "xml" :
content_acceptformat = xml_acceptformat
acceptformat = xml_acceptformat + ",application... |
def validate ( self , email , ** kwargs ) :
"""Check to see if this is a valid email address .""" | email = stringify ( email )
if email is None :
return
if not self . EMAIL_REGEX . match ( email ) :
return False
mailbox , domain = email . rsplit ( '@' , 1 )
return self . domains . validate ( domain , ** kwargs ) |
def contains_locked_file ( directory : str ) :
""": return : True if any of the files in the directory are in use . For example , if the dll is injected
into the game , this will definitely return true .""" | for root , subdirs , files in os . walk ( directory ) :
for filename in files :
file_path = os . path . join ( root , filename )
try :
with open ( file_path , 'a' ) :
pass
except IOError :
logger . debug ( f"Locked file: {file_path}" )
retu... |
def variant ( name , parents_or_properties , explicit_properties = [ ] ) :
"""Declares a new variant .
First determines explicit properties for this variant , by
refining parents ' explicit properties with the passed explicit
properties . The result is remembered and will be used if
this variant is used as ... | parents = [ ]
if not explicit_properties :
explicit_properties = parents_or_properties
else :
parents = parents_or_properties
inherited = property_set . empty ( )
if parents : # If we allow multiple parents , we ' d have to to check for conflicts
# between base variants , and there was no demand for so to bothe... |
def store ( data , arr , start = 0 , stop = None , offset = 0 , blen = None ) :
"""Copy ` data ` block - wise into ` arr ` .""" | # setup
blen = _util . get_blen_array ( data , blen )
if stop is None :
stop = len ( data )
else :
stop = min ( stop , len ( data ) )
length = stop - start
if length < 0 :
raise ValueError ( 'invalid stop/start' )
# copy block - wise
for bi in range ( start , stop , blen ) :
bj = min ( bi + blen , stop ... |
def list_postkantons_by_gemeente ( self , gemeente ) :
'''List all ` postkantons ` in a : class : ` Gemeente `
: param gemeente : The : class : ` Gemeente ` for which the ` potkantons ` are wanted .
: rtype : A : class : ` list ` of : class : ` Postkanton `''' | try :
id = gemeente . id
except AttributeError :
id = gemeente
def creator ( ) :
res = crab_gateway_request ( self . client , 'ListPostkantonsByGemeenteId' , id )
try :
return [ Postkanton ( r . PostkantonCode ) for r in res . PostkantonItem ]
except AttributeError :
return [ ]
if se... |
def configure_terminal ( self ) :
"""Sets all customized properties on the terminal""" | client = self . guake . settings . general
word_chars = client . get_string ( 'word-chars' )
if word_chars :
self . set_word_char_exceptions ( word_chars )
self . set_audible_bell ( client . get_boolean ( 'use-audible-bell' ) )
self . set_sensitive ( True )
cursor_blink_mode = self . guake . settings . style . get_... |
def get_all_names ( self ) :
"""Return the list of all cached global names""" | result = set ( )
for module in self . names :
result . update ( set ( self . names [ module ] ) )
return result |
def get ( cls , object_version , key ) :
"""Get the tag object .""" | return cls . query . filter_by ( version_id = as_object_version_id ( object_version ) , key = key , ) . one_or_none ( ) |
def _verify_names ( sampler , var_names , arg_names ) :
"""Make sure var _ names and arg _ names are assigned reasonably .
This is meant to run before loading emcee objects into InferenceData .
In case var _ names or arg _ names is None , will provide defaults . If they are
not None , it verifies there are th... | # There are 3 possible cases : emcee2 , emcee3 and sampler read from h5 file ( emcee3 only )
if hasattr ( sampler , "args" ) :
num_vars = sampler . chain . shape [ - 1 ]
num_args = len ( sampler . args )
elif hasattr ( sampler , "log_prob_fn" ) :
num_vars = sampler . get_chain ( ) . shape [ - 1 ]
num_ar... |
def _create_connection ( address , options ) :
"""Given ( host , port ) and PoolOptions , connect and return a socket object .
Can raise socket . error .
This is a modified version of create _ connection from CPython > = 2.6.""" | host , port = address
# Check if dealing with a unix domain socket
if host . endswith ( '.sock' ) :
if not hasattr ( socket , "AF_UNIX" ) :
raise ConnectionFailure ( "UNIX-sockets are not supported " "on this system" )
sock = socket . socket ( socket . AF_UNIX )
# SOCK _ CLOEXEC not supported for Un... |
def as_fixed_width ( self , copy = True ) :
"""Convert binning to recipe with fixed width ( if possible . )
Parameters
copy : bool
Ensure that we receive another object
Returns
FixedWidthBinning""" | if self . bin_count == 0 :
raise RuntimeError ( "Cannot guess binning width with zero bins" )
elif self . bin_count == 1 or self . is_consecutive ( ) and self . is_regular ( ) :
return FixedWidthBinning ( min = self . bins [ 0 ] [ 0 ] , bin_count = self . bin_count , bin_width = self . bins [ 1 ] - self . bins ... |
def validate_resource_attributes ( resource , attributes , template , check_unit = True , exact_match = False , ** kwargs ) :
"""Validate that the resource provided matches the template .
Only passes if the resource contains ONLY the attributes specified
in the template .
The template should take the form of ... | errors = [ ]
# is it a node or link ?
res_type = 'GROUP'
if resource . get ( 'x' ) is not None :
res_type = 'NODE'
elif resource . get ( 'node_1_id' ) is not None :
res_type = 'LINK'
elif resource . get ( 'nodes' ) is not None :
res_type = 'NETWORK'
# Find all the node / link / network definitions in the te... |
def info ( cache_dir = CACHE_DIR , product = DEFAULT_PRODUCT ) :
"""Show info about the product cache .
: param cache _ dir : Root of the DEM cache folder .
: param product : DEM product choice .""" | datasource_root , _ = ensure_setup ( cache_dir , product )
util . check_call_make ( datasource_root , targets = [ 'info' ] ) |
def log_similarity_result ( logfile , result ) :
"""Log a similarity evaluation result dictionary as TSV to logfile .""" | assert result [ 'task' ] == 'similarity'
if not logfile :
return
with open ( logfile , 'a' ) as f :
f . write ( '\t' . join ( [ str ( result [ 'global_step' ] ) , result [ 'task' ] , result [ 'dataset_name' ] , json . dumps ( result [ 'dataset_kwargs' ] ) , result [ 'similarity_function' ] , str ( result [ 'spe... |
def __find_executables ( path ) :
"""Used by find _ graphviz
path - single directory as a string
If any of the executables are found , it will return a dictionary
containing the program names as keys and their paths as values .
Otherwise returns None""" | success = False
progs = { 'dot' : '' , 'twopi' : '' , 'neato' : '' , 'circo' : '' , 'fdp' : '' , 'sfdp' : '' }
was_quoted = False
path = path . strip ( )
if path . startswith ( '"' ) and path . endswith ( '"' ) :
path = path [ 1 : - 1 ]
was_quoted = True
if os . path . isdir ( path ) :
for prg in progs . it... |
def function_parameters ( function ) :
"""Simple decorator to raise a TypeError , if paramater
and it ' s static type added to the description _ _ doc _ _
as such ( parameter _ name : str )""" | if not callable ( function ) :
raise TypeError ( 'function_parameters(function=%s) you must pass a function' % ( function ) )
def wrapper ( * args , ** kwargs ) :
if function . __doc__ is not None :
if len ( function . __doc__ ) > 3 and len ( args ) + len ( kwargs ) + len ( function . __defaults__ if fu... |
def list_ ( name = None , runas = None ) :
'''Run launchctl list and return the output
: param str name : The name of the service to list
: param str runas : User to run launchctl commands
: return : If a name is passed returns information about the named service ,
otherwise returns a list of all services a... | if name : # Get service information and label
service = _get_service ( name )
label = service [ 'plist' ] [ 'Label' ]
# we can assume if we are trying to list a LaunchAgent we need
# to run as a user , if not provided , we ' ll use the console user .
if not runas and _launch_agent ( name ) :
... |
def GetClientURNsForHostnames ( hostnames , token = None ) :
"""Gets all client _ ids for a given list of hostnames or FQDNS .
Args :
hostnames : A list of hostnames / FQDNs .
token : An ACL token .
Returns :
A dict with a list of all known GRR client _ ids for each hostname .""" | if data_store . RelationalDBEnabled ( ) :
index = ClientIndex ( )
else :
index = CreateClientIndex ( token = token )
keywords = set ( )
for hostname in hostnames :
if hostname . startswith ( "host:" ) :
keywords . add ( hostname )
else :
keywords . add ( "host:%s" % hostname )
results = ... |
def protocols ( self ) :
""": rtype : dict [ int , list of ProtocolAnalyzer ]""" | if self . __protocols is None :
self . __protocols = self . proto_tree_model . protocols
return self . __protocols |
def setOrderedInputs ( self , value ) :
"""Sets self . orderedInputs to value . Specifies if inputs
should be ordered and if so orders the inputs .""" | self . orderedInputs = value
if self . orderedInputs :
self . loadOrder = [ 0 ] * len ( self . inputs )
for i in range ( len ( self . inputs ) ) :
self . loadOrder [ i ] = i |
def paginated_retrieval ( methodname , itemtype ) :
"""decorator factory for retrieval queries from query params""" | return compose ( reusable , basic_interaction , map_yield ( partial ( _params_as_get , methodname ) ) , ) |
def plot_campaign ( self , campaign = 0 , annotate_channels = True , ** kwargs ) :
"""Plot all the active channels of a campaign .""" | fov = getKeplerFov ( campaign )
corners = fov . getCoordsOfChannelCorners ( )
for ch in np . arange ( 1 , 85 , dtype = int ) :
if ch in fov . brokenChannels :
continue
# certain channel are no longer used
idx = np . where ( corners [ : : , 2 ] == ch )
mdl = int ( corners [ idx , 0 ] [ 0 ] [ ... |
def refresh ( self ) :
"""Refresh session on 401 . This is called automatically if your existing
session times out and resends the operation / s which returned the
error .
: raises SMCConnectionError : Problem re - authenticating using existing
api credentials""" | if self . session and self . session_id : # Did session timeout ?
logger . info ( 'Session timed out, will try obtaining a new session using ' 'previously saved credential information.' )
self . logout ( )
# Force log out session just in case
return self . login ( ** self . copy ( ) )
raise SMCConnectio... |
def camelize ( key ) :
"""Convert a python _ style _ variable _ name to lowerCamelCase .
Examples
> > > camelize ( ' variable _ name ' )
' variableName '
> > > camelize ( ' variableName ' )
' variableName '""" | return '' . join ( x . capitalize ( ) if i > 0 else x for i , x in enumerate ( key . split ( '_' ) ) ) |
def loads ( content ) :
"""Loads variable definitions from a string .""" | lines = _group_lines ( line for line in content . split ( '\n' ) )
lines = [ ( i , _parse_envfile_line ( line ) ) for i , line in lines if line . strip ( ) ]
errors = [ ]
# Reject files with duplicate variables ( no sane default ) .
duplicates = _find_duplicates ( ( ( i , line [ 0 ] ) for i , line in lines ) )
for i , ... |
def lower_case ( f ) :
"""Decorator specifically for turning mssql AST into lowercase""" | # if it has already been wrapped , we return original
if hasattr ( f , "lower_cased" ) :
return f
@ wraps ( f )
def wrapper ( * args , ** kwargs ) :
f . lower_cased = True
return f ( * args , ** kwargs ) . lower ( )
return wrapper |
def merge_all_edges_between_two_vertices ( self , vertex1 , vertex2 ) :
"""Merges all edge between two supplied vertices into a single edge from a perspective of multi - color merging .
Proxies a call to : meth : ` BreakpointGraph . _ BreakpointGraph _ _ merge _ all _ bgedges _ between _ two _ vertices `
: para... | self . __merge_all_bgedges_between_two_vertices ( vertex1 = vertex1 , vertex2 = vertex2 ) |
def dump_in_memory_result ( self , result , output_path ) :
"""Recursively dumps the result of our processing into files within the
given output path .
Args :
result : The in - memory result of our processing .
output _ path : Full path to the folder into which to dump the files .
Returns :
The number o... | file_count = 0
logger . debug ( "Dumping in-memory processing results to output folder: %s" , output_path )
for k , v in iteritems ( result ) :
cur_output_path = os . path . join ( output_path , k )
if isinstance ( v , dict ) :
file_count += self . dump_in_memory_result ( v , cur_output_path )
else ... |
def build_fred ( self ) :
'''Build a flat recurrent encoder - decoder dialogue model''' | encoder = Encoder ( data = self . dataset , config = self . model_config )
decoder = Decoder ( data = self . dataset , config = self . model_config , encoder = encoder )
return EncoderDecoder ( config = self . model_config , encoder = encoder , decoder = decoder , num_gpus = self . num_gpus )
return EncoderDecoder ( co... |
def get_children ( self , path , watch = None ) :
"""Gets the list of children of a node
: param path : Z - Path
: param watch : Watch method""" | return self . _zk . get_children ( self . __path ( path ) , watch = watch ) |
def state_machine_success ( ) :
"""A positive result ! Iterate !""" | from furious . async import Async
from furious . context import get_current_async
result = get_current_async ( ) . result
if result == 'ALPHA' :
logging . info ( 'Inserting continuation for state %s.' , result )
return Async ( target = complex_state_generator_alpha , args = [ result ] )
elif result == 'BRAVO' :... |
def list ( self ) :
"""Returns a list of the users gists as GistInfo objects
Returns :
a list of GistInfo objects""" | # Define the basic request . The per _ page parameter is set to 100 , which
# is the maximum github allows . If the user has more than one page of
# gists , this request object will be modified to retrieve each
# successive page of gists .
request = requests . Request ( 'GET' , 'https://api.github.com/gists' , headers ... |
def _run_shell_command ( self , command , pipe_it = True ) :
"""Runs the given shell command .
: param command :
: return : bool Status""" | stdout = None
if pipe_it :
stdout = PIPE
self . logger . debug ( 'Executing shell command: %s' % command )
return not bool ( Popen ( command , shell = True , stdout = stdout ) . wait ( ) ) |
def attach_volume ( self , xml_bytes ) :
"""Parse the XML returned by the C { AttachVolume } function .
@ param xml _ bytes : XML bytes with a C { AttachVolumeResponse } root
element .
@ return : a C { dict } with status and attach _ time keys .
TODO : volumeId , instanceId , device""" | root = XML ( xml_bytes )
status = root . findtext ( "status" )
attach_time = root . findtext ( "attachTime" )
attach_time = datetime . strptime ( attach_time [ : 19 ] , "%Y-%m-%dT%H:%M:%S" )
return { "status" : status , "attach_time" : attach_time } |
def split_recursive ( self , decl_string ) :
"""implementation details""" | assert self . has_pattern ( decl_string )
to_go = [ decl_string ]
while to_go :
name , args = self . split ( to_go . pop ( ) )
for arg in args :
if self . has_pattern ( arg ) :
to_go . append ( arg )
yield name , args |
def handle_addSubmodule ( repo , ** kwargs ) :
""": return : repo . addSubmodule ( )""" | log . info ( 'addSubmodule: %s %s' % ( repo , kwargs ) )
try :
proxy = repo . addSubmodule ( ** kwargs )
return [ serialize ( proxy , type = 'submodule' , url = proxy . url ) ]
except RepoError , e :
raise |
def present ( name , value , acls = None , ephemeral = False , sequence = False , makepath = False , version = - 1 , profile = None , hosts = None , scheme = None , username = None , password = None , default_acl = None ) :
'''Make sure znode is present in the correct state with the correct acls
name
path to zn... | ret = { 'name' : name , 'result' : False , 'comment' : 'Failed to setup znode {0}' . format ( name ) , 'changes' : { } }
connkwargs = { 'profile' : profile , 'hosts' : hosts , 'scheme' : scheme , 'username' : username , 'password' : password , 'default_acl' : default_acl }
if acls is None :
chk_acls = [ ]
else :
... |
def get_definition_metrics ( self , project , definition_id , min_metrics_time = None ) :
"""GetDefinitionMetrics .
[ Preview API ] Gets build metrics for a definition .
: param str project : Project ID or project name
: param int definition _ id : The ID of the definition .
: param datetime min _ metrics _... | route_values = { }
if project is not None :
route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' )
if definition_id is not None :
route_values [ 'definitionId' ] = self . _serialize . url ( 'definition_id' , definition_id , 'int' )
query_parameters = { }
if min_metrics_time is not ... |
def prepare_everything ( self ) :
"""Convenience method to make the actual | HydPy | instance runable .""" | self . prepare_network ( )
self . init_models ( )
self . load_conditions ( )
with hydpy . pub . options . warnmissingobsfile ( False ) :
self . prepare_nodeseries ( )
self . prepare_modelseries ( )
self . load_inputseries ( ) |
def from_data ( room , conn , data ) :
"""Construct a ChatMessage instance from raw protocol data""" | files = list ( )
rooms = dict ( )
msg = str ( )
for part in data [ "message" ] :
ptype = part [ "type" ]
if ptype == "text" :
val = part [ "value" ]
msg += val
elif ptype == "break" :
msg += "\n"
elif ptype == "file" :
fileid = part [ "id" ]
fileobj = room . filed... |
def endswith ( self , name : str ) -> List [ str ] :
"""Return a list of all keywords ending with the given string .
> > > from hydpy . core . devicetools import Keywords
> > > keywords = Keywords ( ' first _ keyword ' , ' second _ keyword ' ,
. . . ' keyword _ 3 ' , ' keyword _ 4 ' ,
. . . ' keyboard ' )
... | return sorted ( keyword for keyword in self if keyword . endswith ( name ) ) |
def embed_code_links ( app , exception ) :
"""Embed hyperlinks to documentation into example code""" | if exception is not None :
return
# No need to waste time embedding hyperlinks when not running the examples
# XXX : also at the time of writing this fixes make html - noplot
# for some reason I don ' t fully understand
if not app . builder . config . plot_gallery :
return
# XXX : Whitelist of builders for whic... |
def build ( opts = None ) :
"""Build a new board using the given options .
: param opts : dictionary mapping str - > Opt
: return : the new board , Board""" | board = catan . board . Board ( )
modify ( board , opts )
return board |
def points ( ys , width = None ) :
'''Usage :
import scipy . stats
def walk ( steps , position = 0 ) :
for step in steps :
position + = step
yield position
positions = list ( walk ( scipy . stats . norm . rvs ( size = 1000 ) ) )
points ( positions )''' | if width is None :
width = terminal . width ( )
ys = np . array ( ys )
n = len ( ys )
y_min , y_max = np . min ( ys ) , np . max ( ys )
n_bins = min ( width , n )
bins_per_n = float ( n_bins ) / float ( n )
# print n , n _ bins , n _ per _ bin , bins _ per _ n
sums = np . zeros ( n_bins )
counts = np . zeros ( n_bi... |
def real ( self ) :
"""Element - wise real part
Raises :
NoConjugateMatrix : if entries have no ` conjugate ` method and no
other way to determine the real part
Note :
A mathematically equivalent way to obtain a real matrix from a
complex matrix ` ` M ` ` is : :
( M . conjugate ( ) + M ) / 2
However... | def re ( val ) :
if hasattr ( val , 'real' ) :
return val . real
elif hasattr ( val , 'as_real_imag' ) :
return val . as_real_imag ( ) [ 0 ]
elif hasattr ( val , 'conjugate' ) :
return ( val . conjugate ( ) + val ) / 2
else :
raise NoConjugateMatrix ( "Matrix entry %s con... |
def _combine_args ( self ) :
"""Sets protected data by combining raw data set from the constructor .
If a ` ` _ parent ` ` is set , updates the ` ` _ flat _ path ` ` and sets the
` ` _ namespace ` ` and ` ` _ project ` ` if not already set .
: rtype : : class : ` list ` of : class : ` dict `
: returns : A l... | child_path = self . _parse_path ( self . _flat_path )
if self . _parent is not None :
if self . _parent . is_partial :
raise ValueError ( "Parent key must be complete." )
# We know that _ parent . path ( ) will return a copy .
child_path = self . _parent . path + child_path
self . _flat_path = s... |
def check_ok_button ( self ) :
"""Helper to enable or not the OK button .""" | login = self . login . text ( )
password = self . password . text ( )
url = self . url . text ( )
if self . layers . count ( ) >= 1 and login and password and url :
self . ok_button . setEnabled ( True )
else :
self . ok_button . setEnabled ( False ) |
def stop_instance ( self , instance_id ) :
"""Stops the instance gracefully .
: param str instance _ id : instance identifier""" | instance = self . _load_instance ( instance_id )
instance . terminate ( )
del self . _instances [ instance_id ] |
def uniform_discr_fromspace ( fspace , shape , dtype = None , impl = 'numpy' , ** kwargs ) :
"""Return a uniformly discretized L ^ p function space .
Parameters
fspace : ` FunctionSpace `
Continuous function space . Its domain must be an ` IntervalProd ` .
shape : int or sequence of ints
Number of samples... | if not isinstance ( fspace , FunctionSpace ) :
raise TypeError ( '`fspace` {!r} is not a `FunctionSpace` instance' '' . format ( fspace ) )
if not isinstance ( fspace . domain , IntervalProd ) :
raise TypeError ( 'domain {!r} of the function space is not an ' '`IntervalProd` instance' . format ( fspace . domain... |
def get_rate_normalization ( hit_file , parameter , reference = 'event' , cluster_file = None , plot = False , chunk_size = 500000 ) :
'''Takes different hit files ( hit _ files ) , extracts the number of events or the scan time ( reference ) per scan parameter ( parameter )
and returns an array with a normalizat... | logging . info ( 'Calculate the rate normalization' )
with tb . open_file ( hit_file , mode = "r+" ) as in_hit_file_h5 : # open the hit file
meta_data = in_hit_file_h5 . root . meta_data [ : ]
scan_parameter = get_scan_parameter ( meta_data ) [ parameter ]
event_numbers = get_meta_data_at_scan_parameter ( m... |
def _add_mac_token ( self , uri , http_method = 'GET' , body = None , headers = None , token_placement = AUTH_HEADER , ext = None , ** kwargs ) :
"""Add a MAC token to the request authorization header .
Warning : MAC token support is experimental as the spec is not yet stable .""" | if token_placement != AUTH_HEADER :
raise ValueError ( "Invalid token placement." )
headers = tokens . prepare_mac_header ( self . access_token , uri , self . mac_key , http_method , headers = headers , body = body , ext = ext , hash_algorithm = self . mac_algorithm , ** kwargs )
return uri , headers , body |
def set_tensor_symmetry_old ( force_constants , lattice , # column vectors
positions , symmetry ) :
"""Full force constants are symmetrized using crystal symmetry .
This method extracts symmetrically equivalent sets of atomic pairs and
take sum of their force constants and average the sum .
Since get _ force ... | rotations = symmetry . get_symmetry_operations ( ) [ 'rotations' ]
translations = symmetry . get_symmetry_operations ( ) [ 'translations' ]
symprec = symmetry . get_symmetry_tolerance ( )
fc_bak = force_constants . copy ( )
# Create mapping table between an atom and the symmetry operated atom
# map [ i , j ]
# i : atom... |
def listRoles ( self , * args , ** kwargs ) :
"""List Roles
Get a list of all roles , each role object also includes the list of
scopes it expands to .
This method gives output : ` ` v1 / list - roles - response . json # ` `
This method is ` ` stable ` `""" | return self . _makeApiCall ( self . funcinfo [ "listRoles" ] , * args , ** kwargs ) |
def ultimate_oscillator ( close_data , low_data ) :
"""Ultimate Oscillator .
Formula :
UO = 100 * ( ( 4 * AVG7 ) + ( 2 * AVG14 ) + AVG28 ) / ( 4 + 2 + 1)""" | a7 = 4 * average_7 ( close_data , low_data )
a14 = 2 * average_14 ( close_data , low_data )
a28 = average_28 ( close_data , low_data )
uo = 100 * ( ( a7 + a14 + a28 ) / 7 )
return uo |
def is_jamo_modern ( character ) :
"""Test if a single character is a modern jamo character .
Modern jamo includes all U + 11xx jamo in addition to HCJ in modern usage ,
as defined in Unicode 7.0.
WARNING : U + 1160 is NOT considered a modern jamo character , but it is listed
under ' Medial Vowels ' in the ... | code = ord ( character )
return 0x1100 <= code <= 0x1112 or 0x1161 <= code <= 0x1175 or 0x11A8 <= code <= 0x11C2 or is_hcj_modern ( character ) |
def _validate_tag_key ( self , tag_key , exception_param = 'tags.X.member.key' ) :
"""Validates the tag key .
: param all _ tags : Dict to check if there is a duplicate tag .
: param tag _ key : The tag key to check against .
: param exception _ param : The exception parameter to send over to help format the ... | # Validate that the key length is correct :
if len ( tag_key ) > 128 :
raise TagKeyTooBig ( tag_key , param = exception_param )
# Validate that the tag key fits the proper Regex :
# [ \ w \ s _ . : / = + \ - @ ] + SHOULD be the same as the Java regex on the AWS documentation : [ \ p { L } \ p { Z } \ p { N } _ . : ... |
def get_ast_field_name ( ast ) :
"""Return the normalized field name for the given AST node .""" | replacements = { # We always rewrite the following field names into their proper underlying counterparts .
TYPENAME_META_FIELD_NAME : '@class' }
base_field_name = ast . name . value
normalized_name = replacements . get ( base_field_name , base_field_name )
return normalized_name |
def rebind_string ( self , keysym , newstring ) :
"""Change the translation of KEYSYM to NEWSTRING .
If NEWSTRING is None , remove old translation if any .""" | if newstring is None :
try :
del self . keysym_translations [ keysym ]
except KeyError :
pass
else :
self . keysym_translations [ keysym ] = newstring |
def getSubscriptionResults ( self , objectID = None ) :
"""getSubscriptionResults ( string ) - > dict ( integer : < value _ type > )
Returns the subscription results for the last time step and the given object .
If no object id is given , all subscription results are returned in a dict .
If the object id is u... | return self . _connection . _getSubscriptionResults ( self . _subscribeResponseID ) . get ( objectID ) |
def install ( name = None , refresh = False , fromrepo = None , pkgs = None , sources = None , ** kwargs ) :
'''Install package ( s ) using ` ` pkg _ add ( 1 ) ` `
name
The name of the package to be installed .
refresh
Whether or not to refresh the package database before installing .
fromrepo or packager... | try :
pkg_params , pkg_type = __salt__ [ 'pkg_resource.parse_targets' ] ( name , pkgs , sources , ** kwargs )
except MinionError as exc :
raise CommandExecutionError ( exc )
if not pkg_params :
return { }
packageroot = kwargs . get ( 'packageroot' )
if not fromrepo and packageroot :
fromrepo = packagero... |
def copy ( tree , source_filename ) :
"""Copy file in tree , show a progress bar during operations ,
and return the sha1 sum of copied file .""" | # _ , ext = os . path . splitext ( source _ filename )
filehash = sha1 ( )
with printer . progress ( os . path . getsize ( source_filename ) ) as update :
with open ( source_filename , 'rb' ) as fsource :
with NamedTemporaryFile ( dir = os . path . join ( tree , '.kolekto' , 'movies' ) , delete = False ) as... |
def remove_completer ( self ) :
"""Removes current completer .
: return : Method success .
: rtype : bool""" | if self . __completer :
LOGGER . debug ( "> Removing '{0}' completer." . format ( self . __completer ) )
# Signals / Slots .
self . __completer . activated . disconnect ( self . __insert_completion )
self . __completer . deleteLater ( )
self . __completer = None
return True |
def value ( self , value ) :
"""Set the value of the option .
: param value : the option value""" | opt_type = defines . OptionRegistry . LIST [ self . _number ] . value_type
if opt_type == defines . INTEGER :
if type ( value ) is not int :
value = int ( value )
if byte_len ( value ) == 0 :
value = 0
elif opt_type == defines . STRING :
if type ( value ) is not str :
value = str ( v... |
def pack ( self ) :
"""Pack message to binary stream .""" | payload = io . BytesIO ( )
# Advance num bytes equal to header size - the header is written later
# after the payload of all segments and parts has been written :
payload . seek ( self . header_size , io . SEEK_CUR )
# Write out payload of segments and parts :
self . build_payload ( payload )
packet_length = len ( payl... |
def update_file_status ( self ) :
"""Update the status of all the files in the archive""" | nfiles = len ( self . cache . keys ( ) )
status_vect = np . zeros ( ( 6 ) , int )
sys . stdout . write ( "Updating status of %i files: " % nfiles )
sys . stdout . flush ( )
for i , key in enumerate ( self . cache . keys ( ) ) :
if i % 200 == 0 :
sys . stdout . write ( '.' )
sys . stdout . flush ( )
... |
def split_extension ( pathname ) :
"""@ type pathname : str
@ param pathname : Absolute path .
@ rtype : tuple ( str , str )
@ return :
Tuple containing the file and extension components of the filename .""" | filepart = win32 . PathRemoveExtension ( pathname )
extpart = win32 . PathFindExtension ( pathname )
return ( filepart , extpart ) |
def get_records ( self ) :
"""Get the next set of records in this shard . An empty list doesn ' t guarantee the shard is exhausted .
: returns : A list of reformatted records . May be empty .""" | # Won ' t be able to find new records .
if self . exhausted :
return [ ]
# Already caught up , just the one call please .
if self . empty_responses >= CALLS_TO_REACH_HEAD :
return self . _apply_get_records_response ( self . session . get_stream_records ( self . iterator_id ) )
# Up to 5 calls to try and find a ... |
def open_url ( url , retries = 0 , sleep = 0.5 ) :
'''Open a mysql connection to a url . Note that if your password has
punctuation characters , it might break the parsing of url .
url : A string in the form " mysql : / / username : password @ host . domain / database "''' | return open_conn ( retries = retries , sleep = sleep , ** parse_url ( url ) ) |
def resource_get_list ( self ) :
"""Get list of this plugins resources and a hash to check for file changes
( It is recommended to keep a in memory representation of this struct
and not to generate it upon each request )
: return : List of supported resources and hashes
: rtype : list [ ( unicode , unicode ... | if not self . _resources :
return self . resource_update_list ( )
res = [ ]
with self . _resource_lock :
for key in self . _resources :
res . append ( ( key , self . _resources [ key ] [ 'hash' ] ) )
return res |
def summary ( ) :
'''. . versionadded : : 2014.7.0
Show a summary of the last puppet agent run
CLI Example :
. . code - block : : bash
salt ' * ' puppet . summary''' | puppet = _Puppet ( )
try :
with salt . utils . files . fopen ( puppet . lastrunfile , 'r' ) as fp_ :
report = salt . utils . yaml . safe_load ( fp_ )
result = { }
if 'time' in report :
try :
result [ 'last_run' ] = datetime . datetime . fromtimestamp ( int ( report [ 'time' ] [ '... |
def add_chart ( self , chart , row , col ) :
"""Adds a chart to the worksheet at ( row , col ) .
: param xltable . Chart Chart : chart to add to the workbook .
: param int row : Row to add the chart at .""" | self . __charts . append ( ( chart , ( row , col ) ) ) |
def get_asset_admin_session_for_repository ( self , repository_id = None , * args , ** kwargs ) :
"""Gets an asset administration session for the given repository .
arg : repository _ id ( osid . id . Id ) : the Id of the repository
return : ( osid . repository . AssetAdminSession ) - an
AssetAdminSession
r... | if not repository_id :
raise NullArgument ( )
if not self . supports_asset_admin ( ) :
raise Unimplemented ( )
try :
from . import sessions
except ImportError :
raise OperationFailed ( 'import error' )
try :
session = sessions . AssetAdminSession ( repository_id , proxy = self . _proxy , runtime = s... |
def term_doc_lists ( self ) :
'''Returns
dict''' | doc_ids = self . _X . transpose ( ) . tolil ( ) . rows
terms = self . _term_idx_store . values ( )
return dict ( zip ( terms , doc_ids ) ) |
def FitRadius ( z , SampleFreq , Damping , HistBins = 100 ) :
"""Fits the dynamical potential to the Steady
State Potential by varying the Radius .
z : ndarray
Position data
SampleFreq : float
frequency at which the position data was
sampled
Damping : float
value of damping ( in radians / second )
... | dt = 1 / SampleFreq
boltzmann = scipy . constants . Boltzmann
temp = 300
# why halved ? ?
density = 1800
SteadyStatePotnl = list ( steady_state_potential ( z , HistBins = HistBins ) )
yoffset = min ( SteadyStatePotnl [ 1 ] )
SteadyStatePotnl [ 1 ] -= yoffset
SpringPotnlFunc = dynamical_potential ( z , dt )
SpringPotnl ... |
def subontology ( self , minimal = False ) :
"""Generates a sub - ontology based on associations""" | return self . ontology . subontology ( self . objects , minimal = minimal ) |
def decompose_C ( self ) :
"""eigen - decompose self . C and update self . dC , self . C , self . B .
Known bugs : this might give a runtime error with
CMA _ diagonal / separable option on .""" | if self . opts [ 'CMA_diagonal' ] :
_print_warning ( "this might fail with CMA_diagonal option on" , iteration = self . countiter )
print ( self . opts [ 'CMA_diagonal' ] )
# print ( ' % . 19e ' % self . C [ 0 ] [ 0 ] )
self . C = ( self . C + self . C . T ) / 2
self . dC = np . diag ( self . C ) . copy ( )
sel... |
def from_bqtable ( cls , table , client = None ) :
"""A constructor that takes a : py : class : ` BQTable ` .
: param table :
: type table : BQTable""" | return cls ( table . project_id , table . dataset_id , table . table_id , client = client ) |
def safe_get ( d , key , def_val = None ) :
"""Helper function to fetch value from a dictionary
* ` d ` - Dictionary to fetch value from
* ` key ` - Key to lookup in dictionary
* ` def _ val ` - Default value to return if dict does not have a member with key""" | if d . has_key ( key ) :
return d [ key ]
else :
return def_val |
def prepare_message ( self , message_data , delivery_mode , content_type , content_encoding , ** kwargs ) :
"""Prepare message for sending .""" | return ( message_data , content_type , content_encoding ) |
def info ( name ) :
'''Show the information of the given virtual folder .
NAME : Name of a virtual folder .''' | with Session ( ) as session :
try :
result = session . VFolder ( name ) . info ( )
print ( 'Virtual folder "{0}" (ID: {1})' . format ( result [ 'name' ] , result [ 'id' ] ) )
print ( '- Owner:' , result [ 'is_owner' ] )
print ( '- Permission:' , result [ 'permission' ] )
prin... |
def get ( self , name , interval , ** kwargs ) :
'''Get the set of values for a named timeseries and interval . If timestamp
supplied , will fetch data for the period of time in which that timestamp
would have fallen , else returns data for " now " . If the timeseries
resolution was not defined , then returns... | config = self . _intervals . get ( interval )
if not config :
raise UnknownInterval ( interval )
timestamp = kwargs . get ( 'timestamp' , time . time ( ) )
fetch = kwargs . get ( 'fetch' )
process_row = kwargs . get ( 'process_row' ) or self . _process_row
condense = kwargs . get ( 'condense' , False )
join_rows = ... |
def _init_fncsortnt ( flds ) :
"""Return a sort function for sorting header GO IDs found in sections .""" | if 'tinfo' in flds :
if 'D1' in flds :
return lambda ntgo : [ ntgo . NS , - 1 * ntgo . tinfo , ntgo . depth , ntgo . D1 , ntgo . alt ]
else :
return lambda ntgo : [ ntgo . NS , - 1 * ntgo . tinfo , ntgo . depth , ntgo . alt ]
if 'dcnt' in flds :
if 'D1' in flds :
return lambda ntgo :... |
def inline_parse ( text , verbose = False ) :
"""Extract all quantities from unstructured text .""" | if isinstance ( text , str ) :
text = text . decode ( 'utf-8' )
parsed = parse ( text , verbose = verbose )
shift = 0
for quantity in parsed :
index = quantity . span [ 1 ] + shift
to_add = u' {' + unicode ( quantity ) + u'}'
text = text [ 0 : index ] + to_add + text [ index : ]
shift += len ( to_ad... |
def pareto_nbd_model ( T , r , alpha , s , beta , size = 1 ) :
"""Generate artificial data according to the Pareto / NBD model .
See [ 2 ] _ for model details .
Parameters
T : array _ like
The length of time observing new customers .
r , alpha , s , beta : float
Parameters in the model . See [ 1 ] _
s... | if type ( T ) in [ float , int ] :
T = T * np . ones ( size )
else :
T = np . asarray ( T )
lambda_ = random . gamma ( r , scale = 1.0 / alpha , size = size )
mus = random . gamma ( s , scale = 1.0 / beta , size = size )
columns = [ "frequency" , "recency" , "T" , "lambda" , "mu" , "alive" , "customer_id" ]
df ... |
def sfs_folded_scaled ( ac , n = None ) :
"""Compute the folded site frequency spectrum scaled such that a constant
value is expected across the spectrum for neutral variation and constant
population size .
Parameters
ac : array _ like , int , shape ( n _ variants , 2)
Allele counts array .
n : int , op... | # check input
ac , n = _check_ac_n ( ac , n )
# compute the site frequency spectrum
s = sfs_folded ( ac , n = n )
# apply scaling
s = scale_sfs_folded ( s , n )
return s |
def complete_leaf_value ( return_type , # type : Union [ GraphQLEnumType , GraphQLScalarType ]
path , # type : List [ Union [ int , str ] ]
result , # type : Any
) : # type : ( . . . ) - > Union [ int , str , float , bool ]
"""Complete a Scalar or Enum by serializing to a valid value , returning null if serializati... | assert hasattr ( return_type , "serialize" ) , "Missing serialize method on type"
serialized_result = return_type . serialize ( result )
if serialized_result is None :
raise GraphQLError ( ( 'Expected a value of type "{}" but ' + "received: {}" ) . format ( return_type , result ) , path = path , )
return serialized... |
def get_transport_info ( self , key : str ) -> Any :
"""Get extra info from the transport .
Supported keys :
- ` ` peername ` `
- ` ` socket ` `
- ` ` sockname ` `
- ` ` compression ` `
- ` ` cipher ` `
- ` ` peercert ` `
- ` ` sslcontext ` `
- ` ` sslobject ` `
: raises SMTPServerDisconnected :... | self . _raise_error_if_disconnected ( )
return self . transport . get_extra_info ( key ) |
def ToScriptHash ( self , address ) :
"""Retrieve the script _ hash based from an address .
Args :
address ( str ) : a base58 encoded address .
Raises :
ValuesError : if an invalid address is supplied or the coin version is incorrect
Exception : if the address string does not start with ' A ' or the check... | if len ( address ) == 34 :
if address [ 0 ] == 'A' :
data = b58decode ( address )
if data [ 0 ] != self . AddressVersion :
raise ValueError ( 'Not correct Coin Version' )
checksum = Crypto . Default ( ) . Hash256 ( data [ : 21 ] ) [ : 4 ]
if checksum != data [ 21 : ] :
... |
def getsshkeys ( self ) :
"""Gets all the ssh keys for the current user
: return : a dictionary with the lists""" | request = requests . get ( self . keys_url , headers = self . headers , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout )
if request . status_code == 200 :
return request . json ( )
else :
return False |
def set_http_caching ( request , gateway = 'crab' , region = 'permanent' ) :
"""Set an HTTP Cache Control header on a request .
: param pyramid . request . Request request : Request to set headers on .
: param str gateway : What gateway are we caching for ? Defaults to ` crab ` .
: param str region : What cac... | crabpy_exp = request . registry . settings . get ( 'crabpy.%s.cache_config.%s.expiration_time' % ( gateway , region ) , None )
if crabpy_exp is None :
return request
ctime = int ( int ( crabpy_exp ) * 1.05 )
request . response . cache_expires ( ctime , public = True )
return request |
def authorize_get ( self , session , fields = [ ] ) :
'''taobao . itemcats . authorize . get 查询B商家被授权品牌列表和类目列表''' | sellerAuthorize = SellerAuthorize ( )
request = TOPRequest ( 'taobao.authorize.get' )
if not fields :
fields = sellerAuthorize . fields
request [ 'fields' ] = ',' . join ( fields )
self . create ( self . execute ( request , session ) )
return self . seller_authorize |
def _read_datafile_entry ( spg , no , symbol , setting , f ) :
"""Read space group data from f to spg .""" | spg . _no = no
spg . _symbol = symbol . strip ( )
spg . _setting = setting
spg . _centrosymmetric = bool ( int ( f . readline ( ) . split ( ) [ 1 ] ) )
# primitive vectors
f . readline ( )
spg . _scaled_primitive_cell = np . array ( [ list ( map ( float , f . readline ( ) . split ( ) ) ) for i in range ( 3 ) ] , dtype ... |
def generate_code ( request , response ) :
"""Core function . Starts from a CodeGeneratorRequest and adds files to
a CodeGeneratorResponse""" | for proto_file in request . proto_file :
types = [ ]
messages = { }
results = traverse ( proto_file )
map_types = { }
def full_name ( package , item ) :
return "%s.%s" % ( package , item . name )
for item , package in results [ "types" ] :
if item . options . has_key ( "map_entry... |
def get_objective_form_for_update ( self , objective_id ) :
"""Gets the objective form for updating an existing objective .
A new objective form should be requested for each update
transaction .
arg : objective _ id ( osid . id . Id ) : the ` ` Id ` ` of the
` ` Objective ` `
return : ( osid . learning . ... | # Implemented from template for
# osid . resource . ResourceAdminSession . get _ resource _ form _ for _ update _ template
collection = JSONClientValidated ( 'learning' , collection = 'Objective' , runtime = self . _runtime )
if not isinstance ( objective_id , ABCId ) :
raise errors . InvalidArgument ( 'the argumen... |
def transform ( self , X , y = None , ** params ) :
"""Transforms * X * from phase - space to Fourier - space , returning the design
matrix produced by : func : ` Fourier . design _ matrix ` for input to a
regressor .
* * Parameters * *
X : array - like , shape = [ n _ samples , 1]
Column vector of phases... | data = numpy . dstack ( ( numpy . array ( X ) . T [ 0 ] , range ( len ( X ) ) ) ) [ 0 ]
phase , order = data [ data [ : , 0 ] . argsort ( ) ] . T
design_matrix = self . design_matrix ( phase , self . degree )
return design_matrix [ order . argsort ( ) ] |
def format_event_log_date ( date_string , utc ) :
"""Gets a date in the format that the SoftLayer _ EventLog object likes .
: param string date _ string : date in mm / dd / yyyy format
: param string utc : utc offset . Defaults to ' + 0000'""" | user_date_format = "%m/%d/%Y"
user_date = datetime . datetime . strptime ( date_string , user_date_format )
dirty_time = user_date . isoformat ( )
if utc is None :
utc = "+0000"
iso_time_zone = utc [ : 3 ] + ':' + utc [ 3 : ]
cleaned_time = "{}.000000{}" . format ( dirty_time , iso_time_zone )
return cleaned_time |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.