signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def decode ( self , encoded_packet ) : """Decode a transmitted package ."""
b64 = False if not isinstance ( encoded_packet , binary_types ) : encoded_packet = encoded_packet . encode ( 'utf-8' ) elif not isinstance ( encoded_packet , bytes ) : encoded_packet = bytes ( encoded_packet ) self . packet_type = six . byte2int ( encoded_packet [ 0 : 1 ] ) if self . packet_type == 98 : # ' b '...
def find_max_pending_transfers ( gas_limit ) : """Measure gas consumption of TokenNetwork . unlock ( ) depending on number of pending transfers and find the maximum number of pending transfers so gas _ limit is not exceeded ."""
tester = ContractTester ( generate_keys = 2 ) tester . deploy_contract ( 'SecretRegistry' ) tester . deploy_contract ( 'HumanStandardToken' , _initialAmount = 100000 , _decimalUnits = 3 , _tokenName = 'SomeToken' , _tokenSymbol = 'SMT' , ) tester . deploy_contract ( 'TokenNetwork' , _token_address = tester . contract_a...
def parse_rs_alg ( r ) : """Parse resampling algorithm"""
# Note : GRA _ CubicSpline created huge block artifacts for the St . Helen ' s compute _ dh WV cases # Stick with CubicSpline for both upsampling / downsampling for now if r == 'near' : # Note : Nearest respects nodata when downsampling gra = gdal . GRA_NearestNeighbour elif r == 'bilinear' : gra = gdal . GRA_B...
def _write_to_log ( self , output ) : """Write the output string to the log file ."""
with open ( self . log_file , 'a' ) as log_file : log_file . write ( '\n' ) log_file . write ( output ) log_file . write ( '\n' )
def getAssociationFilename ( self , server_url , handle ) : """Create a unique filename for a given server url and handle . This implementation does not assume anything about the format of the handle . The filename that is returned will contain the domain name from the server URL for ease of human inspectio...
if server_url . find ( '://' ) == - 1 : raise ValueError ( 'Bad server URL: %r' % server_url ) proto , rest = server_url . split ( '://' , 1 ) domain = _filenameEscape ( rest . split ( '/' , 1 ) [ 0 ] ) url_hash = _safe64 ( server_url ) if handle : handle_hash = _safe64 ( handle ) else : handle_hash = '' fi...
def checkprint ( self , cmd , shell = None , nofail = False ) : """Just like callprint , but checks output - - so you can get a variable in python corresponding to the return value of the command you call . This is equivalent to running subprocess . check _ output ( ) instead of subprocess . call ( ) . : pa...
self . _report_command ( cmd ) likely_shell = check_shell ( cmd , shell ) if shell is None : shell = likely_shell if not shell : if likely_shell : print ( "Should this command run in a shell instead of directly in a subprocess?" ) cmd = shlex . split ( cmd ) try : return subprocess . check_outpu...
def _policies_present ( name , policies , policies_from_pillar , listeners , backends , region , key , keyid , profile ) : '''helper method for present . ensure that ELB policies are set'''
if policies is None : policies = [ ] pillar_policies = __salt__ [ 'config.option' ] ( policies_from_pillar , [ ] ) policies = policies + pillar_policies if backends is None : backends = [ ] # check for policy name uniqueness and correct type policy_names = set ( ) for p in policies : if 'policy_name' not in...
def main ( ) : """Run the core ."""
parser = ArgumentParser ( ) subs = parser . add_subparsers ( dest = 'cmd' ) setup_parser = subs . add_parser ( 'search' ) setup_parser . add_argument ( '-e' , '--engine' , dest = 'engine' , required = True , help = 'Search engine to use.' , choices = [ 'bing' ] ) setup_parser . add_argument ( '-d' , '--domain' , dest =...
def writeElement ( self , data ) : """Encodes C { data } to AMF . If the data is not able to be matched to an AMF type , then L { pyamf . EncodeError } will be raised ."""
key = type ( data ) func = None try : func = self . _func_cache [ key ] except KeyError : func = self . getTypeFunc ( data ) if func is None : raise pyamf . EncodeError ( 'Unable to encode %r (type %r)' % ( data , key ) ) self . _func_cache [ key ] = func func ( data )
def hincrby ( self , key , field , increment = 1 ) : """Increment the integer value of a hash field by the given number ."""
return self . execute ( b'HINCRBY' , key , field , increment )
def bitmask ( * args ) : """! @ brief Returns a mask with specified bit ranges set . An integer mask is generated based on the bits and bit ranges specified by the arguments . Any number of arguments can be provided . Each argument may be either a 2 - tuple of integers , a list of integers , or an individual ...
mask = 0 for a in args : if type ( a ) is tuple : for b in range ( a [ 1 ] , a [ 0 ] + 1 ) : mask |= 1 << b elif type ( a ) is list : for b in a : mask |= 1 << b elif type ( a ) is int : mask |= 1 << a return mask
def get_multiple_choices_required ( self ) : """Add only the required message , but no ' ng - required ' attribute to the input fields , otherwise all Checkboxes of a MultipleChoiceField would require the property " checked " ."""
errors = [ ] if self . required : for key , msg in self . error_messages . items ( ) : if key == 'required' : errors . append ( ( '$error.required' , msg ) ) return errors
def chunks ( iterable , n ) : """Yield successive n - sized chunks from iterable object . https : / / stackoverflow . com / a / 312464"""
for i in range ( 0 , len ( iterable ) , n ) : yield iterable [ i : i + n ]
def fetch_order_book ( self ) -> OrderBook : """Fetch the order book ."""
return self . _fetch ( 'order book' , self . market . code ) ( self . _order_book ) ( )
def activate_status_output_overall_error_msg ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) activate_status = ET . Element ( "activate_status" ) config = activate_status output = ET . SubElement ( activate_status , "output" ) overall_error_msg = ET . SubElement ( output , "overall-error-msg" ) overall_error_msg . text = kwargs . pop ( 'overall_error_msg' ) callback = kwargs ...
def write ( self , pack_uri , blob ) : """Write * blob * to this zip package with the membername corresponding to * pack _ uri * ."""
self . _zipf . writestr ( pack_uri . membername , blob )
def add_parameters ( parser ) : """Add evaluation specific parameters to parser ."""
group = parser . add_argument_group ( 'Evaluation arguments' ) group . add_argument ( '--eval-batch-size' , type = int , default = 1024 ) # Datasets group . add_argument ( '--similarity-datasets' , type = str , default = nlp . data . word_embedding_evaluation . word_similarity_datasets , nargs = '*' , help = 'Word simi...
def all ( self ) : """Return all testcases : return :"""
tests = list ( ) for testclass in self . classes : tests . extend ( self . classes [ testclass ] . cases ) return tests
def build_visualization ( ontouri , g , viz_index , path = None , title = "" , theme = "" ) : """2017-01-20 : new verion , less clever but also simpler : param g : : param viz _ index : : param main _ entity : : return :"""
this_viz = VISUALIZATIONS_LIST [ viz_index ] if this_viz [ 'ID' ] == "html-simple" : from . viz . viz_html_single import HTMLVisualizer v = HTMLVisualizer ( g , title ) elif this_viz [ 'ID' ] == "html-complex" : from . viz . viz_html_multi import KompleteViz v = KompleteViz ( g , title , theme ) elif th...
def ls ( self , foldername = "INBOX" , reverse = False , since = None , grep = None , field = None , stream = sys . stdout ) : """Do standard text list of the folder to the stream . ' foldername ' is the folder to list . . INBOX by default . ' since ' allows the listing to be date filtered since that date . I...
if foldername == "" : foldername = "INBOX" msg_list = self . _list ( foldername , reverse , since ) for folder , mk , m in msg_list : try : # I am very unsure about this defaulting of foldername output_items = ( "%s%s%s" % ( folder . folder or foldername or "INBOX" , SEPERATOR , mk ) , m . date , m . ge...
def get_now ( ) : """Allows to access global request and read a timestamp from query ."""
if not get_current_request : return datetime . datetime . now ( ) request = get_current_request ( ) if request : openinghours_now = request . GET . get ( 'openinghours-now' ) if openinghours_now : return datetime . datetime . strptime ( openinghours_now , '%Y%m%d%H%M%S' ) return datetime . datetime ...
def to_python ( self , value : Optional [ str ] ) -> Optional [ Any ] : """Called during deserialization and during form ` ` clean ( ) ` ` calls . Must deal with an instance of the correct type ; a string ; or ` ` None ` ` ( if the field allows ` ` null = True ` ` ) . Should raise ` ` ValidationError ` ` if p...
# https : / / docs . djangoproject . com / en / 1.8 / howto / custom - model - fields / # log . debug ( " to _ python : { } , { } " , value , type ( value ) ) if isinstance ( value , datetime . datetime ) : return value if value is None : return value if value == '' : return None return iso_string_to_python...
def get_open_orders ( self , market = None ) : """Get all orders that you currently have opened . A specific market can be requested . Endpoint : 1.1 / market / getopenorders 2.0 / key / market / getopenorders : param market : String literal for the market ( ie . BTC - LTC ) : type market : str : retu...
return self . _api_query ( path_dict = { API_V1_1 : '/market/getopenorders' , API_V2_0 : '/key/market/getopenorders' } , options = { 'market' : market , 'marketname' : market } if market else None , protection = PROTECTION_PRV )
def foreach_loop ( self , context ) : """Run step once for each item in foreach _ items . On each iteration , the invoked step can use context [ ' i ' ] to get the current iterator value . Args : context : ( pypyr . context . Context ) The pypyr context . This arg will mutate ."""
logger . debug ( "starting" ) # Loop decorators only evaluated once , not for every step repeat # execution . foreach = context . get_formatted_iterable ( self . foreach_items ) foreach_length = len ( foreach ) logger . info ( f"foreach decorator will loop {foreach_length} times." ) for i in foreach : logger . info...
def _validate_simple ( email ) : """Does a simple validation of an email by matching it to a regexps : param email : The email to check : return : The valid Email address : raises : ValueError if value is not a valid email"""
name , address = parseaddr ( email ) if not re . match ( '[^@]+@[^@]+\.[^@]+' , address ) : raise ValueError ( 'Invalid email :{email}' . format ( email = email ) ) return address
def Create ( path , password , generate_default_key = True ) : """Create a new user wallet . Args : path ( str ) : A path indicating where to create or open the wallet e . g . " / Wallets / mywallet " . password ( str ) : a 10 characters minimum password to secure the wallet with . Returns : UserWallet : ...
wallet = UserWallet ( path = path , passwordKey = password , create = True ) if generate_default_key : wallet . CreateKey ( ) return wallet
def _convert_results ( self , data , ** kwargs ) : """converts the results of a query to RdfDatatype instances args : data : a list of triples"""
if kwargs . get ( "multiprocessing" , False ) : m = mp . Manager ( ) output = m . Queue ( ) pdb . set_trace ( ) # processes = [ mp . Process ( target = convert _ row _ main , # args = ( row , output , ) ) # for row in data ] # # Run processes # for p in processes : # p . start ( ) ...
def enable_hostgroup_passive_svc_checks ( self , hostgroup ) : """Enable service passive checks for a hostgroup Format of the line that triggers function call : : ENABLE _ HOSTGROUP _ PASSIVE _ SVC _ CHECKS ; < hostgroup _ name > : param hostgroup : hostgroup to enable : type hostgroup : alignak . objects ....
for host_id in hostgroup . get_hosts ( ) : if host_id in self . daemon . hosts : for service_id in self . daemon . hosts [ host_id ] . services : if service_id in self . daemon . services : self . enable_passive_svc_checks ( self . daemon . services [ service_id ] )
def parse ( self ) : """Returns a cleaned lxml ElementTree : returns : Whether the cleaned HTML has matches or not : rtype : bool"""
# Create the element tree self . tree = self . _build_tree ( self . html_contents ) # Get explicits elements to keep and discard self . elts_to_keep = self . _get_elements_to_keep ( ) self . elts_to_discard = self . _get_elements_to_discard ( ) # Init an empty list of Elements to remove self . elts_to_remove = [ ] # Ch...
def execDetails ( self , reqId , contract , execution ) : """execDetails ( EWrapper self , int reqId , Contract contract , Execution execution )"""
return _swigibpy . EWrapper_execDetails ( self , reqId , contract , execution )
def add_vrf ( self , auth , attr ) : """Add a new VRF . * ` auth ` [ BaseAuth ] AAA options . * ` attr ` [ vrf _ attr ] The news VRF ' s attributes . Add a VRF based on the values stored in the ` attr ` dict . Returns a dict describing the VRF which was added . This is the documentation of the interna...
self . _logger . debug ( "add_vrf called; attr: %s" % unicode ( attr ) ) # sanity check - do we have all attributes ? req_attr = [ 'rt' , 'name' ] self . _check_attr ( attr , req_attr , _vrf_attrs ) insert , params = self . _sql_expand_insert ( attr ) sql = "INSERT INTO ip_net_vrf " + insert self . _execute ( sql , par...
def create_volume_attachment ( self , body , ** kwargs ) : # noqa : E501 """create _ volume _ attachment # noqa : E501 create a VolumeAttachment # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . create_volume_attachment_with_http_info ( body , ** kwargs ) # noqa : E501 else : ( data ) = self . create_volume_attachment_with_http_info ( body , ** kwargs ) # noqa : E501 return data
def delete_interconnect ( self , enclosure_uri , bay , timeout = - 1 ) : """Deletes an interconnect from a location . Warning : This won ' t delete the LOGICAL INTERCONNECT itself and might cause inconsistency between the enclosure and Logical Interconnect Group . Args : enclosure _ uri : URI of the Enclo...
uri = "{path}?location=Enclosure:{enclosure_uri},Bay:{bay}" . format ( path = self . LOCATIONS_PATH , enclosure_uri = enclosure_uri , bay = bay ) return self . _helper . delete ( uri , timeout = timeout )
def is_model_view_subclass_method_shouldnt_be_function ( node ) : """Checks that node is get or post method of the View class ."""
if node . name not in ( 'get' , 'post' ) : return False parent = node . parent while parent and not isinstance ( parent , ScopedClass ) : parent = parent . parent subclass = ( 'django.views.View' , 'django.views.generic.View' , 'django.views.generic.base.View' , ) return parent is not None and node_is_subclass ...
def driver_needed ( func ) : """Decorator for WhatsappObjectWithId methods that need to communicate with the browser It ensures that the object receives a driver instance at construction : param func : WhatsappObjectWithId method : return : Wrapped method"""
def wrapped ( self , * args ) : if not self . driver : raise AttributeError ( "No driver passed to object" ) return func ( self , * args ) return wrapped
def add_annotation_value ( graph , annotation , value ) : """Add the given annotation / value pair to all qualified edges . : param pybel . BELGraph graph : : param str annotation : : param str value :"""
if annotation not in graph . defined_annotation_keywords : raise ValueError ( 'annotation not defined: {}' . format ( annotation ) ) for u , v , k in graph . edges ( keys = True ) : if ANNOTATIONS not in graph [ u ] [ v ] [ k ] : continue if annotation not in graph [ u ] [ v ] [ k ] [ ANNOTATIONS ] ...
def submit_rpc ( self , rpc_name , params , flags = 0 ) : """Sends an RPC request . This call will transition session into pending state . If some operation is currently pending on the session , it will be cancelled before sending this request . Spec : http : / / msdn . microsoft . com / en - us / library /...
logger . info ( 'Sending RPC %s flags=%d' , rpc_name , flags ) self . messages = [ ] self . output_params = { } self . cancel_if_pending ( ) self . res_info = None w = self . _writer with self . querying_context ( tds_base . PacketType . RPC ) : if tds_base . IS_TDS72_PLUS ( self ) : self . _start_query ( )...
def _transform ( self , Y , scan_onsets , beta , beta0 , rho_e , sigma_e , rho_X , sigma2_X , rho_X0 , sigma2_X0 ) : """Given the data Y and the response amplitudes beta and beta0 estimated in the fit step , estimate the corresponding X and X0. It is done by a forward - backward algorithm . We assume X and X0...
logger . info ( 'Transforming new data.' ) # Constructing the transition matrix and the variance of # innovation noise as prior for the latent variable X and X0 # in new data . n_C = beta . shape [ 0 ] n_T = Y . shape [ 0 ] weight = np . concatenate ( ( beta , beta0 ) , axis = 0 ) T_X = np . diag ( np . concatenate ( (...
def main ( ) : """Run Windows environment variable editor"""
from spyder . utils . qthelpers import qapplication app = qapplication ( ) if os . name == 'nt' : dialog = WinUserEnvDialog ( ) else : dialog = EnvDialog ( ) dialog . show ( ) app . exec_ ( )
def _set_redist_connected ( self , v , load = False ) : """Setter method for redist _ connected , mapped from YANG variable / isis _ state / router _ isis _ config / is _ address _ family _ v6 / redist _ connected ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = redist_connected . redist_connected , is_container = 'container' , presence = False , yang_name = "redist-connected" , rest_name = "redist-connected" , parent = self , path_helper = self . _path_helper , extmethods = self . _...
def surrounding_nodes ( self , position ) : """Returns nearest node indices and direction of opposite node . : param position : Position inside the mesh to search nearest node for as ( x , y , z ) : return : Nearest node indices and direction of opposite node ."""
n_node_index , n_node_position , n_node_error = self . nearest_node ( position ) if n_node_error == 0.0 : index_mod = [ ] for i in range ( len ( n_node_index ) ) : new_point = np . asarray ( n_node_position ) new_point [ i ] += 1.e-5 * np . abs ( new_point [ i ] ) try : self ...
def unpack_rsp ( cls , rsp_pb ) : """Convert from PLS response to user response"""
if rsp_pb . retType != RET_OK : return RET_ERROR , rsp_pb . retMsg , None order_id = str ( rsp_pb . s2c . orderID ) modify_order_list = [ { 'trd_env' : TRADE . REV_TRD_ENV_MAP [ rsp_pb . s2c . header . trdEnv ] , 'order_id' : order_id } ] return RET_OK , "" , modify_order_list
async def oauth ( request ) : """Oauth example ."""
provider = request . match_info . get ( 'provider' ) client , _ = await app . ps . oauth . login ( provider , request ) user , data = await client . user_info ( ) response = ( "<a href='/'>back</a><br/><br/>" "<ul>" "<li>ID: {u.id}</li>" "<li>Username: {u.username}</li>" "<li>First, last name: {u.first_name}, {u.last_n...
def get_count ( self ) : """Gets the total _ count using the current filter constraints ."""
params = self . get_params ( ) params [ "offset" ] = self . low_mark params [ "limit" ] = 1 r = self . resource . _meta . api . http_resource ( "GET" , self . resource . _meta . resource_name , params = params ) data = self . resource . _meta . api . resource_deserialize ( r . text ) number = data [ "meta" ] [ "total_c...
def to_jsondict ( self ) : """Returns a dict expressing the flow stats ."""
body = { "oxs_fields" : [ ofproto . oxs_to_jsondict ( k , uv ) for k , uv in self . fields ] , "length" : self . length } return { self . __class__ . __name__ : body }
def answer_json_to_strings ( answer : Dict [ str , Any ] ) -> Tuple [ Tuple [ str , ... ] , str ] : """Takes an answer JSON blob from the DROP data release and converts it into strings used for evaluation ."""
if "number" in answer and answer [ "number" ] : return tuple ( [ str ( answer [ "number" ] ) ] ) , "number" elif "spans" in answer and answer [ "spans" ] : return tuple ( answer [ "spans" ] ) , "span" if len ( answer [ "spans" ] ) == 1 else "spans" elif "date" in answer : return tuple ( [ "{0} {1} {2}" . fo...
def _parse_address ( self , config ) : """Parses the config block and returns the ip address value The provided configuration block is scaned and the configured value for the IP address is returned as a dict object . If the IP address value is not configured , then None is returned for the value Args : co...
match = re . search ( r'ip address ([^\s]+)' , config ) value = match . group ( 1 ) if match else None return dict ( address = value )
async def get ( self , request , resource = None , ** kwargs ) : """Get resource or collection of resources . parameters : - name : resource in : path type : string"""
if resource is not None and resource != '' : return self . to_simple ( request , resource , ** kwargs ) return self . to_simple ( request , self . collection , many = True , ** kwargs )
def get_replicas ( self , keyspace , key ) : """Returns a list of : class : ` . Host ` instances that are replicas for a given partition key ."""
t = self . token_map if not t : return [ ] try : return t . get_replicas ( keyspace , t . token_class . from_key ( key ) ) except NoMurmur3 : return [ ]
def getDeviceList ( self , skip_on_access_error = False , skip_on_error = False ) : """Return a list of all USB devices currently plugged in , as USBDevice instances . skip _ on _ error ( bool ) If True , ignore devices which raise USBError . skip _ on _ access _ error ( bool ) DEPRECATED . Alias for skip...
return list ( self . getDeviceIterator ( skip_on_error = skip_on_access_error or skip_on_error , ) , )
def _get_coroutine ( self , request , start_response ) : '''Try to dispapch the request and get the matching coroutine .'''
adapter = self . url_map . bind_to_environ ( request . environ ) resource , kwargs = adapter . match ( ) callback = self . callback_map [ resource ] inject_extra_args ( callback , request , kwargs ) return callback ( request , start_response , ** kwargs )
def get_model ( self ) : '''` object ` of model as a function approximator , which has ` lstm _ model ` whose type is ` pydbm . rnn . lstm _ model . LSTMModel ` .'''
class Model ( object ) : def __init__ ( self , lstm_model ) : self . lstm_model = lstm_model return Model ( self . __lstm_model )
def create_index ( self , attr , unique = False , accept_none = False ) : """Create a new index on a given attribute . If C { unique } is True and records are found in the table with duplicate attribute values , the index is deleted and C { KeyError } is raised . If the table already has an index on the given...
if attr in self . _indexes : raise ValueError ( 'index %r already defined for table' % attr ) if unique : self . _indexes [ attr ] = _UniqueObjIndex ( attr , accept_none ) self . _uniqueIndexes = [ ind for ind in self . _indexes . values ( ) if ind . is_unique ] else : self . _indexes [ attr ] = _ObjInd...
def get_files_in_branch ( profile , branch_sha ) : """Get all files in a branch ' s tree . Args : profile A profile generated from ` ` simplygithub . authentication . profile ` ` . Such profiles tell this module ( i ) the ` ` repo ` ` to connect to , and ( ii ) the ` ` token ` ` to connect with . branch...
tree_sha = get_commit_tree ( profile , branch_sha ) files = get_files_in_tree ( profile , tree_sha ) tree = [ prepare ( x ) for x in files ] return tree
def merge_bibtex_with_aux ( auxpath , mainpath , extradir , parse = get_bibtex_dict , allow_missing = False ) : """Merge multiple BibTeX files into a single homogeneously - formatted output , using a LaTeX . aux file to know which records are worth paying attention to . The file identified by ` mainpath ` wil...
auxpath = Path ( auxpath ) mainpath = Path ( mainpath ) extradir = Path ( extradir ) with auxpath . open ( 'rt' ) as aux : citednames = sorted ( cited_names_from_aux_file ( aux ) ) main = mainpath . try_open ( mode = 'rt' ) if main is None : maindict = { } else : maindict = parse ( main ) main . close (...
def bind_package ( name , path = None , version_range = None , no_deps = False , bind_args = None , quiet = False ) : """Bind software available on the current system , as a rez package . Note : ` bind _ args ` is provided when software is bound via the ' rez - bind ' command line tool . Bind modules can defi...
pending = set ( [ name ] ) installed_variants = [ ] installed_package_names = set ( ) primary = True # bind package and possibly dependencies while pending : pending_ = pending pending = set ( ) exc_type = None for name_ in pending_ : # turn error on binding of dependencies into a warning - we don ' t ...
def get_xattrs ( self , path , xattr_name = None , encoding = 'text' , ** kwargs ) : """Get one or more xattr values for a file or directory . : param xattr _ name : ` ` str ` ` to get one attribute , ` ` list ` ` to get multiple attributes , ` ` None ` ` to get all attributes . : param encoding : ` ` text ` ...
kwargs [ 'xattr.name' ] = xattr_name json = _json ( self . _get ( path , 'GETXATTRS' , encoding = encoding , ** kwargs ) ) [ 'XAttrs' ] # Decode the result result = { } for attr in json : k = attr [ 'name' ] v = attr [ 'value' ] if v is None : result [ k ] = None elif encoding == 'text' : ...
def orderStatus ( self , orderId , status , filled , remaining , avgFillPrice , permId , parentId , lastFillPrice , clientId , whyHeld ) : """orderStatus ( EWrapper self , OrderId orderId , IBString const & status , int filled , int remaining , double avgFillPrice , int permId , int parentId , double lastFillPrice ...
return _swigibpy . EWrapper_orderStatus ( self , orderId , status , filled , remaining , avgFillPrice , permId , parentId , lastFillPrice , clientId , whyHeld )
def p_im ( p ) : """asm : IM expr"""
val = p [ 2 ] . eval ( ) if val not in ( 0 , 1 , 2 ) : error ( p . lineno ( 1 ) , 'Invalid IM number %i' % val ) p [ 0 ] = None return p [ 0 ] = Asm ( p . lineno ( 1 ) , 'IM %i' % val )
def last_written_resolver ( riak_object ) : """A conflict - resolution function that resolves by selecting the most recently - modified sibling by timestamp . : param riak _ object : an object - in - conflict that will be resolved : type riak _ object : : class : ` RiakObject < riak . riak _ object . RiakObje...
riak_object . siblings = [ max ( riak_object . siblings , key = lambda x : x . last_modified ) , ]
def merge_runs ( res_list , print_progress = True ) : """Merges a set of runs with differing ( possibly variable ) numbers of live points into one run . Parameters res _ list : list of : class : ` ~ dynesty . results . Results ` instances A list of : class : ` ~ dynesty . results . Results ` instances retur...
ntot = len ( res_list ) counter = 0 # Establish our set of baseline runs and " add - on " runs . rlist_base = [ ] rlist_add = [ ] for r in res_list : try : if np . any ( r . samples_batch == 0 ) : rlist_base . append ( r ) else : rlist_add . append ( r ) except : ...
def update_network ( self , network , body = None ) : """Updates a network ."""
return self . put ( self . network_path % ( network ) , body = body )
def install ( board_id = 'atmega88' , mcu = 'atmega88' , f_cpu = 20000000 , upload = 'usbasp' , core = 'arduino' , replace_existing = True , ) : """install atmega88 board ."""
board = AutoBunch ( ) board . name = TEMPL . format ( mcu = mcu , f_cpu = f_cpu , upload = upload ) board . upload . using = upload board . upload . maximum_size = 8 * 1024 board . build . mcu = mcu board . build . f_cpu = str ( f_cpu ) + 'L' board . build . core = core # for 1.0 board . build . variant = 'standard' in...
def dump_ckan ( m ) : """Create a groups and organization file"""
doc = MetapackDoc ( cache = m . cache ) doc . new_section ( 'Groups' , 'Title Description Id Image_url' . split ( ) ) doc . new_section ( 'Organizations' , 'Title Description Id Image_url' . split ( ) ) c = RemoteCKAN ( m . ckan_url , apikey = m . api_key ) for g in c . action . group_list ( all_fields = True ) : p...
def run ( self ) : """Begins the runtime execution ."""
iterations = 0 queue = self . queue . tick ( ) while True : try : next ( queue ) except StopIteration : break iterations += 1 sleep ( self . sleep_time ) return iterations
def receive_one_message ( self ) : """Handle a single request . Polls the transport for a new message . After a new message has arrived : py : meth : ` _ spawn ` is called with a handler function and arguments to handle the request . The handler function will try to decode the message using the supplied p...
context , message = self . transport . receive_message ( ) if callable ( self . trace ) : self . trace ( '-->' , context , message ) # assuming protocol is threadsafe and dispatcher is theadsafe , as # long as its immutable def handle_message ( context , message ) : try : request = self . protocol . par...
def _ani_ic_on_planck ( electron_energy , soft_photon_temperature , gamma_energy , theta ) : """IC cross - section for anisotropic interaction with a blackbody photon spectrum following Eq . 11 of Khangulyan , Aharonian , and Kelner 2014, ApJ 783 , 100 ( ` arXiv : 1310.7971 < http : / / www . arxiv . org / abs ...
Ktomec2 = 1.6863699549e-10 soft_photon_temperature *= Ktomec2 gamma_energy = gamma_energy [ : , None ] # Parameters from Eqs 21 , 22 a1 = [ 0.857 , 0.153 , 1.840 , 0.254 ] a2 = [ 0.691 , 1.330 , 1.668 , 0.534 ] z = gamma_energy / electron_energy ttheta = ( 2.0 * electron_energy * soft_photon_temperature * ( 1.0 - np . ...
def percent_k ( data , period ) : """Formula : % k = data ( t ) - low ( n ) / ( high ( n ) - low ( n ) )"""
catch_errors . check_for_period_error ( data , period ) percent_k = [ ( ( data [ idx ] - np . min ( data [ idx + 1 - period : idx + 1 ] ) ) / ( np . max ( data [ idx + 1 - period : idx + 1 ] ) - np . min ( data [ idx + 1 - period : idx + 1 ] ) ) ) for idx in range ( period - 1 , len ( data ) ) ] percent_k = fill_for_no...
def handle_units ( changeset ) : """Populate the change set with addUnit changes ."""
units , records = { } , { } for service_name , service in sorted ( changeset . bundle [ 'services' ] . items ( ) ) : for i in range ( service . get ( 'num_units' , 0 ) ) : record_id = 'addUnit-{}' . format ( changeset . next_action ( ) ) unit_name = '{}/{}' . format ( service_name , i ) reco...
def augment_or_diminish_until_the_interval_is_right ( note1 , note2 , interval ) : """A helper function for the minor and major functions . You should probably not use this directly ."""
cur = measure ( note1 , note2 ) while cur != interval : if cur > interval : note2 = notes . diminish ( note2 ) elif cur < interval : note2 = notes . augment ( note2 ) cur = measure ( note1 , note2 ) # We are practically done right now , but we need to be able to create the # minor seventh of...
def fix_config ( self , options ) : """Fixes the options , if necessary . I . e . , it adds all required elements to the dictionary . : param options : the options to fix : type options : dict : return : the ( potentially ) fixed options : rtype : dict"""
options = super ( GetStorageValue , self ) . fix_config ( options ) opt = "storage_name" if opt not in options : options [ opt ] = "unknown" if opt not in self . help : self . help [ opt ] = "The name of the storage value to retrieve (string)." return options
def check_ordered ( self ) : """True if each chromosome is listed together as a chunk and if the range starts go from smallest to largest otherwise false : return : is it ordered ? : rtype : bool"""
sys . stderr . write ( "error unimplemented check_ordered\n" ) sys . exit ( ) seen_chrs = set ( ) curr_chr = None prevstart = 0 for l in self . _lines : if not l [ 'rng' ] : continue if l [ 'rng' ] . chr != curr_chr : prevstart = 0 if l [ 'rng' ] . chr in seen_chrs : return F...
def run_parallel_map_providers_query ( data , queue = None ) : '''This function will be called from another process when building the providers map .'''
salt . utils . crypt . reinit_crypto ( ) cloud = Cloud ( data [ 'opts' ] ) try : with salt . utils . context . func_globals_inject ( cloud . clouds [ data [ 'fun' ] ] , __active_provider_name__ = ':' . join ( [ data [ 'alias' ] , data [ 'driver' ] ] ) ) : return ( data [ 'alias' ] , data [ 'driver' ] , salt...
def react_to_event ( self , event ) : """Check whether the given event should be handled Checks , whether the editor widget has the focus and whether the selected state machine corresponds to the state machine of this editor . : param event : GTK event object : return : True if the event should be handled ,...
if not react_to_event ( self . view , self . view . editor , event ) : return False if not rafcon . gui . singleton . state_machine_manager_model . selected_state_machine_id == self . model . state_machine . state_machine_id : return False return True
def removeKeyButtonEvent ( self , buttons = [ ] ) : """\~english Remove key button event callbacks @ param buttons : an array of button Ids . eg . [ 12,13,15 , . . . ] \~chinese 移除按键事件回调 @ param buttons : 按钮ID数组 。 例如 : [ 12,13,15 , . . . ]"""
for i in range ( 0 , len ( buttons ) - 1 ) : GPIO . remove_event_detect ( buttons [ i ] )
def sitemap ( request ) : """Return a sitemap xml file for search engines ."""
xml = Sitemap ( ) author = request . matchdict . get ( 'from_id' ) if author is not None : match = "AND '{}' = authors[1]" . format ( author ) else : match = '' with db_connect ( ) as db_connection : with db_connection . cursor ( ) as cursor : cursor . execute ( """SELECT ident_h...
def strings ( self ) : """Return lat / lon as strings ."""
return [ toString ( self . lat , LAT ) , toString ( self . lon , LON ) ]
def get_activate_url ( self , card_id , outer_str = None ) : """获取开卡插件 Url , 内含调用开卡插件所需的参数 详情请参考 https : / / mp . weixin . qq . com / wiki ? id = mp1499332673 _ Unm7V : param card _ id : 会员卡的card _ id : param outer _ str : 渠道值 , 用于统计本次领取的渠道参数 : return : 内含调用开卡插件所需的参数的 Url"""
return self . _post ( 'card/membercard/activate/geturl' , data = { 'card_id' : card_id , 'outer_str' : outer_str , } , result_processor = lambda x : x [ 'url' ] , )
def set_timelimit ( self , timelimit ) : """Limits are specified with the format hh : mm : ss ( hours : minutes : seconds )"""
super ( ) . set_timelimit ( timelimit ) self . qparams [ "wall_clock_limit" ] = qu . time2loadlever ( timelimit )
def _unpack ( struct , bc , offset = 0 ) : """returns the unpacked data tuple , and the next offset past the unpacked data"""
return struct . unpack_from ( bc , offset ) , offset + struct . size
def _saferepr ( obj ) : """Get a safe repr of an object for assertion error messages . The assertion formatting ( util . format _ explanation ( ) ) requires newlines to be escaped since they are a special character for it . Normally assertion . util . format _ explanation ( ) does this but for a custom repr...
repr = py . io . saferepr ( obj ) if py . builtin . _istext ( repr ) : t = py . builtin . text else : t = py . builtin . bytes return repr . replace ( t ( "\n" ) , t ( "\\n" ) )
def create_deamon ( cmd , shell = False , root = False ) : """Usage : Create servcice process ."""
try : if root : cmd . insert ( 0 , 'sudo' ) LOG . info ( cmd ) subproc = subprocess . Popen ( cmd , shell = shell , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) return subproc . pid except Exception as e : LOG . error ( e ) raise
def CreateRetryTask ( self ) : """Creates a new task to retry a previously abandoned task . The retry task will have a new identifier but most of the attributes will be a copy of the previously abandoned task . Returns : Task : a task to retry a previously abandoned task ."""
retry_task = Task ( session_identifier = self . session_identifier ) retry_task . file_entry_type = self . file_entry_type retry_task . merge_priority = self . merge_priority retry_task . path_spec = self . path_spec retry_task . storage_file_size = self . storage_file_size self . has_retry = True return retry_task
def get_alternatives ( self ) : """Get the spelling alternatives for search terms . Returns : A dict in form : { < search term > : { ' count ' : < number of times the searh term occurs in the Storage > , ' words ' : { < an alternative > : { ' count ' : < number of times the alternative occurs in the Storage...
return dict ( [ ( alternatives . find ( 'to' ) . text , { 'count' : int ( alternatives . find ( 'count' ) . text ) , 'words' : dict ( [ ( word . text , word . attrib ) for word in alternatives . findall ( 'word' ) ] ) } ) for alternatives in self . _content . find ( 'alternatives_list' ) . findall ( 'alternatives' ) ] ...
def reopen ( self ) : """Reopens the file . Usually used after it has been rotated ."""
# Read any remaining content in the file and store it in a buffer . self . _read ( ) # Close it to ensure we don ' t leak file descriptors self . _close ( ) # Reopen the file . try : self . _open ( self . _path , skip_to_end = False ) return True except OSError : # If opening fails , it was probably deleted . ...
def _format_summary_node ( self , task_class ) : """Format a section node containg a summary of a Task class ' s key APIs ."""
modulename = task_class . __module__ classname = task_class . __name__ nodes = [ ] nodes . append ( self . _format_class_nodes ( task_class ) ) nodes . append ( self . _format_config_nodes ( modulename , classname ) ) methods = ( 'run' , 'runDataRef' ) for method in methods : if hasattr ( task_class , method ) : ...
def _get_wds ( self , indices ) : """Gets weight decays for indices . Returns 0 for non - weights if the name of weights are provided for ` _ _ init _ _ ` . Parameters indices : list of int Indices of weights . Returns wds : list of float Weight decays for those indices ."""
wds = [ self . wd for _ in indices ] for i , index in enumerate ( indices ) : if index in self . param_dict : wds [ i ] *= self . param_dict [ index ] . wd_mult elif index in self . wd_mult : wds [ i ] *= self . wd_mult [ index ] elif index in self . idx2name : wds [ i ] *= self . wd...
def update ( self , issue , ** kwargs ) : """Update an existing issue on Github . For JSON data returned by Github refer : https : / / developer . github . com / v3 / issues / # edit - an - issue : param issue : object existing issue : returns : dict of JSON data returned by Github . : rtype : ` dict `"""
url = issue . url response = self . session . patch ( url , json . dumps ( kwargs ) ) assert response . status_code == 200 return json . loads ( response . content )
def parse_pseudo_dir ( self , sel , m , has_selector ) : """Parse pseudo direction ."""
value = ct . SEL_DIR_LTR if util . lower ( m . group ( 'dir' ) ) == 'ltr' else ct . SEL_DIR_RTL sel . flags |= value has_selector = True return has_selector
def get_plain_logname ( base_name , root_dir , enable_json ) : """we nest all plain logs to prevent double log shipping"""
if enable_json : nested_dir = os . path . join ( root_dir , 'plain' ) if os . path . exists ( root_dir ) and not os . path . exists ( nested_dir ) : os . mkdir ( nested_dir ) root_dir = nested_dir return os . path . join ( root_dir , '{}.log' . format ( base_name ) )
def get_response ( self , ** kwargs ) : """Returns a Response object containing this object ' s status code and a JSON object containing the key " error " with the value of this object ' s error message in the body . Keyword args are passed through to the Response ."""
return Response ( json . dumps ( { "error" : self . message } ) , # pylint : disable = exception - message - attribute status_code = self . status_code , content_type = "application/json" , charset = "utf-8" , ** kwargs )
def check_flags ( self , ds ) : '''Check the flag _ values , flag _ masks and flag _ meanings attributes for variables to ensure they are CF compliant . CF § 3.5 The attributes flag _ values , flag _ masks and flag _ meanings are intended to make variables that contain flag values self describing . Status c...
ret_val = [ ] for name in cfutil . get_flag_variables ( ds ) : variable = ds . variables [ name ] flag_values = getattr ( variable , "flag_values" , None ) flag_masks = getattr ( variable , "flag_masks" , None ) valid_flags_var = TestCtx ( BaseCheck . HIGH , self . section_titles [ '3.5' ] ) # Check...
def clean_weights ( self , cutoff = 1e-4 , rounding = 5 ) : """Helper method to clean the raw weights , setting any weights whose absolute values are below the cutoff to zero , and rounding the rest . : param cutoff : the lower bound , defaults to 1e - 4 : type cutoff : float , optional : param rounding : n...
if not isinstance ( rounding , int ) or rounding < 1 : raise ValueError ( "rounding must be a positive integer" ) clean_weights = self . weights . copy ( ) clean_weights [ np . abs ( clean_weights ) < cutoff ] = 0 if rounding is not None : clean_weights = np . round ( clean_weights , rounding ) return dict ( zi...
def set_change ( name , change ) : '''Sets the time at which the password expires ( in seconds since the UNIX epoch ) . See ` ` man 8 usermod ` ` on NetBSD and OpenBSD or ` ` man 8 pw ` ` on FreeBSD . A value of ` ` 0 ` ` sets the password to never expire . CLI Example : . . code - block : : bash salt '...
pre_info = info ( name ) if change == pre_info [ 'change' ] : return True if __grains__ [ 'kernel' ] == 'FreeBSD' : cmd = [ 'pw' , 'user' , 'mod' , name , '-f' , change ] else : cmd = [ 'usermod' , '-f' , change , name ] __salt__ [ 'cmd.run' ] ( cmd , python_shell = False ) post_info = info ( name ) if post...
def get_gene_count_tab ( infile , bc_getter = None ) : '''Yields the counts per umi for each gene bc _ getter : method to get umi ( plus optionally , cell barcode ) from read , e . g get _ umi _ read _ id or get _ umi _ tag TODO : ADD FOLLOWING OPTION skip _ regex : skip genes matching this regex . Useful t...
gene = None counts = collections . Counter ( ) for line in infile : values = line . strip ( ) . split ( "\t" ) assert len ( values ) == 2 , "line: %s does not contain 2 columns" % line read_id , assigned_gene = values if assigned_gene != gene : if gene : yield gene , counts g...
def _map_or_apply ( input_layer , op , * args , ** kwargs ) : """Map op across the input if it is a sequence ; otherwise apply it . Note : This takes a keyword argument ` right _ ` to right apply the op to this input . The name is chosen to limit conflicts with other keyword arguments . Args : input _ layer...
# Name is special because it can also set the name scope . kwargs . pop ( 'name' ) right = kwargs . pop ( 'right_' , False ) if input_layer . is_sequence ( ) : if right : args += ( input_layer , ) else : args = ( ( input_layer , ) + args ) result = [ op ( * x , ** kwargs ) for x in _zip_with...
def image_bytes ( b , filename = None , inline = 1 , width = 'auto' , height = 'auto' , preserve_aspect_ratio = None ) : """Return a bytes string that displays image given by bytes b in the terminal If filename = None , the filename defaults to " Unnamed file " width and height are strings , following the forma...
if preserve_aspect_ratio is None : if width != 'auto' and height != 'auto' : preserve_aspect_ratio = False else : preserve_aspect_ratio = True data = { 'name' : base64 . b64encode ( ( filename or 'Unnamed file' ) . encode ( 'utf-8' ) ) . decode ( 'ascii' ) , 'inline' : inline , 'size' : len ( b ...
def setup ( ) : """Configure the settings ( this happens as a side effect of accessing the first setting ) , configure logging and populate the app registry ."""
from trading_bots . bots import bots from trading_bots . conf import settings bots . populate ( settings . installed_bots )
def encode_gen ( line , encoding = "utf-8" ) : """Encodes all Unicode strings in line to encoding Parameters line : Iterable of Unicode strings \t Date to be encoded encoding : String , defaults to " utf - 8" \t Target encoding"""
for ele in line : if isinstance ( ele , types . UnicodeType ) : yield ele . encode ( encoding ) else : yield ele
def dump_opcodes ( opmap ) : """Utility for dumping opcodes"""
op2name = { } for k in opmap . keys ( ) : op2name [ opmap [ k ] ] = k for i in sorted ( op2name . keys ( ) ) : print ( "%-3s %s" % ( str ( i ) , op2name [ i ] ) )