signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def analysis ( analysis_id ) :
"""Display a single analysis .""" | analysis_obj = store . analysis ( analysis_id )
if analysis_obj is None :
return abort ( 404 )
if request . method == 'PUT' :
analysis_obj . update ( request . json )
store . commit ( )
data = analysis_obj . to_dict ( )
data [ 'failed_jobs' ] = [ job_obj . to_dict ( ) for job_obj in analysis_obj . failed_jo... |
def _Execute ( self , http ) :
"""Serialize batch request , send to server , process response .
Args :
http : A httplib2 . Http object to be used to make the request with .
Raises :
httplib2 . HttpLib2Error if a transport error has occured .
apiclient . errors . BatchError if the response is the wrong for... | message = mime_multipart . MIMEMultipart ( 'mixed' )
# Message should not write out its own headers .
setattr ( message , '_write_headers' , lambda self : None )
# Add all the individual requests .
for key in self . __request_response_handlers :
msg = mime_nonmultipart . MIMENonMultipart ( 'application' , 'http' )
... |
def _launch_remote ( self , host , config_port , race , name , interface ) :
"""Make sure this stays synced with bin / play _ vs _ agent . py .""" | self . _tcp_conn , settings = tcp_client ( Addr ( host , config_port ) )
self . _map_name = settings [ "map_name" ]
if settings [ "remote" ] :
self . _udp_sock = udp_server ( Addr ( host , settings [ "ports" ] [ "server" ] [ "game" ] ) )
daemon_thread ( tcp_to_udp , ( self . _tcp_conn , self . _udp_sock , Addr ... |
def save ( self ) :
"""save data into DB :
1 . save new ( missing ) data
2 . update only when needed
3 . delete old data
4 . generate report that will be printed
constraints :
* ensure new nodes do not take a name / slug which is already used
* validate through django before saving
* use good defaul... | self . key_mapping ( )
# retrieve all items
items = self . parsed_data
# init empty lists
added_nodes = [ ]
changed_nodes = [ ]
unmodified_nodes = [ ]
# retrieve a list of all the slugs of this layer
layer_nodes_slug_list = Node . objects . filter ( layer = self . layer ) . values_list ( 'slug' , flat = True )
# keep a... |
def parse ( self , element ) :
r"""Parse xml element .
: param element : an : class : ` ~ xml . etree . ElementTree . Element ` instance
: rtype : dict""" | values = { }
for child in element :
node = self . get_node ( child )
subs = self . parse ( child )
value = subs or node [ 'value' ]
if node [ 'tag' ] not in values :
values [ node [ 'tag' ] ] = value
else :
if not isinstance ( values [ node [ 'tag' ] ] , list ) :
values [... |
def search_regexp ( self , regexp , flags = 0 , minAddr = None , maxAddr = None , bufferPages = - 1 ) :
"""Search for the given regular expression within the process memory .
@ type regexp : str
@ param regexp : Regular expression string .
@ type flags : int
@ param flags : Regular expression flags .
@ ty... | pattern = RegExpPattern ( regexp , flags )
return Search . search_process ( self , pattern , minAddr , maxAddr , bufferPages ) |
def export ( self , ** kwargs ) :
"""Generate audio file from composition .
: param str . filename : Output filename ( no extension )
: param str . filetype : Output file type ( only . wav supported for now )
: param integer samplerate : Sample rate of output audio
: param integer channels : Channels in out... | # get optional args
filename = kwargs . pop ( 'filename' , 'out' )
filetype = kwargs . pop ( 'filetype' , 'wav' )
adjust_dynamics = kwargs . pop ( 'adjust_dynamics' , False )
samplerate = kwargs . pop ( 'samplerate' , None )
channels = kwargs . pop ( 'channels' , self . channels )
separate_tracks = kwargs . pop ( 'sepa... |
def _indent ( s_ , numSpaces ) :
"""Indent string""" | s = s_ . split ( '\n' )
if len ( s ) == 1 :
return s_
first = s . pop ( 0 )
s = [ first ] + [ ( numSpaces * ' ' ) + line for line in s ]
s = '\n' . join ( s )
return s |
def buildASNList ( rootnames , asnname , check_for_duplicates = True ) :
"""Return the list of filenames for a given set of rootnames""" | # Recognize when multiple valid inputs with the same rootname are present
# this would happen when both CTE - corrected ( _ flc ) and non - CTE - corrected ( _ flt )
# products are in the same directory as an ASN table
filelist , duplicates = checkForDuplicateInputs ( rootnames )
if check_for_duplicates and duplicates ... |
def read_sheets ( archive ) :
"""Read worksheet titles and ids for a workbook""" | xml_source = archive . read ( ARC_WORKBOOK )
tree = fromstring ( xml_source )
for element in safe_iterator ( tree , '{%s}sheet' % SHEET_MAIN_NS ) :
attrib = element . attrib
attrib [ 'id' ] = attrib [ "{%s}id" % REL_NS ]
del attrib [ "{%s}id" % REL_NS ]
if attrib [ 'id' ] :
yield attrib |
def setsudo ( self , user = None ) :
"""Set the subsequent API calls to the user provided
: param user : User id or username to change to , None to return to the logged user
: return : Nothing""" | if user is None :
try :
self . headers . pop ( 'SUDO' )
except KeyError :
pass
else :
self . headers [ 'SUDO' ] = user |
def images ( ) :
'''Show the list of registered images in this cluster .''' | fields = [ ( 'Name' , 'name' ) , ( 'Registry' , 'registry' ) , ( 'Tag' , 'tag' ) , ( 'Digest' , 'digest' ) , ( 'Size' , 'size_bytes' ) , ( 'Aliases' , 'aliases' ) , ]
with Session ( ) as session :
try :
items = session . Image . list ( fields = ( item [ 1 ] for item in fields ) )
except Exception as e :... |
def main ( ) :
"""Generates code for name _ to _ rgb dict , assuming an rgb . txt file available ( in X11 format ) .""" | import re
with open ( 'rgb.txt' ) as fp :
line = fp . readline ( )
while line :
reg = re . match ( r'\s*(\d+)\s*(\d+)\s*(\d+)\s*(\w.*\w).*' , line )
if reg :
r = int ( reg . group ( 1 ) ) / 255.
g = int ( reg . group ( 2 ) ) / 255.
b = int ( reg . group ( 3 ) ... |
def _multiline_width ( multiline_s , line_width_fn = len ) :
"""Visible width of a potentially multiline content .""" | return max ( map ( line_width_fn , re . split ( "[\r\n]" , multiline_s ) ) ) |
def interfaces ( root ) :
'''Generate a dictionary with all available interfaces relative to root .
Symlinks are not followed .
CLI example :
. . code - block : : bash
salt ' * ' sysfs . interfaces block / bcache0 / bcache
Output example :
. . code - block : : json
" state " ,
" partial _ stripes _ ... | root = target ( root )
if root is False or not os . path . isdir ( root ) :
log . error ( 'SysFS %s not a dir' , root )
return False
readwrites = [ ]
reads = [ ]
writes = [ ]
for path , _ , files in salt . utils . path . os_walk ( root , followlinks = False ) :
for afile in files :
canpath = os . pa... |
def accel_fl ( q : np . ndarray ) :
"""Accelaration in the earth - sun system using Fluxion potential energy""" | # Infer number of dimensions from q
dims : int = len ( q )
# Number of celestial bodies
B : int = dims // 3
# The force given the positions q of the bodies
f = force ( q )
# The accelerations from this force
a = np . zeros ( dims )
for i in range ( B ) :
a [ slices [ i ] ] = f [ slices [ i ] ] / mass [ i ]
return a |
def get_full_text ( tweet ) :
"""Get the full text of a tweet dict .
Includes @ - mention replies and long links .
Args :
tweet ( Tweet or dict ) : A Tweet object or dictionary
Returns :
str : the untruncated text of a Tweet
( finds extended text if available )
Example :
> > > from tweet _ parser . ... | if is_original_format ( tweet ) :
if tweet [ "truncated" ] :
return tweet [ "extended_tweet" ] [ "full_text" ]
else :
return tweet [ "text" ]
else :
if "long_object" in tweet :
return tweet [ "long_object" ] [ "body" ]
else :
return tweet [ "body" ] |
def Push ( cls , connection , datafile , filename , st_mode = DEFAULT_PUSH_MODE , mtime = 0 , progress_callback = None ) :
"""Push a file - like object to the device .
Args :
connection : ADB connection
datafile : File - like object for reading from
filename : Filename to push to
st _ mode : stat mode for... | fileinfo = ( '{},{}' . format ( filename , int ( st_mode ) ) ) . encode ( 'utf-8' )
cnxn = FileSyncConnection ( connection , b'<2I' )
cnxn . Send ( b'SEND' , fileinfo )
if progress_callback :
total_bytes = os . fstat ( datafile . fileno ( ) ) . st_size if isinstance ( datafile , file ) else - 1
progress = cls .... |
def restore ( self , filename ) :
"""Restore object from mat - file . TODO : determine format specification""" | matfile = loadmat ( filename )
if matfile [ 'dim' ] == 1 :
matfile [ 'solution' ] = matfile [ 'solution' ] [ 0 , : ]
self . elapsed_time = matfile [ 'elapsed_time' ] [ 0 , 0 ]
self . solution = matfile [ 'solution' ]
return self |
def read_out ( self , block_address ) :
"""Prints sector / block number and contents of block . Tag and auth must be set - does auth .""" | if not self . is_tag_set_auth ( ) :
return True
error = self . do_auth ( block_address )
if not error :
( error , data ) = self . rfid . read ( block_address )
print ( self . sector_string ( block_address ) + ": " + str ( data ) )
else :
print ( "Error on " + self . sector_string ( block_address ) ) |
def makeChromID ( chrom , reference = None , prefix = None ) :
"""This will take a chromosome number and a NCBI taxon number ,
and create a unique identifier for the chromosome . These identifiers
are made in the @ base space like :
Homo sapiens ( 9606 ) chr1 = = > : 9606chr1
Mus musculus ( 10090 ) chrX = =... | # blank nodes
if reference is None :
LOG . warning ( 'No reference for this chr. You may have conflicting ids' )
# replace any chr - like prefixes with blank to standardize
chrid = re . sub ( r'ch(r?)[omse]*' , '' , str ( chrom ) )
# remove the build / taxon prefixes to look cleaner
ref = reference
if re . match ( ... |
def rl_loop ( ) :
"""The main reinforcement learning ( RL ) loop .""" | state = State ( )
if FLAGS . checkpoint_dir : # Start from a partially trained model .
initialize_from_checkpoint ( state )
else : # Play the first round of selfplay games with a fake model that returns
# random noise . We do this instead of playing multiple games using a single
# model bootstrapped with random noi... |
def validate_attr_dict ( self , attr_dict : Dict [ str , str ] ) -> None :
"""Validates that ContractType keys in attr _ dict reference existing manifest ContractTypes .""" | attr_dict_names = list ( attr_dict . keys ( ) )
if not self . unlinked_references and not self . linked_references :
raise BytecodeLinkingError ( "Unable to validate attr dict, this contract has no linked/unlinked references." )
unlinked_refs = self . unlinked_references or ( { } , )
linked_refs = self . linked_ref... |
def monkey_patch ( enabled = True ) :
"""Monkey patching PIL . Image . open method
Args :
enabled ( bool ) : If the monkey patch should be activated or deactivated .""" | if enabled :
Image . open = imdirect_open
else :
Image . open = pil_open |
def dump ( self ) :
'''This returns a copy of the screen as a unicode string . This is similar to
_ _ str _ _ / _ _ unicode _ _ except that lines are not terminated with line
feeds .''' | return u'' . join ( [ u'' . join ( c ) for c in self . w ] ) |
def DXHTTPRequest ( resource , data , method = 'POST' , headers = None , auth = True , timeout = DEFAULT_TIMEOUT , use_compression = None , jsonify_data = True , want_full_response = False , decode_response_body = True , prepend_srv = True , session_handler = None , max_retries = DEFAULT_RETRIES , always_retry = False ... | if headers is None :
headers = { }
global _UPGRADE_NOTIFY
seq_num = _get_sequence_number ( )
url = APISERVER + resource if prepend_srv else resource
method = method . upper ( )
# Convert method name to uppercase , to ease string comparisons later
if auth is True :
auth = AUTH_HELPER
if auth :
auth ( _Reques... |
def send ( self , messages = None , api_key = None , secure = None , test = None , ** request_args ) :
'''Send batch request to Postmark API .
Returns result of : func : ` requests . post ` .
: param messages : Batch messages to send to the Postmark API .
: type messages : A list of : class : ` Message `
: ... | return super ( BatchSender , self ) . send ( message = messages , test = test , api_key = api_key , secure = secure , ** request_args ) |
def get_default_config ( self ) :
"""Returns the default collector settings""" | config = super ( LoadAverageCollector , self ) . get_default_config ( )
config . update ( { 'path' : 'loadavg' , 'simple' : 'False' } )
return config |
def _read_http_window_update ( self , size , kind , flag ) :
"""Read HTTP / 2 WINDOW _ UPDATE frames .
Structure of HTTP / 2 WINDOW _ UPDATE frame [ RFC 7540 ] :
| Length ( 24 ) |
| Type ( 8 ) | Flags ( 8 ) |
| R | Stream Identifier ( 31 ) |
| R | Window Size Increment ( 31 ) |
Octets Bits Name Descript... | if size != 4 :
raise ProtocolError ( f'HTTP/2: [Type {kind}] invalid format' , quiet = True )
if any ( ( int ( bit , base = 2 ) for bit in flag ) ) :
raise ProtocolError ( f'HTTP/2: [Type {kind}] invalid format' , quiet = True )
_size = self . _read_binary ( 4 )
if int ( _size [ 0 ] , base = 2 ) :
raise Pro... |
def list ( self , query_criteria = None , order_criteria = None ) :
'''a generator method to list records in table which match query criteria
: param query _ criteria : dictionary with schema dot - path field names and query qualifiers
: param order _ criteria : list of single keypair dictionaries with field na... | title = '%s.list' % self . __class__ . __name__
from sqlalchemy import desc as order_desc
# validate inputs
if query_criteria :
self . model . query ( query_criteria )
else :
query_criteria = { }
if order_criteria :
object_title = '%s(%s=%s)' % ( title , 'order_criteria' , str ( order_criteria ) )
self ... |
def find_usage ( self , service = None , use_ta = True ) :
"""For each limit in the specified service ( or all services if
` ` service ` ` is ` ` None ` ` ) , query the AWS API via ` ` boto3 ` `
and find the current usage amounts for that limit .
This method updates the ` ` current _ usage ` ` attribute of th... | to_get = self . services
if service is not None :
to_get = dict ( ( each , self . services [ each ] ) for each in service )
if use_ta :
self . ta . update_limits ( )
for cls in to_get . values ( ) :
if hasattr ( cls , '_update_limits_from_api' ) :
cls . _update_limits_from_api ( )
logger . debug... |
def create_from_hash ( hash , ezo ) :
'''given the hash of a contract , returns a contract from the data store
: param hash : ( string ) hash of the contract source code
: param ezo : ezo instance
: return : contract instance , error''' | cp , err = ezo . db . get ( "contracts" , hash )
if err :
return None , err
# create a new Contract
c = Contract ( cp [ "name" ] , ezo )
c . abi = cp [ "abi" ]
c . bin = cp [ "bin" ]
c . hash = cp [ "hash" ]
c . source = cp [ "source" ]
c . timestamp = cp [ "timestamp" ]
c . te_map = cp [ 'te-map' ]
return c , None |
def get_my_account_info ( self , ** kwargs ) : # noqa : E501
"""Get account info . # noqa : E501
Returns detailed information about the account . * * Example usage : * * ` curl https : / / api . us - east - 1 . mbedcloud . com / v3 / accounts / me ? include = policies - H ' Authorization : Bearer API _ KEY ' ` . ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'asynchronous' ) :
return self . get_my_account_info_with_http_info ( ** kwargs )
# noqa : E501
else :
( data ) = self . get_my_account_info_with_http_info ( ** kwargs )
# noqa : E501
return data |
def available_metadata ( self ) :
"""List all scenario metadata indicators available in the connected
data source""" | url = self . base_url + 'metadata/types'
headers = { 'Authorization' : 'Bearer {}' . format ( self . auth ( ) ) }
r = requests . get ( url , headers = headers )
return pd . read_json ( r . content , orient = 'records' ) [ 'name' ] |
def address ( self ) -> str :
"""Generate a random full address .
: return : Full address .""" | fmt = self . _data [ 'address_fmt' ]
st_num = self . street_number ( )
st_name = self . street_name ( )
if self . locale in SHORTENED_ADDRESS_FMT :
return fmt . format ( st_num = st_num , st_name = st_name , )
if self . locale == 'ja' :
return fmt . format ( self . random . choice ( self . _data [ 'city' ] ) , ... |
def send ( device_id , description , ** kwargs ) :
"""Site : http : / / parse . com
API : https : / / www . parse . com / docs / push _ guide # scheduled / REST
Desc : Best app for system administrators""" | headers = { "X-Parse-Application-Id" : settings . PARSE_APP_ID , "X-Parse-REST-API-Key" : settings . PARSE_API_KEY , "User-Agent" : "DBMail/%s" % get_version ( ) , "Content-type" : "application/json" , }
data = { "where" : { "user_id" : device_id , } , "data" : { "alert" : description , "title" : kwargs . pop ( "event"... |
def intialize ( self ) :
"""initialize the serial port with baudrate , timeout parameters""" | print '%s call intialize' % self . port
try : # init serial port
self . deviceConnected = False
self . _connect ( )
if self . deviceConnected :
self . UIStatusMsg = self . getVersionNumber ( )
if self . firmwarePrefix not in self . UIStatusMsg :
self . deviceConnected = False
... |
def connect_entry_signals ( ) :
"""Connect all the signals on Entry model .""" | post_save . connect ( ping_directories_handler , sender = Entry , dispatch_uid = ENTRY_PS_PING_DIRECTORIES )
post_save . connect ( ping_external_urls_handler , sender = Entry , dispatch_uid = ENTRY_PS_PING_EXTERNAL_URLS )
post_save . connect ( flush_similar_cache_handler , sender = Entry , dispatch_uid = ENTRY_PS_FLUSH... |
def start ( self , tcpport = 102 ) :
"""start the server .""" | if tcpport != 102 :
logger . info ( "setting server TCP port to %s" % tcpport )
self . set_param ( snap7 . snap7types . LocalPort , tcpport )
logger . info ( "starting server on 0.0.0.0:%s" % tcpport )
return self . library . Srv_Start ( self . pointer ) |
def get_asset_ids ( self ) :
"""Gets the Ids of any assets associated with this activity .
return : ( osid . id . IdList ) - list of asset Ids
raise : IllegalState - is _ asset _ based _ activity ( ) is false
compliance : mandatory - This method must be implemented .""" | if not self . is_asset_based_activity ( ) :
raise IllegalState ( )
else :
ids = [ ]
for i in self . _my_map [ 'assetIds' ] :
ids . append ( Id ( i ) )
return IdList ( ids ) |
def get_base_route ( cls ) :
"""Returns the route base to use for the current class .""" | base_route = cls . __name__ . lower ( )
if cls . base_route is not None :
base_route = cls . base_route
base_rule = parse_rule ( base_route )
cls . base_args = [ r [ 2 ] for r in base_rule ]
return base_route . strip ( "/" ) |
def _binary_op ( cls , x : 'TensorFluent' , y : 'TensorFluent' , op : Callable [ [ tf . Tensor , tf . Tensor ] , tf . Tensor ] , dtype : tf . DType ) -> 'TensorFluent' :
'''Returns a TensorFluent for the binary ` op ` applied to fluents ` x ` and ` y ` .
Args :
x : The first operand .
y : The second operand .... | # scope
s1 = x . scope . as_list ( )
s2 = y . scope . as_list ( )
scope , perm1 , perm2 = TensorFluentScope . broadcast ( s1 , s2 )
if x . batch and perm1 != [ ] :
perm1 = [ 0 ] + [ p + 1 for p in perm1 ]
if y . batch and perm2 != [ ] :
perm2 = [ 0 ] + [ p + 1 for p in perm2 ]
x = x . transpose ( perm1 )
y = y ... |
def compute_plot_size ( plot ) :
"""Computes the size of bokeh models that make up a layout such as
figures , rows , columns , widgetboxes and Plot .""" | if isinstance ( plot , GridBox ) :
ndmapping = NdMapping ( { ( x , y ) : fig for fig , y , x in plot . children } , kdims = [ 'x' , 'y' ] )
cols = ndmapping . groupby ( 'x' )
rows = ndmapping . groupby ( 'y' )
width = sum ( [ max ( [ compute_plot_size ( f ) [ 0 ] for f in col ] ) for col in cols ] )
... |
def from_str ( cls : Type [ CRCPubkeyType ] , crc_pubkey : str ) -> CRCPubkeyType :
"""Return CRCPubkey instance from CRC public key string
: param crc _ pubkey : CRC public key
: return :""" | data = CRCPubkey . re_crc_pubkey . match ( crc_pubkey )
if data is None :
raise Exception ( "Could not parse CRC public key {0}" . format ( crc_pubkey ) )
pubkey = data . group ( 1 )
crc = data . group ( 2 )
return cls ( pubkey , crc ) |
async def update_state ( self , name , state ) :
"""Update the state for a service .
Args :
name ( string ) : The name of the service
state ( int ) : The new state of the service""" | await self . send_command ( OPERATIONS . CMD_UPDATE_STATE , { 'name' : name , 'new_status' : state } , MESSAGES . UpdateStateResponse , timeout = 5.0 ) |
def update ( context , id , export_control , active ) :
"""update ( context , id , export _ control , active )
Update a component
> > > dcictl component - update [ OPTIONS ]
: param string id : ID of the component [ required ]
: param boolean export - control : Set the component visible for users
: param ... | component_info = component . get ( context , id = id )
etag = component_info . json ( ) [ 'component' ] [ 'etag' ]
result = component . update ( context , id = id , etag = etag , export_control = export_control , state = utils . active_string ( active ) )
utils . format_output ( result , context . format ) |
def rows ( self ) :
"""Return the list of object on the active page .""" | return map ( lambda o : self . _meta . row_class ( self , o ) , self . paginator . page ( self . _meta . page ) . object_list ) |
def _process_omia_omim_map ( self , row ) :
"""Links OMIA groups to OMIM equivalents .
: param row :
: return :""" | # omia _ id , omim _ id , added _ by
model = Model ( self . graph )
omia_id = 'OMIA:' + row [ 'omia_id' ]
omim_id = 'OMIM:' + row [ 'omim_id' ]
# also store this for use when we say that a given animal is
# a model of a disease
if omia_id not in self . omia_omim_map :
self . omia_omim_map [ omia_id ] = set ( )
self... |
def transformFromNative ( obj ) :
"""Replace the date , datetime or period tuples in obj . value with
appropriate strings .""" | if obj . value and type ( obj . value [ 0 ] ) == datetime . date :
obj . isNative = False
obj . value_param = 'DATE'
obj . value = ',' . join ( [ dateToString ( val ) for val in obj . value ] )
return obj
# Fixme : handle PERIOD case
else :
if obj . isNative :
obj . isNative = False
... |
def view_label_matrix ( L , colorbar = True ) :
"""Display an [ n , m ] matrix of labels""" | L = L . todense ( ) if sparse . issparse ( L ) else L
plt . imshow ( L , aspect = "auto" )
plt . title ( "Label Matrix" )
if colorbar :
labels = sorted ( np . unique ( np . asarray ( L ) . reshape ( - 1 , 1 ) . squeeze ( ) ) )
boundaries = np . array ( labels + [ max ( labels ) + 1 ] ) - 0.5
plt . colorbar ... |
def site_url ( self , url ) :
"""URL setter and validator for site _ url property .
Parameters :
url ( str ) : URL of on Moebooru / Danbooru based sites .
Raises :
PybooruError : When URL scheme or URL are invalid .""" | # Regular expression to URL validate
regex = re . compile ( r'^(?:http|https)://' # Scheme only HTTP / HTTPS
r' ( ? : ( ? : [ A - Z0 - 9 ] ( ? : [ A - Z0 - 9 - ] { 0 , 61 } [ A - Z0 - 9 ] ) ?\ . ) + ( ? : [ A - Z ] { 2 , 6 } .? | [ A - Z0 - 9 - ] { 2 , } ( ? < ! - ) .? ) | ' # Domain
r' localhost | ' # lo... |
def get_user_info ( self , request ) :
"""Requires Flask - Login ( https : / / pypi . python . org / pypi / Flask - Login / )
to be installed and setup .""" | user_info = { }
try :
ip_address = request . access_route [ 0 ]
except IndexError :
ip_address = request . remote_addr
if ip_address :
user_info [ 'ip_address' ] = ip_address
if not has_flask_login :
return user_info
if not hasattr ( current_app , 'login_manager' ) :
return user_info
try :
is_au... |
def _do_query ( self , query , iph , eth , in_port , msg ) :
"""the process when the snooper received a QUERY message .""" | datapath = msg . datapath
dpid = datapath . id
ofproto = datapath . ofproto
parser = datapath . ofproto_parser
# learn the querier .
self . _to_querier [ dpid ] = { 'port' : in_port , 'ip' : iph . src , 'mac' : eth . src }
# set the timeout time .
timeout = igmp . QUERY_RESPONSE_INTERVAL
if query . maxresp :
timeou... |
def centerOnAnimated ( self , centerOn , animate = 0 ) :
"""Animates the centering options over a given number of seconds .
: param centerOn | < QRectF > | < QPointF > | < XNode >
animate | < float > | seconds""" | if isinstance ( centerOn , XNode ) :
center = centerOn . sceneRect ( ) . center ( )
elif isinstance ( centerOn , QRectF ) :
center = centerOn . center ( )
elif isinstance ( centerOn , QPointF ) :
center = centerOn
else :
return
anim = XObjectAnimation ( self , 'centerOn' , self )
anim . setStartValue ( ... |
def lookup ( var_name , contexts = ( ) , start = 0 ) :
"""lookup the value of the var _ name on the stack of contexts
: var _ name : TODO
: contexts : TODO
: returns : None if not found""" | start = len ( contexts ) if start >= 0 else start
for context in reversed ( contexts [ : start ] ) :
try :
if var_name in context :
return context [ var_name ]
except TypeError as te : # we may put variable on the context , skip it
continue
return None |
def Import ( context , request ) :
"""Read Dimensional - CSV analysis results""" | form = request . form
# TODO form [ ' file ' ] sometimes returns a list
infile = form [ 'instrument_results_file' ] [ 0 ] if isinstance ( form [ 'instrument_results_file' ] , list ) else form [ 'instrument_results_file' ]
artoapply = form [ 'artoapply' ]
override = form [ 'results_override' ]
instrument = form . get ( ... |
def get_local_variable_from_name ( self , variable_name ) :
"""Return a local variable from a name
Args :
varible _ name ( str ) : name of the variable
Returns :
LocalVariable""" | return next ( ( v for v in self . variables if v . name == variable_name ) , None ) |
def debug_print ( self ) :
'''Print tree''' | def print_node ( node , depth = 0 ) :
print ( '{}{}' . format ( ' ' * depth , repr ( node ) ) )
if node . is_container ( ) :
for child in node . children :
print_node ( child , depth + 1 )
for root in self . stack :
print_node ( root ) |
def by_name ( self , region , summoner_name ) :
"""Get a summoner by summoner name
: param string region : The region to execute this request on
: param string summoner _ name : Summoner Name
: returns : SummonerDTO : represents a summoner""" | url , query = SummonerApiV4Urls . by_name ( region = region , summoner_name = summoner_name )
return self . _raw_request ( self . by_name . __name__ , region , url , query ) |
def ght ( img , template ) :
r"""Implementation of the general hough transform for all dimensions .
Providing a template , this method searches in the image for structures similar to the
one depicted by the template . The returned hough image denotes how well the structure
fit in each index .
The indices of... | # cast template to bool and img to numpy array
img = numpy . asarray ( img )
template = numpy . asarray ( template ) . astype ( numpy . bool )
# check supplied parameters
if img . ndim != template . ndim :
raise AttributeError ( 'The supplied image and template must be of the same dimensionality.' )
if not numpy . ... |
def _identifySuperGraph ( self ) :
"""A helper function for determining the condensed
representation of the tree . That is , one that does not hold
all of the internal nodes of the graph . The results will be
stored in ContourTree . superNodes and ContourTree . superArcs .
These two can be used to potential... | if self . debug :
sys . stdout . write ( "Condensing Graph: " )
start = time . clock ( )
G = nx . DiGraph ( )
G . add_edges_from ( self . edges )
if self . short_circuit :
self . superNodes = G . nodes ( )
self . superArcs = G . edges ( )
# There should be a way to populate this from the data we
... |
def skipall ( stm , size ) :
"""Skips exactly size bytes in stm
If EOF is reached before size bytes are skipped
will raise : class : ` ClosedConnectionError `
: param stm : Stream to skip bytes in , should have read method
this read method can return less than requested
number of bytes .
: param size : ... | res = stm . recv ( size )
if len ( res ) == size :
return
elif len ( res ) == 0 :
raise ClosedConnectionError ( )
left = size - len ( res )
while left :
buf = stm . recv ( left )
if len ( buf ) == 0 :
raise ClosedConnectionError ( )
left -= len ( buf ) |
def link_py_so ( obj_files , so_file = None , cwd = None , libraries = None , cplus = False , fort = False , ** kwargs ) :
"""Link python extension module ( shared object ) for importing
Parameters
obj _ files : iterable of path strings
object files to be linked
so _ file : path string
Name ( path ) of sh... | libraries = libraries or [ ]
include_dirs = kwargs . pop ( 'include_dirs' , [ ] )
library_dirs = kwargs . pop ( 'library_dirs' , [ ] )
# from distutils / command / build _ ext . py :
if sys . platform == "win32" :
warnings . warn ( "Windows not yet supported." )
elif sys . platform == 'darwin' : # Don ' t use the d... |
def sniff ( filepath ) :
"""Sniffs CSV dialect and header info from csvfilepath
Returns a tuple of dialect and has _ header""" | with open ( filepath , "rb" ) as csvfile :
sample = csvfile . read ( config [ "sniff_size" ] )
sniffer = csv . Sniffer ( )
dialect = sniffer . sniff ( sample ) ( )
has_header = sniffer . has_header ( sample )
return dialect , has_header |
def get_etf_config ( self , etf_name , _async = False ) :
"""查询etf的基本信息
: param etf _ name : etf基金名称
: param _ async :
: return :""" | params = { }
path = '/etf/swap/config'
params [ 'etf_name' ] = etf_name
return api_key_get ( params , path , _async = _async ) |
def get_flatpages_i18n ( parser , token ) :
"""Retrieves all flatpage objects available for the current site and
visible to the specific user ( or visible to all users if no user is
specified ) . Populates the template context with them in a variable
whose name is defined by the ` ` as ` ` clause .
An optio... | bits = token . split_contents ( )
syntax_message = ( "%(tag_name)s expects a syntax of %(tag_name)s " "['url_starts_with'] [for user] as context_name" % dict ( tag_name = bits [ 0 ] ) )
# Must have at 3-6 bits in the tag
if 3 <= len ( bits ) <= 8 :
containing = None
excluding = None
# If there ' s an even n... |
def init_db ( dbURL , pwd_salt_size = None , pwd_rounds = None ) :
'''Initialize users database
initialize database and create necessary tables
to handle users oprations .
: param dbURL : database url , as described in : func : ` init _ proxy `''' | if not dbURL :
dbURL = 'sqlite:///:memory:'
logging . getLogger ( __name__ ) . debug ( "Initializing database: {}" . format ( dict ( url = dbURL , pwd_salt_size = pwd_salt_size , pwd_rounds = pwd_rounds ) ) )
try :
db = init_proxy ( dbURL )
global pwdCryptCtx
pwdCryptCtx = gen_crypt_context ( salt_size ... |
def getMeasurement ( self , measurementId , measurementStatus = None ) :
"""Gets the measurement with the given id .
: param measurementId : the id .
: param measurementStatus : the status of the requested measurement .
: return : the matching measurement or none if it doesn ' t exist .""" | return next ( ( x for x in self . getMeasurements ( measurementStatus ) if x . id == measurementId ) , None ) |
def _init_classes ( self , y ) :
"""Map all possible classes to the range [ 0 , . . , C - 1]
Parameters
y : list of arrays of int , each element has shape = [ samples _ i , ]
Labels of the samples for each subject
Returns
new _ y : list of arrays of int , each element has shape = [ samples _ i , ]
Mappe... | self . classes_ = unique_labels ( utils . concatenate_not_none ( y ) )
new_y = [ None ] * len ( y )
for s in range ( len ( y ) ) :
new_y [ s ] = np . digitize ( y [ s ] , self . classes_ ) - 1
return new_y |
def decode ( self , targets , encoder_outputs , attention_bias ) :
"""Generate logits for each value in the target sequence .
Args :
targets : target values for the output sequence .
int tensor with shape [ batch _ size , target _ length ]
encoder _ outputs : continuous representation of input sequence .
... | with tf . name_scope ( "decode" ) : # Prepare inputs to decoder layers by shifting targets , adding positional
# encoding and applying dropout .
decoder_inputs = self . embedding_softmax_layer ( targets )
with tf . name_scope ( "shift_targets" ) : # Shift targets to the right , and remove the last element
... |
def set_taskfileinfo ( self , tfi ) :
"""Set the : class : ` jukeboxcore . filesys . TaskFileInfo ` that the refobject represents .
: param tfi : the taskfileinfo for the refobject or None if nothing is loaded .
: type tfi : : class : ` jukeboxcore . filesys . TaskFileInfo ` | None
: returns : None
: rtype ... | self . _taskfileinfo = tfi
if tfi :
self . set_element ( tfi . task . element ) |
def launchEditor ( mapObj ) :
"""PURPOSE : launch the editor using a specific map object
INPUT : mapObj ( sc2maptool . mapRecord . MapRecord )""" | cfg = Config ( )
if cfg . is64bit :
selectedArchitecture = c . SUPPORT_64_BIT_TERMS
else :
selectedArchitecture = c . SUPPORT_32_BIT_TERMS
editorCmd = "%s -run %s -testMod %s -displayMode 1"
fullAppPath = os . path . join ( cfg . installedApp . data_dir , c . FOLDER_APP_SUPPORT % ( selectedArchitecture [ 0 ] ) ... |
def checkCytoscapeVersion ( host = cytoscape_host , port = cytoscape_port ) :
"""Checks cytoscape version
: param host : cytoscape host address , default = cytoscape _ host
: param port : cytoscape port , default = 1234
: returns : cytoscape and api version""" | URL = "http://" + str ( host ) + ":" + str ( port ) + "/v1/version/"
r = requests . get ( url = URL )
r = json . loads ( r . content )
for k in r . keys ( ) :
print ( k , r [ k ] ) |
def absent ( name , grant = None , database = None , user = None , host = 'localhost' , grant_option = False , escape = True , ** connection_args ) :
'''Ensure that the grant is absent
name
The name ( key ) of the grant to add
grant
The grant priv _ type ( i . e . select , insert , update OR all privileges ... | ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' }
# Check if grant exists , and if so , remove it
if __salt__ [ 'mysql.grant_exists' ] ( grant , database , user , host , grant_option , escape , ** connection_args ) :
if __opts__ [ 'test' ] :
ret [ 'result' ] = None
ret [ '... |
def path ( self ) :
"""Return the project path ( aka project root )
If ` ` package . _ _ file _ _ ` ` is ` ` / foo / foo / _ _ init _ _ . py ` ` , then project . path
should be ` ` / foo ` ` .""" | return pathlib . Path ( self . package . __file__ ) . resolve ( ) . parent . parent |
def AsIPAddr ( self ) :
"""Returns the IP as an ` IPAddress ` object ( if packed bytes are defined ) .""" | if self . packed_bytes is None :
return None
packed_bytes = self . packed_bytes . AsBytes ( )
if self . address_type == NetworkAddress . Family . INET :
return ipaddress . IPv4Address ( packed_bytes )
if self . address_type == NetworkAddress . Family . INET6 :
return ipaddress . IPv6Address ( packed_bytes )... |
def unindent_selection ( self , cursor ) :
"""Un - indents selected text
: param cursor : QTextCursor""" | doc = self . editor . document ( )
tab_len = self . editor . tab_length
nb_lines = len ( cursor . selection ( ) . toPlainText ( ) . splitlines ( ) )
if nb_lines == 0 :
nb_lines = 1
block = doc . findBlock ( cursor . selectionStart ( ) )
assert isinstance ( block , QtGui . QTextBlock )
i = 0
_logger ( ) . debug ( 'u... |
def _can_refresh_check ( self , check_id ) :
"""Determine if the given check _ id can be refreshed yet .
: param check _ id : the Trusted Advisor check ID
: type check _ id : str
: return : whether or not the check can be refreshed yet
: rtype : bool""" | try :
refresh_status = self . conn . describe_trusted_advisor_check_refresh_statuses ( checkIds = [ check_id ] )
logger . debug ( "TA Check %s refresh status: %s" , check_id , refresh_status [ 'statuses' ] [ 0 ] )
ms = refresh_status [ 'statuses' ] [ 0 ] [ 'millisUntilNextRefreshable' ]
if ms > 0 :
... |
def sync ( self , userId , groupInfo ) :
"""同步用户所属群组方法 ( 当第一次连接融云服务器时 , 需要向融云服务器提交 userId 对应的用户当前所加入的所有群组 , 此接口主要为防止应用中用户群信息同融云已知的用户所属群信息不同步 。 ) 方法
@ param userId : 被同步群信息的用户 Id 。 ( 必传 )
@ param groupInfo : 该用户的群信息 , 如群 Id 已经存在 , 则不会刷新对应群组名称 , 如果想刷新群组名称请调用刷新群组信息方法 。
@ return code : 返回码 , 200 为正常 。
@ return ... | desc = { "name" : "CodeSuccessReslut" , "desc" : " http 成功返回结果" , "fields" : [ { "name" : "code" , "type" : "Integer" , "desc" : "返回码,200 为正常。" } , { "name" : "errorMessage" , "type" : "String" , "desc" : "错误信息。" } ] }
params = { 'group[{0}]' . format ( Id ) : name for Id , name in groupInfo }
params [ 'userId' ] = use... |
def _lookup_symbols ( self , symbols_filename ) :
"""Look up symbols for actions and action mentions""" | symbol_lookup = GenewaysSymbols ( symbols_filename )
for action in self . actions :
action . up_symbol = symbol_lookup . id_to_symbol ( action . up )
action . dn_symbol = symbol_lookup . id_to_symbol ( action . dn ) |
def echo_size ( self , transferred = 1 , status = None ) :
'''Sample usage :
f = lambda x , y : x + y
ldata = range ( 10)
toBeTransferred = reduce ( f , range ( 10 ) )
progress = ProgressBarUtils ( " refresh " , toBeTransferred = toBeTransferred , unit = " KB " , chunk _ size = 1.0 , run _ status = " 正在下载 "... | self . transferred += transferred
# if status is not None :
self . status = status or self . status
end_str = "\r"
if self . transferred == self . toBeTransferred :
end_str = '\n'
self . status = status or self . fin_status
print ( self . __get_info ( ) + end_str ) |
def str_ripper ( self , text ) :
"""Got this code from here :
http : / / stackoverflow . com / questions / 6116978 / python - replace - multiple - strings
This method takes a set of strings , A , and removes all whole
elements of set A from string B .
Input : text string to strip based on instance attribute... | return self . pattern . sub ( lambda m : self . rep [ re . escape ( m . group ( 0 ) ) ] , text ) |
def join ( table1 , table2 , on = None , how = 'inner' , name = None ) :
"""Join two tables and return the resulting Table object .
Fields in the resulting table have their names prefixed with their
corresponding table name . For example , when joining ` item ` and
` parse ` tables , the ` i - input ` field o... | if how not in ( 'inner' , 'left' ) :
ItsdbError ( 'Only \'inner\' and \'left\' join methods are allowed.' )
# validate and normalize the pivot
on = _join_pivot ( on , table1 , table2 )
# the fields of the joined table
fields = _RelationJoin ( table1 . fields , table2 . fields , on = on )
# get key mappings to the r... |
def delete ( self , key , * keys ) :
"""Delete a key .""" | fut = self . execute ( b'DEL' , key , * keys )
return wait_convert ( fut , int ) |
def set_shaders ( self , vert , frag ) :
"""This function takes care of setting the shading code and
compiling + linking it into a working program object that is ready
to use .""" | self . _linked = False
# Create temporary shader objects
vert_handle = gl . glCreateShader ( gl . GL_VERTEX_SHADER )
frag_handle = gl . glCreateShader ( gl . GL_FRAGMENT_SHADER )
# For both vertex and fragment shader : set source , compile , check
for code , handle , type_ in [ ( vert , vert_handle , 'vertex' ) , ( fra... |
def _input_as_multiline_string ( self , data ) :
"""Writes data to tempfile and sets - infile parameter
data - - list of lines""" | if data :
self . Parameters [ '-infile' ] . on ( super ( Clustalw , self ) . _input_as_multiline_string ( data ) )
return '' |
def save_to_wav ( self , file_name ) :
"""Save this time series to a wav format audio file .
Parameters
file _ name : string
The output file name""" | scaled = _numpy . int16 ( self . numpy ( ) / max ( abs ( self ) ) * 32767 )
write_wav ( file_name , self . sample_rate , scaled ) |
def _import_astorb_to_database ( self , astorbDictList ) :
"""* import the astorb orbital elements to database *
* * Key Arguments : * *
- ` ` astorbDictList ` ` - - the astorb database parsed as a list of dictionaries
* * Return : * *
- None""" | self . log . info ( 'starting the ``_import_astorb_to_database`` method' )
print "Refreshing the orbital elements database table"
dbSettings = self . settings [ "database settings" ] [ "atlasMovers" ]
insert_list_of_dictionaries_into_database_tables ( dbConn = self . atlasMoversDBConn , log = self . log , dictList = as... |
def run ( hostname = None , port = None , path = None , loop = None ) :
"""The arguments are not all optional . Either a path or hostname + port should
be specified ; you have to specify one .""" | if path :
log . debug ( "Starting Opentrons server application on {}" . format ( path ) )
hostname , port = None , None
else :
log . debug ( "Starting Opentrons server application on {}:{}" . format ( hostname , port ) )
path = None
web . run_app ( init ( loop ) , host = hostname , port = port , path = ... |
def dfs ( self , node , bucket = None , order = "append" ) :
"""Recursive depth first search . By default ( " order " = ` ` " append " ` ` ) this
returns the * * node objects * * in the reverse postorder . To change this
into the preorder use a ` ` collections . deque ` ` as " bucket " and
` ` " appendleft " ... | if self [ node ] . discovered :
return bucket
self [ node ] . discovered = True
nodes_ = sorted ( self [ node ] . iternodes ( ) , cmp = self . cmp_branch )
for node_ in nodes_ :
self . dfs ( node_ , bucket , order )
getattr ( bucket , order ) ( node )
self [ node ] . examined = True
return bucket |
def _internal_add ( self , pattern : Pattern , label , renaming ) -> int :
"""Add a new pattern to the matcher .
Equivalent patterns are not added again . However , patterns that are structurally equivalent ,
but have different constraints or different variable names are distinguished by the matcher .
Args : ... | pattern_index = len ( self . patterns )
renamed_constraints = [ c . with_renamed_vars ( renaming ) for c in pattern . local_constraints ]
constraint_indices = [ self . _add_constraint ( c , pattern_index ) for c in renamed_constraints ]
self . patterns . append ( ( pattern , label , constraint_indices ) )
self . patter... |
def plot_neuron3d ( ax , nrn , neurite_type = NeuriteType . all , diameter_scale = _DIAMETER_SCALE , linewidth = _LINEWIDTH , color = None , alpha = _ALPHA ) :
'''Generates a figure of the neuron ,
that contains a soma and a list of trees .
Args :
ax ( matplotlib axes ) : on what to plot
nrn ( neuron ) : ne... | plot_soma3d ( ax , nrn . soma , color = color , alpha = alpha )
for neurite in iter_neurites ( nrn , filt = tree_type_checker ( neurite_type ) ) :
plot_tree3d ( ax , neurite , diameter_scale = diameter_scale , linewidth = linewidth , color = color , alpha = alpha )
ax . set_title ( nrn . name ) |
def element_text_should_be ( self , locator , expected , message = '' ) :
"""Verifies element identified by ` ` locator ` ` exactly contains text ` ` expected ` ` .
In contrast to ` Element Should Contain Text ` , this keyword does not try
a substring match but an exact match on the element identified by ` ` lo... | self . _info ( "Verifying element '%s' contains exactly text '%s'." % ( locator , expected ) )
element = self . _element_find ( locator , True , True )
actual = element . text
if expected != actual :
if not message :
message = "The text of element '%s' should have been '%s' but " "in fact it was '%s'." % ( ... |
def list_security_groups ( self , retrieve_all = True , ** _params ) :
"""Fetches a list of all security groups for a project .""" | return self . list ( 'security_groups' , self . security_groups_path , retrieve_all , ** _params ) |
def fetch_exemplars ( keyword , outfile , n = 50 ) :
"""Fetch top lists matching this keyword , then return Twitter screen
names along with the number of different lists on which each appers . .""" | list_urls = fetch_lists ( keyword , n )
print ( 'found %d lists for %s' % ( len ( list_urls ) , keyword ) )
counts = Counter ( )
for list_url in list_urls :
counts . update ( fetch_list_members ( list_url ) )
# Write to file .
outf = io . open ( outfile , 'wt' )
for handle in sorted ( counts ) :
outf . write ( ... |
def _strify ( s ) :
"""If s is a unicode string , encode it to UTF - 8 and return the results ,
otherwise return str ( s ) , or None if s is None""" | if s is None :
return None
if isinstance ( s , unicode ) :
return s . encode ( "utf-8" )
return str ( s ) |
def create_ogr_field_from_definition ( field_definition ) :
"""Helper to create a field from definition .
: param field _ definition : The definition of the field ( see :
safe . definitions . fields ) .
: type field _ definition : dict
: return : The new ogr field definition .
: rtype : ogr . FieldDefn""" | if isinstance ( field_definition [ 'type' ] , list ) : # Use the first element in the list of type
field_type = field_definition [ 'type' ] [ 0 ]
else :
field_type = field_definition [ 'type' ]
# Conversion to OGR field
field_type = field_type_converter . get ( field_type , ogr . OFTString )
return ogr . FieldD... |
def _function_add_call_edge ( self , addr , src_node , function_addr , syscall = False , stmt_idx = None , ins_addr = None ) :
"""Add a call edge to the function transition map .
: param int addr : Address that is being called ( callee ) .
: param CFGNode src _ node : The source CFG node ( caller ) .
: param ... | try :
if src_node is None :
self . kb . functions . _add_node ( function_addr , addr , syscall = syscall )
else :
src_snippet = self . _to_snippet ( cfg_node = src_node )
return_to_outside = False
ret_snippet = None
self . kb . functions . _add_call_to ( function_addr , s... |
def RunValidation ( feed , options , problems ) :
"""Validate feed , returning the loaded Schedule and exit code .
Args :
feed : GTFS file , either path of the file as a string or a file object
options : options object returned by optparse
problems : transitfeed . ProblemReporter instance
Returns :
a tr... | util . CheckVersion ( problems , options . latest_version )
# TODO : Add tests for this flag in testfeedvalidator . py
if options . extension :
try :
__import__ ( options . extension )
extension_module = sys . modules [ options . extension ]
except ImportError : # TODO : Document extensions in a... |
def headerData ( self , section , orientation , role ) :
"""Return the header data
Will call : meth : ` TreeItem . data ` of the root : class : ` TreeItem ` with the
given section ( column ) and role for horizontal orientations .
Vertical orientations are numbered .
: param section : the section in the head... | if orientation == QtCore . Qt . Horizontal :
d = self . _root . data ( section , role )
if d is None and role == QtCore . Qt . DisplayRole :
return str ( section + 1 )
return d
if orientation == QtCore . Qt . Vertical and role == QtCore . Qt . DisplayRole :
return str ( section + 1 ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.