signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def append ( self , text ) :
"""Append line to the end""" | cursor = QTextCursor ( self . _doc )
cursor . movePosition ( QTextCursor . End )
cursor . insertBlock ( )
cursor . insertText ( text ) |
def eval_hessian ( self , * args , ** kwargs ) :
""": return : Hessian evaluated at the specified point .""" | # Evaluate the hessian model and use the resulting Ans namedtuple as a
# dict . From this , take the relevant components .
eval_hess_dict = self . hessian_model ( * args , ** kwargs ) . _asdict ( )
hess = [ [ [ np . broadcast_to ( eval_hess_dict . get ( D ( var , p1 , p2 ) , 0 ) , eval_hess_dict [ var ] . shape ) for p... |
def train ( self , dataset ) :
r"""Train model with given feature .
Parameters
X : array - like , shape = ( n _ samples , n _ features )
Train feature vector .
Y : array - like , shape = ( n _ samples , n _ labels )
Target labels .
Attributes
clfs \ _ : list of : py : mod : ` libact . models ` object ... | X , Y = dataset . format_sklearn ( )
X = np . array ( X )
Y = np . array ( Y )
self . n_labels_ = np . shape ( Y ) [ 1 ]
self . n_features_ = np . shape ( X ) [ 1 ]
self . clfs_ = [ ]
for i in range ( self . n_labels_ ) : # TODO should we handle it here or we should handle it before calling
if len ( np . unique ( Y... |
def data_attrs ( mapitem ) :
"""Generate the data - . . . attributes for a mapitem .""" | data_attrs = { }
try :
data_attrs [ 'marker-detail-api-url' ] = reverse ( 'fluentcms-googlemaps-marker-detail' )
except NoReverseMatch :
pass
data_attrs . update ( mapitem . get_map_options ( ) )
return mark_safe ( u'' . join ( [ format_html ( u' data-{0}="{1}"' , k . replace ( '_' , '-' ) , _data_value ( v ) )... |
def reference_to_greatcircle ( reference_frame , greatcircle_frame ) :
"""Convert a reference coordinate to a great circle frame .""" | # Define rotation matrices along the position angle vector , and
# relative to the origin .
pole = greatcircle_frame . pole . transform_to ( coord . ICRS )
ra0 = greatcircle_frame . ra0
center = greatcircle_frame . center
R_rot = rotation_matrix ( greatcircle_frame . rotation , 'z' )
if not np . isnan ( ra0 ) :
xax... |
def decoratornames ( self ) :
"""Get the qualified names of each of the decorators on this function .
: returns : The names of the decorators .
: rtype : set ( str )""" | result = set ( )
decoratornodes = [ ]
if self . decorators is not None :
decoratornodes += self . decorators . nodes
decoratornodes += self . extra_decorators
for decnode in decoratornodes :
try :
for infnode in decnode . infer ( ) :
result . add ( infnode . qname ( ) )
except exceptions... |
def b64decode ( s , altchars = None , validate = False ) :
"""Decode bytes encoded with the standard Base64 alphabet .
Argument ` ` s ` ` is a : term : ` bytes - like object ` or ASCII string to
decode .
Optional ` ` altchars ` ` must be a : term : ` bytes - like object ` or ASCII
string of length 2 which s... | if version_info < ( 3 , 0 ) or validate :
if validate and len ( s ) % 4 != 0 :
raise BinAsciiError ( 'Incorrect padding' )
s = _get_bytes ( s )
if altchars is not None :
altchars = _get_bytes ( altchars )
assert len ( altchars ) == 2 , repr ( altchars )
if version_info < ( 3 ... |
def plot ( self ) :
"""plot the activation function""" | plt . ion ( )
plt . show ( )
x = numpy . linspace ( 0 , 15 , 100 )
y = numpy . zeros ( x . shape )
y = self . excite ( y , x )
plt . plot ( x , y )
plt . xlabel ( 'Input' )
plt . ylabel ( 'Persistence' )
plt . title ( 'Sigmoid Activation Function' ) |
def _populate ( self , soup ) :
"""Populate the list , assuming ` ` soup ` ` is a ` ` BeautifulSoup ` ` object .""" | tables = soup . select ( 'table[rules=all]' )
if not tables :
return
trs = tables [ 0 ] . select ( 'tr' ) [ 1 : ]
if len ( trs [ 0 ] ) == 5 : # M1
self . _populate_small_table ( trs )
else : # M2
self . _populate_large_table ( trs ) |
def flattened ( self , order = None , include_smaller = True ) :
"""Return a flattened pixel collection at a single order .""" | if order is None :
order = self . order
else :
order = self . _validate_order ( order )
# Start with the cells which are already at this order .
flat = set ( self [ order ] )
# Look at lower orders and expand them into this set .
# Based on the " map " algorithm from Appendix A of the
# MOC recommendation .
for... |
def _fetch_url ( url ) :
"""Returns the content of the provided URL .""" | try :
resp = urllib2 . urlopen ( _Request ( url ) )
except urllib2 . URLError :
if 'wikileaks.org' in url :
resp = urllib2 . urlopen ( _Request ( url . replace ( 'wikileaks.org' , 'wikileaks.ch' ) ) )
else :
raise
if resp . info ( ) . get ( 'Content-Encoding' ) == 'gzip' :
return gzip . ... |
def logger_init ( level ) :
"""Initialize the logger for this thread .
Sets the log level to ERROR ( 0 ) , WARNING ( 1 ) , INFO ( 2 ) , or DEBUG ( 3 ) ,
depending on the argument ` level ` .""" | levellist = [ logging . ERROR , logging . WARNING , logging . INFO , logging . DEBUG ]
handler = logging . StreamHandler ( )
fmt = ( '%(levelname) -10s %(asctime)s %(name) -30s %(funcName) ' '-35s %(lineno) -5d: %(message)s' )
handler . setFormatter ( logging . Formatter ( fmt ) )
logger = logging . root
logger . addHa... |
def ReadClientSnapshotHistory ( self , client_id , timerange = None , cursor = None ) :
"""Reads the full history for a particular client .""" | client_id_int = db_utils . ClientIDToInt ( client_id )
query = ( "SELECT sn.client_snapshot, st.startup_info, " " UNIX_TIMESTAMP(sn.timestamp) FROM " "client_snapshot_history AS sn, " "client_startup_history AS st WHERE " "sn.client_id = st.client_id AND " "sn.timestamp = st.timestamp AND " "sn.client_id=%s " )
a... |
def get_redirect_link ( self ) :
"""Return the absolute URL to redirect or to open in
a browser . The first time the link is used it logs in the user
automatically and performs a redirect to a given page . Once used ,
the link keeps working as a plain redirect .
: return : The user ' s redirect link .
: r... | response = API . get_redirect_link ( self . api_token )
_fail_if_contains_errors ( response )
link_json = response . json ( )
return link_json [ 'link' ] |
def check_directory ( self ) :
"""Check if migrations directory exists .""" | exists = os . path . exists ( self . directory )
if not exists :
logger . error ( "No migrations directory found. Check your path or create a migration first." )
logger . error ( "Directory: %s" % self . directory )
return exists |
def setShowTerritory ( self , state ) :
"""Sets the display mode for this widget to the inputed mode .
: param state | < bool >""" | if state == self . _showTerritory :
return
self . _showTerritory = state
self . setDirty ( ) |
def start ( self ) :
"""Start session .""" | conn = self . loop . create_connection ( lambda : self , self . session . host , self . session . port )
task = self . loop . create_task ( conn )
task . add_done_callback ( self . init_done ) |
def find_subpixel_peak_position ( corr , subpixel_method = 'gaussian' ) :
"""Find subpixel approximation of the correlation peak .
This function returns a subpixels approximation of the correlation
peak by using one of the several methods available . If requested ,
the function also returns the signal to nois... | # initialization
default_peak_position = ( corr . shape [ 0 ] / 2 , corr . shape [ 1 ] / 2 )
# the peak locations
peak1_i , peak1_j , dummy = find_first_peak ( corr )
try : # the peak and its neighbours : left , right , down , up
c = corr [ peak1_i , peak1_j ]
cl = corr [ peak1_i - 1 , peak1_j ]
cr = corr [... |
def _solve_msm_eigensystem ( transmat , k ) :
"""Find the dominant eigenpairs of an MSM transition matrix
Parameters
transmat : np . ndarray , shape = ( n _ states , n _ states )
The transition matrix
k : int
The number of eigenpairs to find .
Notes
Normalize the left ( : math : ` \ phi ` ) and right ... | u , lv , rv = scipy . linalg . eig ( transmat , left = True , right = True )
order = np . argsort ( - np . real ( u ) )
u = np . real_if_close ( u [ order [ : k ] ] )
lv = np . real_if_close ( lv [ : , order [ : k ] ] )
rv = np . real_if_close ( rv [ : , order [ : k ] ] )
return _normalize_eigensystem ( u , lv , rv ) |
def to_netcdf ( self , path = None , mode = 'w' , format = None , group = None , engine = None , encoding = None , unlimited_dims = None , compute = True ) :
"""Write dataset contents to a netCDF file .
Parameters
path : str , Path or file - like object , optional
Path to which to save this dataset . File - l... | if encoding is None :
encoding = { }
from . . backends . api import to_netcdf
return to_netcdf ( self , path , mode , format = format , group = group , engine = engine , encoding = encoding , unlimited_dims = unlimited_dims , compute = compute ) |
def _IsIdentifier ( cls , string ) :
"""Checks if a string contains an identifier .
Args :
string ( str ) : string to check .
Returns :
bool : True if the string contains an identifier , False otherwise .""" | return ( string and not string [ 0 ] . isdigit ( ) and all ( character . isalnum ( ) or character == '_' for character in string ) ) |
def system_config_dir ( ) :
r"""Return the system - wide config dir ( full path ) .
- Linux , SunOS : / etc / glances
- * BSD , macOS : / usr / local / etc / glances
- Windows : % APPDATA % \ glances""" | if LINUX or SUNOS :
path = '/etc'
elif BSD or MACOS :
path = '/usr/local/etc'
else :
path = os . environ . get ( 'APPDATA' )
if path is None :
path = ''
else :
path = os . path . join ( path , 'glances' )
return path |
def tail ( self , n = 5 ) :
"""Return last n rows of each group .
Essentially equivalent to ` ` . apply ( lambda x : x . tail ( n ) ) ` ` ,
except ignores as _ index flag .
% ( see _ also ) s
Examples
> > > df = pd . DataFrame ( [ [ ' a ' , 1 ] , [ ' a ' , 2 ] , [ ' b ' , 1 ] , [ ' b ' , 2 ] ] ,
columns... | self . _reset_group_selection ( )
mask = self . _cumcount_array ( ascending = False ) < n
return self . _selected_obj [ mask ] |
def prepare_for_json_encoding ( obj ) :
"""Convert an arbitrary object into just JSON data types ( list , dict , unicode str , int , bool , null ) .""" | obj_type = type ( obj )
if obj_type == list or obj_type == tuple :
return [ prepare_for_json_encoding ( item ) for item in obj ]
if obj_type == dict : # alphabetizing keys lets us compare attributes for equality across runs
return OrderedDict ( ( prepare_for_json_encoding ( k ) , prepare_for_json_encoding ( obj... |
def WhereIs ( self , prog , path = None , pathext = None , reject = [ ] ) :
"""Find prog in the path .""" | if path is None :
try :
path = self [ 'ENV' ] [ 'PATH' ]
except KeyError :
pass
elif SCons . Util . is_String ( path ) :
path = self . subst ( path )
if pathext is None :
try :
pathext = self [ 'ENV' ] [ 'PATHEXT' ]
except KeyError :
pass
elif SCons . Util . is_String... |
def _raise_for_status ( response ) :
'''Custom raise _ for _ status with more appropriate error message .''' | http_error_msg = ""
if 400 <= response . status_code < 500 :
http_error_msg = "{0} Client Error: {1}" . format ( response . status_code , response . reason )
elif 500 <= response . status_code < 600 :
http_error_msg = "{0} Server Error: {1}" . format ( response . status_code , response . reason )
if http_error_... |
def first_return_times ( dts , c = None , d = 0.0 ) :
"""For an ensemble of time series , return the set of all time intervals
between successive returns to value c for all instances in the ensemble .
If c is not given , the default is the mean across all times and across all
time series in the ensemble .
A... | if c is None :
c = dts . mean ( )
vmrt = distob . vectorize ( analyses1 . first_return_times )
all_intervals = vmrt ( dts , c , d )
if hasattr ( type ( all_intervals ) , '__array_interface__' ) :
return np . ravel ( all_intervals )
else :
return np . hstack ( [ distob . gather ( ilist ) for ilist in all_int... |
def compute_samples ( self ) :
"""Sample from a Normal distribution with inferred mu and std""" | eps = tf . random_normal ( [ self . batch_size , self . eq_samples , self . iw_samples , self . num_latent ] )
z = tf . reshape ( eps * self . std + self . mu , [ - 1 , self . num_latent ] )
return z |
def set_bind ( self ) :
"""Sets key bindings - - we need this more than once""" | IntegerEntry . set_bind ( self )
self . bind ( '<Next>' , lambda e : self . set ( self . imin ) )
self . bind ( '<Prior>' , lambda e : self . set ( self . imax ) ) |
def lp10 ( self , subset_k , subset_p , weights = { } ) :
"""Force reactions in K above epsilon while minimizing support of P .
This program forces reactions in subset K to attain flux > epsilon
while minimizing the sum of absolute flux values for reactions
in subset P ( L1 - regularization ) .""" | if self . _z is None :
self . _add_minimization_vars ( )
positive = set ( subset_k ) - self . _flipped
negative = set ( subset_k ) & self . _flipped
v = self . _v . set ( positive )
cs = self . _prob . add_linear_constraints ( v >= self . _epsilon )
self . _temp_constr . extend ( cs )
v = self . _v . set ( negative... |
def _run_initdb ( name , auth = 'password' , user = None , password = None , encoding = 'UTF8' , locale = None , runas = None , waldir = None , checksums = False ) :
'''Helper function to call initdb''' | if runas is None :
if 'FreeBSD' in __grains__ [ 'os_family' ] :
runas = 'pgsql'
elif 'OpenBSD' in __grains__ [ 'os_family' ] :
runas = '_postgresql'
else :
runas = 'postgres'
if user is None :
user = runas
_INITDB_BIN = _find_pg_binary ( 'initdb' )
if not _INITDB_BIN :
raise ... |
def init_uniform_ttable ( wordlist ) :
"""Initialize ( normalized ) theta uniformly""" | n = len ( wordlist )
return numpy . ones ( ( n , n + 1 ) ) * ( 1 / n ) |
def _get_devices_by_activation_state ( self , state ) :
'''Get a list of bigips by activation statue .
: param state : str - - state to filter the returned list of devices
: returns : list - - list of devices that are in the given state''' | devices_with_state = [ ]
for device in self . devices :
act = device . tm . cm . devices . device . load ( name = get_device_info ( device ) . name , partition = self . partition )
if act . failoverState == state :
devices_with_state . append ( device )
return devices_with_state |
def disembowel ( rest ) :
"Disembowel some ( one | thing ) !" | if rest :
stabee = rest
karma . Karma . store . change ( stabee , - 1 )
else :
stabee = "someone nearby"
return ( "/me takes %s, brings them down to the basement, ties them to a " "leaky pipe, and once bored of playing with them mercifully " "ritually disembowels them..." % stabee ) |
def build ( root , source_module , output_dir , json_dump = False , ignore_modules = None , index_filename = 'index' ) :
'''Build markdown documentation from a directory and / or python module .
# ignore _ modules : takes a list of module names to ignore
# index _ filename : _ _ init _ _ . py output ( default i... | if root . endswith ( '/' ) :
root = root [ : - 1 ]
if ignore_modules is None :
ignore_modules = [ ]
elif isinstance ( ignore_modules , str ) :
ignore_modules = ignore_modules . split ( ',' )
# Ensure output _ dir format ( no / at start , / at end )
if output_dir . startswith ( '/' ) :
output_dir = outpu... |
def EccZmaxRperiRap ( self , * args , ** kwargs ) :
"""NAME :
EccZmaxRperiRap
PURPOSE :
evaluate the eccentricity , maximum height above the plane , peri - and apocenter
INPUT :
Either :
a ) R , vR , vT , z , vz [ , phi ] :
1 ) floats : phase - space value for single object ( phi is optional ) ( each ... | try :
return self . _EccZmaxRperiRap ( * args , ** kwargs )
except AttributeError : # pragma : no cover
raise NotImplementedError ( "'EccZmaxRperiRap' method not implemented for this actionAngle module" ) |
def reporter ( self ) :
"""Creates a report of the results""" | # Create a set of all the gene names without alleles or accessions e . g . sul1_18 _ AY260546 becomes sul1
genedict = dict ( )
# Load the notes file to a dictionary
notefile = os . path . join ( self . targetpath , 'notes.txt' )
with open ( notefile , 'r' ) as notes :
for line in notes : # Ignore comment lines - th... |
def fmt_ria ( ria , verbose = True , mip = False ) :
"""Format a | RepertoireIrreducibilityAnalysis | .""" | if verbose :
mechanism = 'Mechanism: {}\n' . format ( fmt_mechanism ( ria . mechanism , ria . node_labels ) )
direction = '\nDirection: {}' . format ( ria . direction )
else :
mechanism = ''
direction = ''
if config . REPR_VERBOSITY is HIGH :
partition = '\n{}:\n{}' . format ( ( 'MIP' if mip else 'P... |
def run_powerflow ( self , session , method = 'onthefly' , export_pypsa = False , debug = False ) :
"""Performs power flow calculation for all MV grids
Args :
session : sqlalchemy . orm . session . Session
Database session
method : str
Specify export method
If method = ' db ' grid data will be exported ... | if method == 'db' : # Empty tables
pypsa_io . delete_powerflow_tables ( session )
for grid_district in self . mv_grid_districts ( ) :
if export_pypsa :
export_pypsa_dir = repr ( grid_district . mv_grid )
else :
export_pypsa_dir = None
grid_district . mv_grid . run... |
def flush_and_refresh ( self , index ) :
"""Flush and refresh one or more indices .
. . warning : :
Do not call this method unless you know what you are doing . This
method is only intended to be called during tests .""" | self . client . indices . flush ( wait_if_ongoing = True , index = index )
self . client . indices . refresh ( index = index )
self . client . cluster . health ( wait_for_status = 'yellow' , request_timeout = 30 )
return True |
def dict_to_hdf5 ( dict_like , h5group ) :
"""Save a dictionnary - like object inside a h5 file group""" | # Write attributes
for key , value in dict_like . items ( ) :
if value is not None :
h5group . attrs [ str ( key ) ] = value |
def zero_mutable_fields ( pkt , sending = False ) :
"""When using AH , all " mutable " fields must be " zeroed " before calculating
the ICV . See RFC 4302 , Section 3.3.3.1 . Handling Mutable Fields .
@ param pkt : an IP ( v6 ) packet containing an AH layer .
NOTE : The packet will be modified
@ param sendi... | if pkt . haslayer ( AH ) :
pkt [ AH ] . icv = chr ( 0 ) * len ( pkt [ AH ] . icv )
else :
raise TypeError ( 'no AH layer found' )
if pkt . version == 4 : # the tos field has been replaced by DSCP and ECN
# Routers may rewrite the DS field as needed to provide a
# desired local or end - to - end service
pkt ... |
def _matcher ( self , other ) :
"""QueryCGRContainer < CGRContainer
QueryContainer < QueryCGRContainer [ more general ]""" | if isinstance ( other , CGRContainer ) :
return GraphMatcher ( other , self , lambda x , y : y == x , lambda x , y : y == x )
elif isinstance ( other , QueryCGRContainer ) :
return GraphMatcher ( other , self , lambda x , y : x == y , lambda x , y : x == y )
raise TypeError ( 'only cgr_query-cgr or cgr_query-cg... |
def create_changeset ( self , changeset , project = None ) :
"""CreateChangeset .
Create a new changeset .
: param : class : ` < TfvcChangeset > < azure . devops . v5_0 . tfvc . models . TfvcChangeset > ` changeset :
: param str project : Project ID or project name
: rtype : : class : ` < TfvcChangesetRef >... | route_values = { }
if project is not None :
route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' )
content = self . _serialize . body ( changeset , 'TfvcChangeset' )
response = self . _send ( http_method = 'POST' , location_id = '0bc8f0a4-6bfb-42a9-ba84-139da7b99c49' , version = '5.0' ... |
def put_script ( self , id , body , context = None , params = None ) :
"""Create a script in given language with specified ID .
` < http : / / www . elastic . co / guide / en / elasticsearch / reference / current / modules - scripting . html > ` _
: arg id : Script ID
: arg body : The document""" | for param in ( id , body ) :
if param in SKIP_IN_PATH :
raise ValueError ( "Empty value passed for a required argument." )
return self . transport . perform_request ( "PUT" , _make_path ( "_scripts" , id , context ) , params = params , body = body ) |
def write_quick ( self ) :
"""Send only the read / write bit""" | self . bus . write_quick ( self . address )
self . log . debug ( "write_quick: Sent the read / write bit" ) |
def isclose ( a , b , rtol = 1e-5 , atol = 1e-8 ) :
"""This is essentially np . isclose , but slightly faster .""" | return abs ( a - b ) < ( atol + rtol * abs ( b ) ) |
def _get_global_include_abs_path ( self , path ) :
"""Get a value after converting to absolute path .
Becoming different from other parameter ,
validation of ` include ` parameter is complex .
Before other validation ( at first ) this method is called to merge to
one configuration .
: param str path : You... | if not os . path . isabs ( path ) :
path = os . path . abspath ( path )
if os . path . isdir ( path ) or path . endswith ( '/' ) :
path = os . path . join ( path , '*' )
return path |
def create_blacklist_entry ( self , value , reason = "unwanted" , context = "allFields" , exact_match = False , enabled = True ) :
"""Creates a new blacklist entry .
Keyword arguments :
value - - The string value to blacklist .
reason - - The reason for why the value is blacklisted . Can be : " spam " , " unw... | create_blacklist_endpoint = Template ( "${rest_root}/blacklist/${public_key}" )
url = create_blacklist_endpoint . substitute ( rest_root = self . _rest_root , public_key = self . _public_key )
data = { "value" : value , "reason" : reason , "context" : context , "match" : "exact" if exact_match else "contains" , "status... |
def check_redundancy ( text ) :
"""Check the text .""" | err = "dates_times.am_pm.midnight_noon"
msg = ( u"'a.m.' is always morning; 'p.m.' is always night." )
list = [ "\d{1,2} ?a\.?m\.? in the morning" , "\d{1,2} ?p\.?m\.? in the evening" , "\d{1,2} ?p\.?m\.? at night" , "\d{1,2} ?p\.?m\.? in the afternoon" , ]
return existence_check ( text , list , err , msg , join = True... |
def normalized_distance ( self , * sequences ) :
"""Get distance from 0 to 1""" | return float ( self . distance ( * sequences ) ) / self . maximum ( * sequences ) |
def _pil_props ( self ) :
"""A tuple containing useful image properties extracted from this image
using Pillow ( Python Imaging Library , or ' PIL ' ) .""" | stream = BytesIO ( self . _blob )
pil_image = PIL_Image . open ( stream )
format = pil_image . format
width_px , height_px = pil_image . size
dpi = pil_image . info . get ( 'dpi' )
stream . close ( )
return ( format , ( width_px , height_px ) , dpi ) |
async def set_chat_title ( self , chat_id : typing . Union [ base . Integer , base . String ] , title : base . String ) -> base . Boolean :
"""Use this method to change the title of a chat . Titles can ' t be changed for private chats .
The bot must be an administrator in the chat for this to work and must have t... | payload = generate_payload ( ** locals ( ) )
result = await self . request ( api . Methods . SET_CHAT_TITLE , payload )
return result |
def to_json ( self ) :
"""Returns the JSON Representation of the content type field validation .""" | result = { }
for k , v in self . _data . items ( ) :
result [ camel_case ( k ) ] = v
return result |
def get_keys ( self , bucket , timeout = None ) :
"""Fetch a list of keys for the bucket""" | bucket_type = self . _get_bucket_type ( bucket . bucket_type )
url = self . key_list_path ( bucket . name , bucket_type = bucket_type , timeout = timeout )
status , _ , body = self . _request ( 'GET' , url )
if status == 200 :
props = json . loads ( bytes_to_str ( body ) )
return props [ 'keys' ]
else :
rai... |
def _busy_wait_ms ( self , ms ) :
"""Busy wait for the specified number of milliseconds .""" | start = time . time ( )
delta = ms / 1000.0
while ( time . time ( ) - start ) <= delta :
pass |
def set_std_streams_blocking ( ) :
"""Set stdout and stderr to be blocking .
This is called after Popen . communicate ( ) to revert stdout and stderr back
to be blocking ( the default ) in the event that the process to which they
were passed manipulated one or both file descriptors to be non - blocking .""" | if not fcntl :
return
for f in ( sys . __stdout__ , sys . __stderr__ ) :
fileno = f . fileno ( )
flags = fcntl . fcntl ( fileno , fcntl . F_GETFL )
fcntl . fcntl ( fileno , fcntl . F_SETFL , flags & ~ os . O_NONBLOCK ) |
def get_bounds ( tune_params ) :
"""create a bounds array from the tunable parameters""" | bounds = [ ]
for values in tune_params . values ( ) :
sorted_values = numpy . sort ( values )
bounds . append ( ( sorted_values [ 0 ] , sorted_values [ - 1 ] ) )
return bounds |
def xlabel ( self , labels ) :
"""Determine x - axis label
Parameters
labels : dict
Labels as specified by the user through the ` ` labs ` ` or
` ` xlab ` ` calls .
Returns
out : str
x - axis label""" | if self . panel_scales_x [ 0 ] . name is not None :
return self . panel_scales_x [ 0 ] . name
else :
return labels . get ( 'x' , '' ) |
def _RawGlobPathSpecWithAlphabeticalSchema ( file_system , parent_path_spec , segment_format , location , segment_length , upper_case = False ) :
"""Globs for path specifications according to an alphabetical naming schema .
Args :
file _ system ( FileSystem ) : file system .
parent _ path _ spec ( PathSpec ) ... | segment_number = 0
segment_files = [ ]
while True :
segment_index = segment_number
segment_letters = [ ]
while len ( segment_letters ) < segment_length :
segment_index , remainder = divmod ( segment_index , 26 )
if upper_case :
segment_letters . append ( chr ( ord ( 'A' ) + remai... |
def api_user ( request , userPk , key = None , hproPk = None ) :
"""Return information about an user""" | if not check_api_key ( request , key , hproPk ) :
return HttpResponseForbidden
if settings . PIAPI_STANDALONE :
if not settings . PIAPI_REALUSERS :
user = generate_user ( pk = userPk )
if user is None :
return HttpResponseNotFound ( )
else :
user = get_object_or_404 ( DUs... |
def hookable ( cls ) :
"""Initialise hookery in a class that declares hooks by decorating it with this decorator .
This replaces the class with another one which has the same name , but also inherits Hookable
which has HookableMeta set as metaclass so that sub - classes of cls will have hook descriptors
initi... | assert isinstance ( cls , type )
# For classes that won ' t have descriptors initialised by metaclass , need to do it here .
hook_definitions = [ ]
if not issubclass ( cls , Hookable ) :
for k , v in list ( cls . __dict__ . items ( ) ) :
if isinstance ( v , ( ClassHook , InstanceHook ) ) :
delat... |
def read_cluster_status ( hosts , jolokia_port , jolokia_prefix ) :
"""Read and return the number of under replicated partitions and
missing brokers from the specified hosts .
: param hosts : list of brokers ip addresses
: type hosts : list of strings
: param jolokia _ port : HTTP port for Jolokia
: type ... | under_replicated = 0
missing_brokers = 0
for host , request in generate_requests ( hosts , jolokia_port , jolokia_prefix ) :
try :
response = request . result ( )
if 400 <= response . status_code <= 599 :
print ( "Got status code {0}. Exiting." . format ( response . status_code ) )
... |
def build_trie ( pattern_filename , pattern_format , encoding , on_word_boundaries ) :
'''Constructs a finite state machine for performing string rewriting .
Arguments :
- ` pattern _ filename ` :
- ` pattern _ format ` :
- ` encoding ` :
- ` on _ word _ boundaries ` :''' | boundaries = on_word_boundaries
if pattern_format == 'auto' or not on_word_boundaries :
tsv , boundaries = detect_pattern_format ( pattern_filename , encoding , on_word_boundaries )
if pattern_format == 'auto' :
if tsv :
pattern_format = 'tsv'
else :
pattern_format = 'sed'
trie = fsed . ahoc... |
def antenna1 ( self , context ) :
"""antenna1 data source""" | lrow , urow = MS . uvw_row_extents ( context )
antenna1 = self . _manager . ordered_uvw_table . getcol ( MS . ANTENNA1 , startrow = lrow , nrow = urow - lrow )
return antenna1 . reshape ( context . shape ) . astype ( context . dtype ) |
def circle_residual ( params , xedge , yedge ) :
"""Residuals for circle fitting
Parameters
params : lmfit . Parameters
Must contain the keys :
- " cx " : origin of x coordinate [ px ]
- " cy " : origin of y coordinate [ px ]
xedge : 1D np . ndarray
Edge coordinates x [ px ]
yedge : 1D np . ndarray ... | radii = circle_radii ( params , xedge , yedge )
return radii - np . mean ( radii ) |
def get_allowed_domain ( url , allow_subdomains = True ) :
"""Determines the url ' s domain .
: param str url : the url to extract the allowed domain from
: param bool allow _ subdomains : determines wether to include subdomains
: return str : subdomains . domain . topleveldomain or domain . topleveldomain""" | if allow_subdomains :
return re . sub ( re_www , '' , re . search ( r'[^/]+\.[^/]+' , url ) . group ( 0 ) )
else :
return re . search ( re_domain , UrlExtractor . get_allowed_domain ( url ) ) . group ( 0 ) |
def details ( self ) :
"""Copy details from the source profile to the destination profile .""" | return self . dest_user . profile . details . convert_and_update ( self . source_profile . details . as_dict ) |
def validate_version ( self , where = None ) :
"""are we trying to operate on an old version ?""" | if where is not None :
if ( self . version [ 0 ] <= 0 and self . version [ 1 ] <= 10 and self . version [ 2 ] < 1 ) :
ws = incompatibility_doc % '.' . join ( [ str ( x ) for x in self . version ] )
warnings . warn ( ws , IncompatibilityWarning ) |
def get_deletions ( aln_df ) :
"""Get a list of tuples indicating the first and last residues of a deletion region , as well as the length of the deletion .
Examples :
# Deletion of residues 1 to 4 , length 4
> > > test = { ' id _ a ' : { 0 : ' a ' , 1 : ' a ' , 2 : ' a ' , 3 : ' a ' } , ' id _ a _ aa ' : { 0... | deletion_df = aln_df [ aln_df [ 'type' ] == 'deletion' ]
if not deletion_df . empty :
deletion_df [ 'id_a_pos' ] = deletion_df [ 'id_a_pos' ] . astype ( int )
deletions = [ ]
for k , g in groupby ( deletion_df . index , key = lambda n , c = count ( ) : n - next ( c ) ) :
tmp = list ( g )
deletion_indices = ... |
def set_random_starting_grid ( lfe ) :
"""generate a random grid for game of life using a
set of patterns ( just to make it interesting )""" | cls_patterns = mod_grid . GameOfLifePatterns ( 25 )
print ( cls_patterns )
exit ( 0 )
patterns = cls_patterns . get_patterns ( )
for pattern in patterns :
lfe . set_tile ( pattern [ 0 ] , pattern [ 1 ] , 1 ) |
def optional_data_directories ( self ) :
"""Data directories entries are somewhat wierd .
First of all they have no direct type information in it , the type
is assumed from the position inside the table . For this reason
there are often " null " entries , with all fields set to zero .
Here we parse all the ... | base_offset = self . pe_header_offset + COFF_Header . get_size ( ) + OptionalHeader_StandardFields . get_size ( ) + OptionalHeader_WindowsFields . get_size ( )
for i in range ( 0 , self . optional_windows_fields . NumberOfRvaAndSizes ) :
offset = base_offset + i * OptionalHeader_DataDirectory . get_size ( )
hea... |
def _gerritCmd ( self , * args ) :
'''Construct a command as a list of strings suitable for
: func : ` subprocess . call ` .''' | if self . gerrit_identity_file is not None :
options = [ '-i' , self . gerrit_identity_file ]
else :
options = [ ]
return [ 'ssh' ] + options + [ '@' . join ( ( self . gerrit_username , self . gerrit_server ) ) , '-p' , str ( self . gerrit_port ) , 'gerrit' ] + list ( args ) |
def _ProcessUnknownEnums ( message , encoded_message ) :
"""Add unknown enum values from encoded _ message as unknown fields .
ProtoRPC diverges from the usual protocol buffer behavior here and
doesn ' t allow unknown fields . Throwing on unknown fields makes it
impossible to let servers add new enum values a... | if not encoded_message :
return message
decoded_message = json . loads ( six . ensure_str ( encoded_message ) )
for field in message . all_fields ( ) :
if ( isinstance ( field , messages . EnumField ) and field . name in decoded_message and message . get_assigned_value ( field . name ) is None ) :
messa... |
def transform_sources ( self , sources , with_string = False ) :
"""Get the defintions of needed strings and functions
after replacement .""" | modules = { }
updater = partial ( self . replace_source , modules = modules , prefix = 'string_' )
for filename in sources :
updated = update_func_body ( sources [ filename ] , updater )
sources [ filename ] = EXTERN_AND_SEG + updated
logging . debug ( 'modules: %s' , modules )
return sources , self . build_fun... |
def log_to_file ( filename , level = None , fmt = None , datefmt = None ) :
"""Send log output to the given file .
Parameters
filename : str
level : int , optional
An optional logging level that will apply only to this stream
handler .
fmt : str , optional
An optional format string that will be used f... | _add_urbansim_handler ( logging . FileHandler ( filename ) , fmt = fmt , datefmt = datefmt ) |
def abbreviate_sha1 ( cls , sha1 ) :
"""Uniquely abbreviates the given SHA1.""" | # For now we invoke git - rev - parse ( 1 ) , but hopefully eventually
# we will be able to do this via pygit2.
cmd = [ 'git' , 'rev-parse' , '--short' , sha1 ]
# cls . logger . debug ( " " . join ( cmd ) )
out = subprocess . check_output ( cmd , universal_newlines = True ) . strip ( )
# cls . logger . debug ( out )
re... |
def _pandas_interp ( self , data , indices ) :
"""The actual transformation based on the following stackoverflow
entry : http : / / stackoverflow . com / a / 10465162""" | new_index = np . arange ( indices [ - 1 ] + 1 )
data_frame = DataFrame ( data , index = indices )
data_frame_reindexed = data_frame . reindex ( new_index )
data_interpol = data_frame_reindexed . apply ( Series . interpolate )
del new_index
del data_frame
del data_frame_reindexed
return data_interpol |
def extract ( cls , keystr ) :
"""for # { key } returns key""" | regex = r'#{\s*(%s)\s*}' % cls . ALLOWED_KEY
return re . match ( regex , keystr ) . group ( 1 ) |
def get_event_attendee ( self , id , attendee_id , ** data ) :
"""GET / events / : id / attendees / : attendee _ id /
Returns a single : format : ` attendee ` by ID , as the key ` ` attendee ` ` .""" | return self . get ( "/events/{0}/attendees/{0}/" . format ( id , attendee_id ) , data = data ) |
def _hn2db ( self , hn ) :
'''This will add a hostname for a hostname for an included domain or return an existing entry''' | db = self . hn_db
hn_found = False
for k , v in db . items ( ) :
if v == hn : # the hostname is in the database
ret_hn = k
hn_found = True
if hn_found :
return ret_hn
else :
self . hostname_count += 1
# we have a new hostname , so we increment the counter to get the host ID number
o_... |
def percentAt ( self , value ) :
"""Returns the percentage the value represents between the minimum and
maximum for this axis .
: param value | < int > | | < float >
: return < float >""" | min_val = self . minimum ( )
max_val = self . maximum ( )
if value < min_val :
return 0.0
elif max_val < value :
return 1.0
# round the max value to sync with the values in the grid
max_val = self . rounded ( max_val )
try :
perc = ( value - min_val ) / float ( max_val - min_val )
except ( TypeError , ZeroD... |
def handler_context ( self , type_ , from_ , cb , * , wildcard_resource = True ) :
"""Context manager which temporarily registers a callback .
The arguments are the same as for : meth : ` register _ callback ` .
When the context is entered , the callback ` cb ` is registered . When the
context is exited , no ... | self . register_callback ( type_ , from_ , cb , wildcard_resource = wildcard_resource )
try :
yield
finally :
self . unregister_callback ( type_ , from_ , wildcard_resource = wildcard_resource ) |
def add_iri_thermal_plasma ( inst , glat_label = 'glat' , glong_label = 'glong' , alt_label = 'alt' ) :
"""Uses IRI ( International Reference Ionosphere ) model to simulate an ionosphere .
Uses pyglow module to run IRI . Configured to use actual solar parameters to run
model .
Example
# function added velow... | import pyglow
from pyglow . pyglow import Point
iri_params = [ ]
# print ' IRI Simulations '
for time , lat , lon , alt in zip ( inst . data . index , inst [ glat_label ] , inst [ glong_label ] , inst [ alt_label ] ) : # Point class is instantiated . Its parameters are a function of time and spatial location
pt = P... |
def _to_io_meta ( shape_meta , valid_keys , key_mappings ) :
"""This is used to make meta data compatible with a specific io
by filtering and mapping to it ' s valid keys
Parameters
shape _ meta : dict
meta attribute of a ` regions . Region ` object
valid _ keys : python list
Contains all the valid keys... | meta = dict ( )
for key in shape_meta :
if key in valid_keys :
meta [ key_mappings . get ( key , key ) ] = shape_meta [ key ]
return meta |
def get_network_events ( self ) :
""": calls : ` GET / networks / : owner / : repo / events < http : / / developer . github . com / v3 / activity / events > ` _
: rtype : : class : ` github . PaginatedList . PaginatedList ` of : class : ` github . Event . Event `""" | return github . PaginatedList . PaginatedList ( github . Event . Event , self . _requester , "/networks/" + self . owner . login + "/" + self . name + "/events" , None ) |
def leave_swarm ( self , force = False ) :
"""Leave a swarm .
Args :
force ( bool ) : Leave the swarm even if this node is a manager .
Default : ` ` False ` `
Returns :
` ` True ` ` if the request went through .
Raises :
: py : class : ` docker . errors . APIError `
If the server returns an error ."... | url = self . _url ( '/swarm/leave' )
response = self . _post ( url , params = { 'force' : force } )
# Ignore " this node is not part of a swarm " error
if force and response . status_code == http_client . NOT_ACCEPTABLE :
return True
# FIXME : Temporary workaround for 1.13.0 - rc bug
# https : / / github . com / do... |
def new_orthogonal_center ( X , data_norms , centroids , center_norms = None ) :
"""Initialize the centrodis by orthogonal _ initialization .
Parameters
X ( data ) : array - like , shape = ( m _ samples , n _ samples )
data _ norms : array - like , shape = ( 1 , n _ samples )
center _ norms : array - like ,... | if center_norms is None :
center_norms = np . linalg . norm ( centroids , axis = 1 )
cosine = np . inner ( X , centroids )
# cosine [ i , j ] = np . dot ( X [ i , : ] , centroids [ j , : ] )
cosine = cosine / center_norms
# divide each column by the center norm
cosine = cosine / data_norms [ : , np . newaxis ]
# di... |
def load_cash_balances_with_children ( self , root_account_fullname : str ) :
"""loads data for cash balances""" | assert isinstance ( root_account_fullname , str )
svc = AccountsAggregate ( self . book )
root_account = svc . get_by_fullname ( root_account_fullname )
if not root_account :
raise ValueError ( "Account not found" , root_account_fullname )
accounts = self . __get_all_child_accounts_as_array ( root_account )
# read ... |
def get_filter ( filetypes , ext ) :
"""Return filter associated to file extension""" | if not ext :
return ALL_FILTER
for title , ftypes in filetypes :
if ext in ftypes :
return _create_filter ( title , ftypes )
else :
return '' |
def Then2 ( self , f , arg1 , * args , ** kwargs ) :
"""` Then2 ( f , . . . ) ` is equivalent to ` ThenAt ( 2 , f , . . . ) ` . Checkout ` phi . builder . Builder . ThenAt ` for more information .""" | args = ( arg1 , ) + args
return self . ThenAt ( 2 , f , * args , ** kwargs ) |
def _urlendecode ( url , func ) :
"""Encode or decode ` ` url ` ` by applying ` ` func ` ` to all of its
URL - encodable parts .""" | parsed = urlparse ( url )
for attr in URL_ENCODABLE_PARTS :
parsed = parsed . _replace ( ** { attr : func ( getattr ( parsed , attr ) ) } )
return urlunparse ( parsed ) |
def delete_tag ( self , tag_id ) :
"""Deletes a Tag to current object
: param tag _ id : the id of the tag which should be deleted
: type tag _ id : int
: rtype : None""" | from highton . models . tag import Tag
self . _delete_request ( endpoint = self . ENDPOINT + '/' + str ( self . id ) + '/' + Tag . ENDPOINT + '/' + str ( tag_id ) , ) |
def _resolve_username ( self , account , username ) :
"""Resolve username and handle deprecation of account kwarg""" | if account is not None :
warnings . warn ( "Use keyword argument 'username' instead of 'account'" , DeprecationWarning )
return username or account or self . username |
def _killBackref ( receiver , senderkey ) :
"""Do the actual removal of back reference from receiver to senderkey""" | receiverkey = id ( receiver )
set = sendersBack . get ( receiverkey , ( ) )
while senderkey in set :
try :
set . remove ( senderkey )
except :
break
if not set :
try :
del sendersBack [ receiverkey ]
except KeyError :
pass
return True |
def find_python ( ) :
"""Search for Python automatically""" | python = ( _state . get ( "pythonExecutable" ) or # Support for multiple executables .
next ( ( exe for exe in os . getenv ( "PYBLISH_QML_PYTHON_EXECUTABLE" , "" ) . split ( os . pathsep ) if os . path . isfile ( exe ) ) , None ) or # Search PATH for executables .
which ( "python" ) or which ( "python3" ) )
if not pyth... |
def assign_activity_to_objective_bank ( self , activity_id , objective_bank_id ) :
"""Adds an existing ` ` Activity ` ` to a ` ` ObjectiveBank ` ` .
arg : activity _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` Activity ` `
arg : objective _ bank _ id ( osid . id . Id ) : the ` ` Id ` ` of the
` ` Object... | # Implemented from template for
# osid . resource . ResourceBinAssignmentSession . assign _ resource _ to _ bin
mgr = self . _get_provider_manager ( 'LEARNING' , local = True )
lookup_session = mgr . get_objective_bank_lookup_session ( proxy = self . _proxy )
lookup_session . get_objective_bank ( objective_bank_id )
# ... |
def upload_rotate ( file_path , s3_bucket , s3_key_prefix , aws_key = None , aws_secret = None ) :
'''Upload file _ path to s3 bucket with prefix
Ex . upload _ rotate ( ' / tmp / file - 2015-01-01 . tar . bz2 ' , ' backups ' , ' foo . net / ' )
would upload file to bucket backups with key = foo . net / file - 2... | key = '' . join ( [ s3_key_prefix , os . path . basename ( file_path ) ] )
logger . debug ( "Uploading {0} to {1}" . format ( file_path , key ) )
upload ( file_path , s3_bucket , key , aws_access_key_id = aws_key , aws_secret_access_key = aws_secret )
file_root , file_ext = splitext ( os . path . basename ( file_path )... |
def _onLeftButtonDown ( self , evt ) :
"""Start measuring on an axis .""" | x = evt . GetX ( )
y = self . figure . bbox . height - evt . GetY ( )
evt . Skip ( )
self . CaptureMouse ( )
FigureCanvasBase . button_press_event ( self , x , y , 1 , guiEvent = evt ) |
def url_to_dir_parts ( url , include_protocol = False , include_hostname = False , alt_char = False ) :
'''Return a list of directory parts from a URL .
Args :
url ( str ) : The URL .
include _ protocol ( bool ) : If True , the scheme from the URL will be
included .
include _ hostname ( bool ) : If True ,... | assert isinstance ( url , str ) , 'Expect str. Got {}.' . format ( type ( url ) )
url_split_result = urllib . parse . urlsplit ( url )
parts = [ ]
if include_protocol :
parts . append ( url_split_result . scheme )
if include_hostname :
hostname = url_split_result . hostname
if url_split_result . port :
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.