signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_tensors_inputs ( placeholders , tensors , names ) : """Args : placeholders ( list [ Tensor ] ) : tensors ( list [ Tensor ] ) : list of tf . Tensor names ( list [ str ] ) : names matching the given tensors Returns : list [ Tensor ] : inputs to used for the tower function , with the corresponding ...
assert len ( tensors ) == len ( names ) , "Input tensors {} and input names {} have different length!" . format ( tensors , names ) ret = copy . copy ( placeholders ) placeholder_names = [ p . name for p in placeholders ] for name , tensor in zip ( names , tensors ) : tensorname = get_op_tensor_name ( name ) [ 1 ] ...
def main ( ) : """NAME change _ case _ magic . py DESCRIPTION picks out key and converts to upper or lower case SYNTAX change _ case _ magic . py [ command line options ] OPTIONS - h prints help message and quits - f FILE : specify input magic format file - F FILE : specify output magic format fil...
dir_path = "./" change = 'l' if '-WD' in sys . argv : ind = sys . argv . index ( '-WD' ) dir_path = sys . argv [ ind + 1 ] if '-h' in sys . argv : print ( main . __doc__ ) sys . exit ( ) if '-f' in sys . argv : ind = sys . argv . index ( '-f' ) magic_file = dir_path + '/' + sys . argv [ ind + 1 ...
def vesting_balance_withdraw ( self , vesting_id , amount = None , account = None , ** kwargs ) : """Withdraw vesting balance : param str vesting _ id : Id of the vesting object : param bitshares . amount . Amount Amount : to withdraw ( " all " if not provided " ) : param str account : ( optional ) the acco...
if not account : if "default_account" in self . config : account = self . config [ "default_account" ] if not account : raise ValueError ( "You need to provide an account" ) account = Account ( account , blockchain_instance = self ) if not amount : obj = Vesting ( vesting_id , blockchain_instance = ...
def make_regression ( func , n_samples = 100 , n_features = 1 , bias = 0.0 , noise = 0.0 , random_state = None ) : """Make dataset for a regression problem . Examples > > > f = lambda x : 0.5 * x + np . sin ( 2 * x ) > > > X , y = make _ regression ( f , bias = . 5 , noise = 1 . , random _ state = 1) > > > ...
generator = check_random_state ( random_state ) X = generator . randn ( n_samples , n_features ) # unpack the columns of X y = func ( * X . T ) + bias if noise > 0.0 : y += generator . normal ( scale = noise , size = y . shape ) return X , y
def getargspec ( obj ) : """An improved inspect . getargspec . Has a slightly different return value from the default getargspec . Returns a tuple of : required , optional , args , kwargs list , dict , bool , bool Required is a list of required named arguments . Optional is a dictionary mapping optional...
argnames , varargs , varkw , _defaults = None , None , None , None if inspect . isfunction ( obj ) or inspect . ismethod ( obj ) : argnames , varargs , varkw , _defaults = inspect . getargspec ( obj ) elif inspect . isclass ( obj ) : if inspect . ismethoddescriptor ( obj . __init__ ) : argnames , vararg...
def create_dir ( entry , section , domain , output ) : """Create the output directory for the entry if needed ."""
full_output_dir = os . path . join ( output , section , domain , entry [ 'assembly_accession' ] ) try : os . makedirs ( full_output_dir ) except OSError as err : if err . errno == errno . EEXIST and os . path . isdir ( full_output_dir ) : pass else : raise return full_output_dir
def convert ( self , targetunits ) : """Set new user unit , for either wavelength or flux . This effectively converts the spectrum wavelength or flux to given unit . Note that actual data are always kept in internal units ( Angstrom and ` ` photlam ` ` ) , and only converted to user units by : meth : ` getA...
nunits = units . Units ( targetunits ) if nunits . isFlux : self . fluxunits = nunits else : self . waveunits = nunits
def clone ( self , repo , ref , deps = ( ) ) : """Clone the given url and checkout the specific ref ."""
if os . path . isdir ( repo ) : repo = os . path . abspath ( repo ) def clone_strategy ( directory ) : env = git . no_git_env ( ) def _git_cmd ( * args ) : cmd_output ( 'git' , * args , cwd = directory , env = env ) _git_cmd ( 'init' , '.' ) _git_cmd ( 'remote' , 'add' , 'origin' , repo ) ...
def _custom_response_edit ( self , method , url , headers , body , response ) : """This method allows a service to edit a response . If you want to do this , you probably really want to use _ edit _ mock _ response - this method will operate on Live resources ."""
if self . get_implementation ( ) . is_mock ( ) : delay = self . get_setting ( "MOCKDATA_DELAY" , 0.0 ) time . sleep ( delay ) self . _edit_mock_response ( method , url , headers , body , response )
def tsp ( points , start = 0 ) : """Find an ordering of points where each is visited and the next point is the closest in euclidean distance , and if there are multiple points with equal distance go to an arbitrary one . Assumes every point is visitable from every other point , i . e . the travelling sale...
# points should be float points = np . asanyarray ( points , dtype = np . float64 ) if len ( points . shape ) != 2 : raise ValueError ( 'points must be (n, dimension)!' ) # start should be an index start = int ( start ) # a mask of unvisited points by index unvisited = np . ones ( len ( points ) , dtype = np . bool...
def _run_dragonpy_cli ( self , * args ) : """Run DragonPy cli with given args . Add " - - verbosity " from GUI ."""
verbosity = self . frame_settings . var_verbosity . get ( ) verbosity_no = VERBOSITY_DICT2 [ verbosity ] log . debug ( "Verbosity: %i (%s)" % ( verbosity_no , verbosity ) ) args = ( "--verbosity" , "%s" % verbosity_no # " - - log _ list " , # " - - log " , # " dragonpy . components . cpu6809,40 " , # " dragonpy . Drago...
def pso ( self , n_particles = 10 , n_iterations = 10 , lowerLimit = - 0.2 , upperLimit = 0.2 , threadCount = 1 , mpi = False , print_key = 'default' ) : """returns the best fit for the lense model on catalogue basis with particle swarm optimizer"""
init_pos = self . chain . get_args ( self . chain . kwargs_data_init ) num_param = self . chain . num_param lowerLimit = [ lowerLimit ] * num_param upperLimit = [ upperLimit ] * num_param if mpi is True : pso = MpiParticleSwarmOptimizer ( self . chain , lowerLimit , upperLimit , n_particles , threads = 1 ) else : ...
def refresh ( self ) : """refreshes a service"""
params = { "f" : "json" } uURL = self . _url + "/refresh" res = self . _get ( url = uURL , param_dict = params , securityHandler = self . _securityHandler , proxy_port = self . _proxy_port , proxy_url = self . _proxy_url ) self . __init ( ) return res
def run_fsm ( self , name , command , events , transitions , timeout , max_transitions = 20 ) : """Wrap the FSM code ."""
self . ctrl . send_command ( command ) return FSM ( name , self , events , transitions , timeout = timeout , max_transitions = max_transitions ) . run ( )
def convert_model_to_external_data ( model , all_tensors_to_one_file = True , location = None ) : # type : ( ModelProto , bool , Optional [ Text ] ) - > None """call to set all tensors as external data . save _ model saves all the tensors data as external data after calling this function . @ params model : Mode...
if all_tensors_to_one_file : file_name = Text ( uuid . uuid1 ( ) ) if location : file_name = location for tensor in _get_all_tensors ( model ) : set_external_data ( tensor , file_name ) else : for tensor in _get_all_tensors ( model ) : set_external_data ( tensor , tensor . name )
def OutputDocumentFor ( objs , apply_theme = None , always_new = False ) : '''Find or create a ( possibly temporary ) Document to use for serializing Bokeh content . Typical usage is similar to : . . code - block : : python with OutputDocumentFor ( models ) : ( docs _ json , [ render _ item ] ) = standalo...
# Note : Comms handling relies on the fact that the new _ doc returned # has models with the same IDs as they were started with if not isinstance ( objs , collections_abc . Sequence ) or len ( objs ) == 0 or not all ( isinstance ( x , Model ) for x in objs ) : raise ValueError ( "OutputDocumentFor expects a sequenc...
def _common_scan ( self , values_function , cursor = '0' , match = None , count = 10 , key = None ) : """Common scanning skeleton . : param key : optional function used to identify what ' match ' is applied to"""
if count is None : count = 10 cursor = int ( cursor ) count = int ( count ) if not count : raise ValueError ( 'if specified, count must be > 0: %s' % count ) values = values_function ( ) if cursor + count >= len ( values ) : # we reached the end , back to zero result_cursor = 0 else : result_cursor = cu...
def are_symmetrically_equivalent ( self , sites1 , sites2 , symm_prec = 1e-3 ) : """Given two sets of PeriodicSites , test if they are actually symmetrically equivalent under this space group . Useful , for example , if you want to test if selecting atoms 1 and 2 out of a set of 4 atoms are symmetrically the ...
def in_sites ( site ) : for test_site in sites1 : if test_site . is_periodic_image ( site , symm_prec , False ) : return True return False for op in self : newsites2 = [ PeriodicSite ( site . species , op . operate ( site . frac_coords ) , site . lattice ) for site in sites2 ] for si...
def can_resume ( self ) : """Test if the generator can be resumed , i . e . is not running or closed ."""
# TOCHECK relies on generator . gi _ frame # Equivalent to ` inspect . getgeneratorstate ( self . generator ) in # ( inspect . GEN _ CREATED , inspect . GEN _ SUSPENDED ) ` , # which is only available starting 3.2. gen = self . generator return ( gen is not None and not gen . gi_running and gen . gi_frame is not None )
def Instance ( expected , message = "Not an instance of {}" ) : """Creates a validator that checks if the given value is an instance of ` ` expected ` ` . A custom message can be specified with ` ` message ` ` ."""
@ wraps ( Instance ) def built ( value ) : if not isinstance ( value , expected ) : raise Error ( message . format ( expected . __name__ ) ) return value return built
def get_slotname ( slot , host = None , admin_username = None , admin_password = None ) : '''Get the name of a slot number in the chassis . slot The number of the slot for which to obtain the name . host The chassis host . admin _ username The username used to access the chassis . admin _ password T...
slots = list_slotnames ( host = host , admin_username = admin_username , admin_password = admin_password ) # The keys for this dictionary are strings , not integers , so convert the # argument to a string slot = six . text_type ( slot ) return slots [ slot ] [ 'slotname' ]
def getinputfile ( self , outputfile , loadmetadata = True , client = None , requiremetadata = False ) : """Grabs one input file for the specified output filename ( raises a KeyError exception if there is no such output , StopIteration if there are no input files for it ) . Shortcut for getinputfiles ( )"""
if isinstance ( outputfile , CLAMOutputFile ) : outputfilename = str ( outputfile ) . replace ( os . path . join ( self . projectpath , 'output/' ) , '' ) else : outputfilename = outputfile if outputfilename not in self : raise KeyError ( "No such outputfile " + outputfilename ) try : return next ( self...
def encode ( self , b64 = False , always_bytes = True ) : """Encode the packet for transmission ."""
if self . binary and not b64 : encoded_packet = six . int2byte ( self . packet_type ) else : encoded_packet = six . text_type ( self . packet_type ) if self . binary and b64 : encoded_packet = 'b' + encoded_packet if self . binary : if b64 : encoded_packet += base64 . b64encode ( self . ...
def _parse ( self , html ) : """Parse given string as HTML and return it ' s etree representation ."""
if self . _has_body_re . search ( html ) : tree = lxml . html . document_fromstring ( html ) . find ( './/body' ) self . has_body = True else : tree = lxml . html . fragment_fromstring ( html , create_parent = self . _root_tag ) if tree . tag != self . _root_tag : # ensure the root element exists even if no...
def _show_list_message ( resolved_config ) : """Show the message for when a user has passed in - - list ."""
# Show what ' s available . supported_programs = util . get_list_of_all_supported_commands ( resolved_config ) msg_line_1 = 'Legend: ' msg_line_2 = ( ' ' + util . FLAG_ONLY_CUSTOM + ' only custom files' ) msg_line_3 = ( ' ' + util . FLAG_CUSTOM_AND_DEFAULT + ' custom and default files' ) msg_line_4 = ' ' + ' ...
def destroy ( self ) : """从服务器上删除这个对象 : rtype : None"""
if not self . id : return client . delete ( '/classes/{0}/{1}' . format ( self . _class_name , self . id ) , self . _flags )
def kmer_counter ( seq , k = 4 ) : """Return a sequence of all the unique substrings ( k - mer or q - gram ) within a short ( < 128 symbol ) string Used for algorithms like UniqTag for genome unique identifier locality sensitive hashing . jellyfish is a C implementation of k - mer counting If seq is a string ...
if isinstance ( seq , basestring ) : return Counter ( generate_kmers ( seq , k ) )
def _tile_read ( src_dst , bounds , tilesize , indexes = None , nodata = None , resampling_method = "bilinear" ) : """Read data and mask . Attributes src _ dst : rasterio . io . DatasetReader rasterio . io . DatasetReader object bounds : list Mercator tile bounds ( left , bottom , right , top ) tilesize...
if isinstance ( indexes , int ) : indexes = [ indexes ] elif isinstance ( indexes , tuple ) : indexes = list ( indexes ) vrt_params = dict ( add_alpha = True , crs = "epsg:3857" , resampling = Resampling [ resampling_method ] ) vrt_transform , vrt_width , vrt_height = get_vrt_transform ( src_dst , bounds ) vrt_...
def crop_to_ratio ( self ) : "Get crop coordinates and perform the crop if we get any ."
crop_box = self . get_crop_box ( ) if not crop_box : return crop_box = self . center_important_part ( crop_box ) iw , ih = self . image . size # see if we want to crop something from outside of the image out_of_photo = min ( crop_box [ 0 ] , crop_box [ 1 ] ) < 0 or crop_box [ 2 ] > iw or crop_box [ 3 ] > ih # check...
def write_psts ( self , prefix , existing_jco = None , noptmax = None ) : """write parameter and optionally observation realizations to a series of pest control files Parameters prefix : str pest control file prefix existing _ jco : str filename of an existing jacobian matrix to add to the pest + + op...
self . log ( "writing realized pest control files" ) # get a copy of the pest control file pst = self . pst . get ( par_names = self . pst . par_names , obs_names = self . pst . obs_names ) if noptmax is not None : pst . control_data . noptmax = noptmax pst . control_data . noptmax = noptmax if existing_jco is ...
def _check_is_max_context ( doc_spans , cur_span_index , position ) : """Check if this is the ' max context ' doc span for the token ."""
# Because of the sliding window approach taken to scoring documents , a single # token can appear in multiple documents . E . g . # Doc : the man went to the store and bought a gallon of milk # Span A : the man went to the # Span B : to the store and bought # Span C : and bought a gallon of # Now the word ' bought ' wi...
def check_permissions ( self , request ) : """Retrieves the controlled object and perform the permissions check ."""
obj = ( hasattr ( self , 'get_controlled_object' ) and self . get_controlled_object ( ) or hasattr ( self , 'get_object' ) and self . get_object ( ) or getattr ( self , 'object' , None ) ) user = request . user # Get the permissions to check perms = self . get_required_permissions ( self ) # Check permissions has_permi...
def importRootCertificate ( self , alias , rootCACertificate ) : """This operation imports a certificate authority ( CA ) ' s root and intermediate certificates into the keystore ."""
url = self . _url + "/sslcertificates/importRootOrIntermediate" files = { } files [ 'rootCACertificate' ] = rootCACertificate params = { "f" : "json" , "alias" : alias } return self . _post ( url = url , param_dict = params , securityHandler = self . _securityHandler , files = files , proxy_url = self . _proxy_url , pr...
def count_children ( obj , type = None ) : """Return the number of children of obj , optionally restricting by class"""
if type is None : return len ( obj ) else : # there doesn ' t appear to be any hdf5 function for getting this # information without inspecting each child , which makes this somewhat # slow return sum ( 1 for x in obj if obj . get ( x , getclass = True ) is type )
def preview_unmount ( self ) : """Returns a list of all commands that would be executed if the : func : ` unmount ` method would be called . Note : any system changes between calling this method and calling : func : ` unmount ` aren ' t listed by this command ."""
commands = [ ] for mountpoint in self . find_bindmounts ( ) : commands . append ( 'umount {0}' . format ( mountpoint ) ) for mountpoint in self . find_mounts ( ) : commands . append ( 'umount {0}' . format ( mountpoint ) ) commands . append ( 'rm -Rf {0}' . format ( mountpoint ) ) for vgname , pvname in sel...
def printer ( data , depth = 0 ) : """Prepare data for printing . : param data : a data value that will be processed by method : param int depth : recurrency indicator , to maintain proper indent : returns : string with formatted config : rtype : str"""
indent = _INDENT * depth config_string = '' if not depth else ':\n' if isinstance ( data , dict ) : for key , val in data . items ( ) : line = '{0}{1}' . format ( indent , key ) values = printer ( val , depth + 1 ) if not values . count ( '\n' ) : values = ': {0}' . format ( valu...
def get_protocol ( handle : Handle , want_v2 : bool ) -> Protocol : """Make a Protocol instance for the given handle . Each transport can have a preference for using a particular protocol version . This preference is overridable through ` TREZOR _ PROTOCOL _ V1 ` environment variable , which forces the librar...
force_v1 = int ( os . environ . get ( "TREZOR_PROTOCOL_V1" , 1 ) ) if want_v2 and not force_v1 : return ProtocolV2 ( handle ) else : return ProtocolV1 ( handle )
def delete_session ( sid_s ) : """Delete entries in the data - and kvsessionstore with the given sid _ s . On a successful deletion , the flask - kvsession store returns 1 while the sqlalchemy datastore returns None . : param sid _ s : The session ID . : returns : ` ` 1 ` ` if deletion was successful ."""
# Remove entries from sessionstore _sessionstore . delete ( sid_s ) # Find and remove the corresponding SessionActivity entry with db . session . begin_nested ( ) : SessionActivity . query . filter_by ( sid_s = sid_s ) . delete ( ) return 1
def fix_pdf ( pdf_file , destination ) : """Fix malformed pdf files when data are present after ' % % EOF ' . . note : : Originally from sciunto , https : / / github . com / sciunto / tear - pages : param pdfFile : PDF filepath : param destination : destination"""
tmp = tempfile . NamedTemporaryFile ( ) with open ( tmp . name , 'wb' ) as output : with open ( pdf_file , "rb" ) as fh : for line in fh : output . write ( line ) if b'%%EOF' in line : break shutil . copy ( tmp . name , destination )
def as_text ( self ) : '''Fetch and render all regions For search and test purposes just a prototype'''
from leonardo . templatetags . leonardo_tags import _render_content request = get_anonymous_request ( self ) content = '' try : for region in [ region . key for region in self . _feincms_all_regions ] : content += '' . join ( _render_content ( content , request = request , context = { } ) for content in get...
def Parse ( self , cmd , args , stdout , stderr , return_val , time_taken , knowledge_base ) : """Parse the yum repolist output ."""
_ = stderr , time_taken , args , knowledge_base # Unused . self . CheckReturn ( cmd , return_val ) output = iter ( stdout . decode ( "utf-8" ) . splitlines ( ) ) repo_regexes = { "name" : self . _re_compile ( "Repo-name" ) , "revision" : self . _re_compile ( "Repo-revision" ) , "last_update" : self . _re_compile ( "Rep...
def get_package_dir ( self , package ) : """Returns the directory , relative to the top of the source distribution , where package ` ` package ` ` should be found ( at least according to the : attr : ` package _ dir ` option , if any ) . Copied from : meth : ` distutils . command . build _ py . get _ package ...
path = package . split ( '.' ) if not self . package_dir : if path : return os . path . join ( * path ) return '' tail = [ ] while path : try : pdir = self . package_dir [ '.' . join ( path ) ] except KeyError : tail . insert ( 0 , path [ - 1 ] ) del path [ - 1 ] else...
def run_band_structure ( self , paths , with_eigenvectors = False , with_group_velocities = False , is_band_connection = False , path_connections = None , labels = None , is_legacy_plot = False ) : """Run phonon band structure calculation . Parameters paths : List of array _ like Sets of qpoints that can be p...
if self . _dynamical_matrix is None : msg = ( "Dynamical matrix has not yet built." ) raise RuntimeError ( msg ) if with_group_velocities : if self . _group_velocity is None : self . _set_group_velocity ( ) group_velocity = self . _group_velocity else : group_velocity = None self . _band_str...
def writeline ( self , data ) : """Writes data to serial port . : param data : Data to write : return : Nothing : raises : IOError if SerialException occurs ."""
try : if self . ch_mode : data += "\n" parts = split_by_n ( data , self . ch_mode_chunk_size ) for split_str in parts : self . port . write ( split_str . encode ( ) ) time . sleep ( self . ch_mode_ch_delay ) else : self . port . write ( ( data + "\n" ) . e...
def QA_fetch_stock_block_adv ( code = None , blockname = None , collections = DATABASE . stock_block ) : '''返回板块 ❌ : param code : : param blockname : : param collections : 默认数据库 stock _ block : return : QA _ DataStruct _ Stock _ block'''
if code is not None and blockname is None : # 返回这个股票代码所属的板块 data = pd . DataFrame ( [ item for item in collections . find ( { 'code' : { '$in' : code } } ) ] ) data = data . drop ( [ '_id' ] , axis = 1 ) return QA_DataStruct_Stock_block ( data . set_index ( [ 'blockname' , 'code' ] , drop = True ) . drop_du...
def get_search_schema ( self , schema ) : """Fetch a Solr schema from Yokozuna . : param schema : name of Solr schema : type schema : string : rtype dict"""
if not self . yz_wm_schema : raise NotImplementedError ( "Search 2.0 administration is not " "supported for this version" ) url = self . search_schema_path ( schema ) # Run the request . . . status , _ , body = self . _request ( 'GET' , url ) if status == 200 : result = { } result [ 'name' ] = schema re...
def replace_by_key ( pif , key , subs , new_key = None , remove = False ) : """Replace values that match a key Deeply traverses the pif object , looking for ` key ` and replacing values in accordance with ` subs ` . If ` new _ key ` is set , the replaced values are assigned to that key . If ` remove ` is ` ...
if not new_key : new_key = key remove = False orig = pif . as_dictionary ( ) new = _recurse_replace ( orig , to_camel_case ( key ) , to_camel_case ( new_key ) , subs , remove ) return pypif . pif . loads ( json . dumps ( new ) )
def _format_metric_name ( self , m_name , cfunc ) : '''Format a cacti metric name into a Datadog - friendly name'''
try : aggr = CFUNC_TO_AGGR [ cfunc ] except KeyError : aggr = cfunc . lower ( ) try : m_name = CACTI_TO_DD [ m_name ] if aggr != 'avg' : m_name += '.{}' . format ( aggr ) return m_name except KeyError : return "cacti.{}.{}" . format ( m_name . lower ( ) , aggr )
def check_page ( fn ) : "Decorator to protect drawing methods"
@ wraps ( fn ) def wrapper ( self , * args , ** kwargs ) : if not self . page and not kwargs . get ( 'split_only' ) : self . error ( "No page open, you need to call add_page() first" ) else : return fn ( self , * args , ** kwargs ) return wrapper
def sys_prefix ( self ) : """The prefix run inside the context of the environment : return : The python prefix inside the environment : rtype : : data : ` sys . prefix `"""
command = [ self . python , "-c" "import sys; print(sys.prefix)" ] c = vistir . misc . run ( command , return_object = True , block = True , nospin = True , write_to_stdout = False ) sys_prefix = vistir . compat . Path ( vistir . misc . to_text ( c . out ) . strip ( ) ) . as_posix ( ) return sys_prefix
def get_connection ( cls , pid , connection ) : """Return the specified : class : ` ~ queries . pool . Connection ` from the pool . : param str pid : The pool ID : param connection : The connection to return for : type connection : psycopg2 . extensions . connection : rtype : queries . pool . Connection""...
with cls . _lock : return cls . _pools [ pid ] . connection_handle ( connection )
def str2int ( self , str_value ) : """Conversion class name string = > integer ."""
str_value = tf . compat . as_text ( str_value ) if self . _str2int : return self . _str2int [ str_value ] # No names provided , try to integerize failed_parse = False try : int_value = int ( str_value ) except ValueError : failed_parse = True if failed_parse or not 0 <= int_value < self . _num_classes : ...
def encode ( val ) : """Encode a string assuming the encoding is UTF - 8. : param : a unicode or bytes object : returns : bytes"""
if isinstance ( val , ( list , tuple ) ) : # encode a list or tuple of strings return [ encode ( v ) for v in val ] elif isinstance ( val , str ) : return val . encode ( 'utf-8' ) else : # assume it was an already encoded object return val
def connect_gs ( gs_access_key_id = None , gs_secret_access_key = None , ** kwargs ) : """@ type gs _ access _ key _ id : string @ param gs _ access _ key _ id : Your Google Cloud Storage Access Key ID @ type gs _ secret _ access _ key : string @ param gs _ secret _ access _ key : Your Google Cloud Storage Se...
from boto . gs . connection import GSConnection return GSConnection ( gs_access_key_id , gs_secret_access_key , ** kwargs )
def get_option_names ( self ) : """returns a list of fully qualified option names . returns : a list of strings representing the Options in the source Namespace list . Each item will be fully qualified with dot delimited Namespace names ."""
return [ x for x in self . option_definitions . keys_breadth_first ( ) if isinstance ( self . option_definitions [ x ] , Option ) ]
def __fa_process_sequence ( self , sequence , avoid , initial_state , execution_state , trace_current , next_addr ) : """Process a REIL sequence . Args : sequence ( ReilSequence ) : A REIL sequence to process . avoid ( list ) : List of address to avoid . initial _ state : Initial state . execution _ state...
# TODO : Process execution intra states . ip = sequence . address next_ip = None while ip : # Fetch next instruction in the sequence . try : instr = sequence . fetch ( ip ) except ReilSequenceInvalidAddressError : # At this point , ip should be a native instruction address , therefore # the index sh...
def increase_and_check_counter ( self ) : '''increase counter by one and check whether a period is end'''
self . counter += 1 self . counter %= self . period if not self . counter : return True else : return False
def save_conf ( fn = None ) : """Save current configuration to file as YAML If not given , uses current config directory , ` ` confdir ` ` , which can be set by INTAKE _ CONF _ DIR ."""
if fn is None : fn = cfile ( ) try : os . makedirs ( os . path . dirname ( fn ) ) except ( OSError , IOError ) : pass with open ( fn , 'w' ) as f : yaml . dump ( conf , f )
def answerShippingQuery ( self , shipping_query_id , ok , shipping_options = None , error_message = None ) : """See : https : / / core . telegram . org / bots / api # answershippingquery"""
p = _strip ( locals ( ) ) return self . _api_request ( 'answerShippingQuery' , _rectify ( p ) )
def _determine_tool ( files ) : """Yields tuples in the form of ( linker file , tool the file links for"""
for file in files : linker_ext = file . split ( '.' ) [ - 1 ] if "sct" in linker_ext or "lin" in linker_ext : yield ( str ( file ) , "uvision" ) elif "ld" in linker_ext : yield ( str ( file ) , "make_gcc_arm" ) elif "icf" in linker_ext : yield ( str ( file ) , "iar_arm" )
def decrypt ( self , encryption_key , iv , encrypted_data ) : """Decrypt encrypted subtitle data @ param int subtitle _ id @ param str iv @ param str encrypted _ data @ return str"""
logger . info ( 'Decrypting subtitles with length (%d bytes), key=%r' , len ( encrypted_data ) , encryption_key ) return zlib . decompress ( aes_decrypt ( encryption_key , iv , encrypted_data ) )
def _ISO8601_to_UNIXtime ( iso ) : """Converts an ISO8601 - formatted string in the format ` ` YYYY - MM - DD HH : MM : SS + 00 ` ` to the correspondant UNIXtime : param iso : the ISO8601 - formatted string : type iso : string : returns : an int UNIXtime : raises : * TypeError * when bad argument types ar...
try : d = datetime . strptime ( iso , '%Y-%m-%d %H:%M:%S+00' ) except ValueError : raise ValueError ( __name__ + ": bad format for input ISO8601 string, ' \ 'should have been: YYYY-MM-DD HH:MM:SS+00" ) return _datetime_to_UNIXtime ( d )
def update ( self , weight = values . unset , priority = values . unset , enabled = values . unset , friendly_name = values . unset , sip_url = values . unset ) : """Update the OriginationUrlInstance : param unicode weight : The value that determines the relative load the URI should receive compared to others wit...
return self . _proxy . update ( weight = weight , priority = priority , enabled = enabled , friendly_name = friendly_name , sip_url = sip_url , )
def collect_garbage ( ) : '''Completely removed all currently ' uninstalled ' packages in the nix store . Tells the user how many store paths were removed and how much space was freed . : return : How much space was freed and how many derivations were removed : rtype : str . . warning : : This is a destru...
cmd = _nix_collect_garbage ( ) cmd . append ( '--delete-old' ) out = _run ( cmd ) return out [ 'stdout' ] . splitlines ( )
def openflow_controller_connection_address_active_controller_vrf ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) openflow_controller = ET . SubElement ( config , "openflow-controller" , xmlns = "urn:brocade.com:mgmt:brocade-openflow" ) controller_name_key = ET . SubElement ( openflow_controller , "controller-name" ) controller_name_key . text = kwargs . pop ( 'controller_name' ) connection_addre...
def add_timedelta ( self , delta ) : """Add timedelta duration to the instance . : param delta : The timedelta instance : type delta : datetime . timedelta : rtype : Time"""
if delta . days : raise TypeError ( "Cannot add timedelta with days to Time." ) return self . add ( seconds = delta . seconds , microseconds = delta . microseconds )
def get_game ( self , name ) : """Get the game instance for a game name : param name : the name of the game : type name : : class : ` str ` : returns : the game instance : rtype : : class : ` models . Game ` | None : raises : None"""
games = self . search_games ( query = name , live = False ) for g in games : if g . name == name : return g
def main ( ) : """Main method ."""
args = parse_cmd_arguments ( ) html_file = args . file try : json . loads ( args . add_tags or '{}' ) json . loads ( args . exc_tags or '{}' ) except ValueError : print ( '\033[91m' + 'Invalid json string: please provide a valid json ' 'string e.g {}' . format ( '\'{"img": "data-url"}\'' ) + '\033[0m' ) ...
def main ( gi , ranges ) : """Print the features of the genbank entry given by gi . If ranges is non - emtpy , only print features that include the ranges . gi : either a hit from a BLAST record , in the form ' gi | 63148399 | gb | DQ011818.1 | ' or a gi number ( 63148399 in this example ) . ranges : a poss...
# TODO : Make it so we can pass a ' db ' argument to getSequence . record = getSequence ( gi ) if record is None : print ( "Looks like you're offline." ) sys . exit ( 3 ) else : printed = set ( ) if ranges : for ( start , end ) in ranges : for index , feature in enumerate ( record . ...
def _split_variables ( variables ) : """Split variables into always passed ( std ) and specified ( file ) . We always pass some variables to each step but need to explicitly define file and algorithm variables so they can be linked in as needed ."""
file_vs = [ ] std_vs = [ ] for v in variables : cur_type = v [ "type" ] while isinstance ( cur_type , dict ) : if "items" in cur_type : cur_type = cur_type [ "items" ] else : cur_type = cur_type [ "type" ] if ( cur_type in [ "File" , "null" , "record" ] or ( isinstanc...
def update_metric ( self , metric , labels , pre_sliced = False ) : """Update evaluation metric with label and current outputs ."""
for current_exec , ( texec , islice ) in enumerate ( zip ( self . train_execs , self . slices ) ) : if not pre_sliced : labels_slice = [ label [ islice ] for label in labels ] else : labels_slice = labels [ current_exec ] metric . update ( labels_slice , texec . outputs )
def sent_tokenize ( self , text , ** kwargs ) : """NLTK ' s sentence tokenizer ( currently PunktSentenceTokenizer ) . Uses an unsupervised algorithm to build a model for abbreviation words , collocations , and words that start sentences , then uses that to find sentence boundaries ."""
sentences = self . sent_tok . tokenize ( text , realign_boundaries = kwargs . get ( "realign_boundaries" , True ) ) return sentences
def cli_certify_complex_dict ( config , schema , key_certifier , value_certifier , allow_extra , include_collections , value , ) : """Console script for certify _ dict ."""
schema = load_json_pickle ( schema , config ) key_certifier = create_certifier ( load_json_pickle ( key_certifier , config ) ) value_certifier = create_certifier ( load_json_pickle ( value_certifier , config ) ) execute_cli_command ( 'dict' , config , lambda x : load_json_pickle ( x , config ) , certify_dict , value , ...
def data_and_labels ( self ) : """Dataset features and labels in a matrix form for learning . Also returns sample _ ids in the same order . Returns data _ matrix : ndarray 2D array of shape [ num _ samples , num _ features ] with features corresponding row - wise to sample _ ids labels : ndarray Array...
sample_ids = np . array ( self . keys ) label_dict = self . labels matrix = np . full ( [ self . num_samples , self . num_features ] , np . nan ) labels = np . full ( [ self . num_samples , 1 ] , np . nan ) for ix , sample in enumerate ( sample_ids ) : matrix [ ix , : ] = self . __data [ sample ] labels [ ix ] ...
def get_num_shards ( num_samples : int , samples_per_shard : int , min_num_shards : int ) -> int : """Returns the number of shards . : param num _ samples : Number of training data samples . : param samples _ per _ shard : Samples per shard . : param min _ num _ shards : Minimum number of shards . : return ...
return max ( int ( math . ceil ( num_samples / samples_per_shard ) ) , min_num_shards )
def PopupGetFile ( message , default_path = '' , default_extension = '' , save_as = False , file_types = ( ( "ALL Files" , "*.*" ) , ) , no_window = False , size = ( None , None ) , button_color = None , background_color = None , text_color = None , icon = DEFAULT_WINDOW_ICON , font = None , no_titlebar = False , grab_...
global _my_windows if no_window : if _my_windows . NumOpenWindows : root = tk . Toplevel ( ) else : root = tk . Tk ( ) try : root . attributes ( '-alpha' , 0 ) # hide window while building it . makes for smoother ' paint ' except : pass if save_as : fi...
def _send_packet ( self , sid , pkt ) : """Send a Socket . IO packet to a client ."""
encoded_packet = pkt . encode ( ) if isinstance ( encoded_packet , list ) : binary = False for ep in encoded_packet : self . eio . send ( sid , ep , binary = binary ) binary = True else : self . eio . send ( sid , encoded_packet , binary = False )
def pmap ( func , args , processes = None , callback = lambda * _ , ** __ : None , ** kwargs ) : """pmap ( func , args , processes = None , callback = do _ nothing , * * kwargs ) Parallel equivalent of ` ` map ( func , args ) ` ` , with the additional ability of providing keyword arguments to func , and a callb...
if processes is 1 : results = [ ] for arg in args : result = func ( arg , ** kwargs ) results . append ( result ) callback ( result ) return results else : with Pool ( ) if processes is None else Pool ( processes ) as p : results = [ p . apply_async ( func , ( arg , ) , k...
def extender ( path = None , cache = None ) : """A context that temporarily extends sys . path and reverts it after the context is complete ."""
old_path = sys . path [ : ] extend ( path , cache = None ) try : yield finally : sys . path = old_path
def check_for_completion ( self ) : """Check once for completion of the job and return completion status and result if it has completed . If the job completed in error , an : exc : ` ~ zhmcclient . HTTPError ` exception is raised . Returns : : A tuple ( status , result ) with : * status ( : term : ` str...
job_result_obj = self . session . get ( self . uri ) job_status = job_result_obj [ 'status' ] if job_status == 'complete' : self . session . delete ( self . uri ) op_status_code = job_result_obj [ 'job-status-code' ] if op_status_code in ( 200 , 201 ) : op_result_obj = job_result_obj . get ( 'job-re...
def _fw_rule_update ( self , drvr_name , data ) : """Firewall Rule update routine . Function to decode the updated rules and call routines that in turn calls the device routines to update rules ."""
LOG . debug ( "FW Update %s" , data ) tenant_id = data . get ( 'firewall_rule' ) . get ( 'tenant_id' ) fw_rule = data . get ( 'firewall_rule' ) rule = self . _fw_rule_decode_store ( data ) rule_id = fw_rule . get ( 'id' ) if tenant_id not in self . fwid_attr or not ( self . fwid_attr [ tenant_id ] . is_rule_present ( r...
def pretty_xml ( data ) : """Return a pretty formated xml"""
parsed_string = minidom . parseString ( data . decode ( 'utf-8' ) ) return parsed_string . toprettyxml ( indent = '\t' , encoding = 'utf-8' )
def get_or_create_home_repo ( reset = False ) : """Check to make sure we never operate with a non - existing local repo"""
dosetup = True if os . path . exists ( ONTOSPY_LOCAL ) : dosetup = False if reset : import shutil var = input ( "Delete the local library and all of its contents? (y/n) " ) if var == "y" : shutil . rmtree ( ONTOSPY_LOCAL ) dosetup = True else : ...
def close_file ( self ) : """Closes the editor file . : return : Method success . : rtype : bool"""
if not self . is_modified ( ) : LOGGER . debug ( "> Closing '{0}' file." . format ( self . __file ) ) self . file_closed . emit ( ) return True choice = message_box . message_box ( "Warning" , "Warning" , "'{0}' document has been modified!\nWould you like to save your changes?" . format ( self . get_file_sh...
def _create_update_tracking_related_event ( instance ) : """Create a TrackingEvent and TrackedFieldModification for an UPDATE event for each related model ."""
events = { } # Create a dict mapping related model field to modified fields for field , related_fields in instance . _tracked_related_fields . items ( ) : if not isinstance ( instance . _meta . get_field ( field ) , ManyToManyField ) : if isinstance ( instance . _meta . get_field ( field ) , ForeignKey ) : ...
def is_expired_token ( self , client ) : """For a given client will test whether or not the token has expired . This is for testing a client object and does not look up from client _ id . You can use _ get _ client _ from _ cache ( ) to lookup a client from client _ id ."""
if 'expires' not in client : return True expires = dateutil . parser . parse ( client [ 'expires' ] ) if expires < datetime . datetime . now ( ) : return True return False
def utf8 ( value ) : r"""Check that the string is UTF - 8 . Returns an encode bytestring . > > > utf8 ( b ' \ xe0 ' ) # doctest : + ELLIPSIS Traceback ( most recent call last ) : ValueError : Not UTF - 8 : . . ."""
try : if isinstance ( value , bytes ) : return value . decode ( 'utf-8' ) else : return value except Exception : raise ValueError ( 'Not UTF-8: %r' % value )
def fetch_job ( config ) : '''Fetch any available work from the OpenSubmit server and return an according job object . Returns None if no work is available . Errors are reported by this function directly .'''
url = "%s/jobs/?Secret=%s&UUID=%s" % ( config . get ( "Server" , "url" ) , config . get ( "Server" , "secret" ) , config . get ( "Server" , "uuid" ) ) try : # Fetch information from server result = urlopen ( url ) headers = result . info ( ) logger . debug ( "Raw job data: " + str ( result . headers ) . rep...
def apply ( self , word , ctx = None ) : """ignore ctx information right now"""
return Sequential . in_sequence ( word , AdjacentVowels . uyir_letters , AdjacentVowels . reason )
def split_for_transport ( orig_pkt , transport_proto ) : """Split an IP ( v6 ) packet in the correct location to insert an ESP or AH header . @ param orig _ pkt : the packet to split . Must be an IP or IPv6 packet @ param transport _ proto : the IPsec protocol number that will be inserted at the split posit...
# force resolution of default fields to avoid padding errors header = orig_pkt . __class__ ( raw ( orig_pkt ) ) next_hdr = header . payload nh = None if header . version == 4 : nh = header . proto header . proto = transport_proto header . remove_payload ( ) del header . chksum del header . len r...
def read_config ( contents ) : """Reads pylintrc config into native ConfigParser object . Args : contents ( str ) : The contents of the file containing the INI config . Returns : ConfigParser . ConfigParser : The parsed configuration ."""
file_obj = io . StringIO ( contents ) config = six . moves . configparser . ConfigParser ( ) config . readfp ( file_obj ) return config
def _calc_q_h0 ( n , x , h , nt , n_jobs = 1 , verbose = 0 , random_state = None ) : """Calculate q under the null hypothesis of whiteness ."""
rng = check_random_state ( random_state ) par , func = parallel_loop ( _calc_q_statistic , n_jobs , verbose ) q = par ( func ( rng . permutation ( x . T ) . T , h , nt ) for _ in range ( n ) ) return np . array ( q )
def timesince ( d , now = None , pos = True , flag = False ) : """pos means calculate which direction , pos = True , now - d , pos = False , d - now flag means return value type , True will return since , message and Flase return message > > > d = datetime . datetime ( 2009 , 10 , 1 , 12 , 23 , 19) > > > time...
if not d : if flag : return 0 , '' else : return '' chunks = ( ( 60 * 60 * 24 * 365 , lambda n : ungettext ( 'year' , 'years' , n ) ) , ( 60 * 60 * 24 * 30 , lambda n : ungettext ( 'month' , 'months' , n ) ) , ( 60 * 60 * 24 * 7 , lambda n : ungettext ( 'week' , 'weeks' , n ) ) , ( 60 * 60 * 24 ...
def qdc ( self ) : '''Return the qdc tag for the term'''
start_tag = '' . join ( ( '<' , self . get_term_display ( ) . lower ( ) , ' q="' , self . qualifier , '">' , ) ) if self . qualifier else '' . join ( ( '<' , self . get_term_display ( ) . lower ( ) , '>' , ) ) qdc = '' . join ( ( start_tag , saxutils . escape ( self . content ) , '</' , self . get_term_display ( ) . lo...
def tpl_single_send ( self , param , must = [ APIKEY , MOBILE , TPL_ID , TPL_VALUE ] ) : '''指定模板单发 only v2 deprecated 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 mobile String 是 接收的手机号 ( 针对国际短信 , mobile参数会自动格式化到E . 164格式 , 可能会造成传入mobile参数跟后续的状态报告中的号码不一致 。 E . 164格式说明 , 参见 : h...
r = self . verify_param ( param , must ) if not r . is_succ ( ) : return r h = CommonResultHandler ( lambda rsp : { VERSION_V2 : rsp } [ self . version ( ) ] ) return self . path ( 'tpl_single_send.json' ) . post ( param , h , r )
def accept_reject_or_neither ( self , url , parent_page = None ) : '''Returns ` True ` ( accepted ) , ` False ` ( rejected ) , or ` None ` ( no decision ) . ` None ` usually means rejected , unless ` max _ hops _ off ` comes into play .'''
if not isinstance ( url , urlcanon . ParsedUrl ) : url = urlcanon . semantic ( url ) if not url . scheme in ( b'http' , b'https' ) : # XXX doesn ' t belong here maybe ( where ? worker ignores unknown # schemes ? ) return False try_parent_urls = [ ] if parent_page : try_parent_urls . append ( urlcanon . sema...
def get_transactions ( self , include_investment = False ) : """Returns the transaction data as a Pandas DataFrame ."""
assert_pd ( ) s = StringIO ( self . get_transactions_csv ( include_investment = include_investment ) ) s . seek ( 0 ) df = pd . read_csv ( s , parse_dates = [ 'Date' ] ) df . columns = [ c . lower ( ) . replace ( ' ' , '_' ) for c in df . columns ] df . category = ( df . category . str . lower ( ) . replace ( 'uncatego...
def config_add ( self , key , value , ** kwargs ) : """Add a value to a key . Returns a list of warnings Conda may have emitted ."""
cmd_list = [ 'config' , '--add' , key , value ] cmd_list . extend ( self . _setup_config_from_kwargs ( kwargs ) ) return self . _call_and_parse ( cmd_list , abspath = kwargs . get ( 'abspath' , True ) , callback = lambda o , e : o . get ( 'warnings' , [ ] ) )
def linear_deform ( template , displacement , out = None ) : """Linearized deformation of a template with a displacement field . The function maps a given template ` ` I ` ` and a given displacement field ` ` v ` ` to the new function ` ` x - - > I ( x + v ( x ) ) ` ` . Parameters template : ` DiscreteLpEle...
image_pts = template . space . points ( ) for i , vi in enumerate ( displacement ) : image_pts [ : , i ] += vi . asarray ( ) . ravel ( ) values = template . interpolation ( image_pts . T , out = out , bounds_check = False ) return values . reshape ( template . space . shape )
def state_reachable ( subsystem ) : """Return whether a state can be reached according to the network ' s TPM ."""
# If there is a row ` r ` in the TPM such that all entries of ` r - state ` are # between - 1 and 1 , then the given state has a nonzero probability of being # reached from some state . # First we take the submatrix of the conditioned TPM that corresponds to # the nodes that are actually in the subsystem . . . tpm = su...