signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def tgcanrecruit ( self , region = None ) : """Whether the nation will receive a recruitment telegram . Useful in conjunction with the Telegrams API . Parameters region : str Name of the region you are recruiting for . Returns an : class : ` ApiQuery ` of bool"""
params = { 'from' : normalize ( region ) } if region is not None else { } @ api_query ( 'tgcanrecruit' , ** params ) async def result ( _ , root ) : return bool ( int ( root . find ( 'TGCANRECRUIT' ) . text ) ) return result ( self )
def get_s3_client ( ) : """A DRY place to make sure AWS credentials in settings override environment based credentials . Boto3 will fall back to : http : / / boto3 . readthedocs . io / en / latest / guide / configuration . html"""
session_kwargs = { } if hasattr ( settings , 'AWS_ACCESS_KEY_ID' ) : session_kwargs [ 'aws_access_key_id' ] = settings . AWS_ACCESS_KEY_ID if hasattr ( settings , 'AWS_SECRET_ACCESS_KEY' ) : session_kwargs [ 'aws_secret_access_key' ] = settings . AWS_SECRET_ACCESS_KEY boto3 . setup_default_session ( ** session_...
def expand ( self , new_size ) : """expand the LUN to a new size : param new _ size : new size in bytes . : return : the old size"""
ret = self . size_total resp = self . modify ( size = new_size ) resp . raise_if_err ( ) return ret
def cleanup_images ( self ) : """Remove all images created by CONU and remove all hidden images ( cached dowloads ) : return : None"""
for image in self . list_images ( ) : if CONU_ARTIFACT_TAG in image . name : image . rmi ( ) # remove all hidden images - > causes trouble when pulling the image again run_cmd ( [ "machinectl" , "--no-pager" , "clean" ] )
def _read ( self , max_tries = 40 ) : """- read the bit stream from HX711 and convert to an int value . - validates the acquired data : param max _ tries : how often to try to get data : type max _ tries : int : return raw data : rtype : int"""
# start by setting the pd _ sck to false GPIO . output ( self . _pd_sck , False ) # init the counter ready_counter = 0 # loop until HX711 is ready # halt when maximum number of tires is reached while self . _ready ( ) is False : time . sleep ( 0.01 ) # sleep for 10 ms before next try ready_counter += 1 ...
def on_event ( self , event ) : '''pass events to the parent'''
state = self . state if isinstance ( event , wx . MouseEvent ) : self . on_mouse_event ( event ) if isinstance ( event , wx . KeyEvent ) : self . on_key_event ( event ) if ( isinstance ( event , wx . MouseEvent ) and not event . ButtonIsDown ( wx . MOUSE_BTN_ANY ) and event . GetWheelRotation ( ) == 0 ) : # don...
def captureRegion ( self , filename , x , y , w , h ) : """Save a region of the current display to filename"""
log . debug ( 'captureRegion %s' , filename ) return self . _capture ( filename , x , y , x + w , y + h )
def _handle_result_line ( self , sline ) : """Parses the data line and adds to the dictionary . : param sline : a split data line to parse : returns : the number of rows to jump and parse the next data line or return the code error - 1"""
# If there are less values founded than headers , it ' s an error if len ( sline ) != len ( self . _columns ) : self . err ( "One data line has the wrong number of items" ) return - 1 result = '' name = '' for idx , val in enumerate ( sline ) : if self . _columns [ idx ] == 'Analyte Name' : name = v...
def create_footprints_gdf ( polygon = None , north = None , south = None , east = None , west = None , footprint_type = 'building' , retain_invalid = False ) : """Get footprint data from OSM then assemble it into a GeoDataFrame . Parameters polygon : shapely Polygon or MultiPolygon geographic shape to fetch t...
responses = osm_footprints_download ( polygon , north , south , east , west , footprint_type ) # list of polygons to removed at the end of the process pop_list = [ ] vertices = { } for response in responses : for result in response [ 'elements' ] : if 'type' in result and result [ 'type' ] == 'node' : ...
def _GetCachedEntryDataTypeMap ( self , format_type , value_data , cached_entry_offset ) : """Determines the cached entry data type map . Args : format _ type ( int ) : format type . value _ data ( bytes ) : value data . cached _ entry _ offset ( int ) : offset of the first cached entry data relative to t...
if format_type not in self . _SUPPORTED_FORMAT_TYPES : raise errors . ParseError ( 'Unsupported format type: {0:d}' . format ( format_type ) ) data_type_map_name = '' if format_type == self . _FORMAT_TYPE_XP : data_type_map_name = 'appcompatcache_cached_entry_xp_32bit' elif format_type in ( self . _FORMAT_TYPE_...
def exec ( self , globals = None , locals = None ) : """Execute simple code blocks . Do not attempt this on modules or other blocks where you have imports as they won ' t work . Instead write the code to a file and use runpy . run _ path ( )"""
if locals is None : locals = { } builtins . exec ( self . to_code ( ) , globals , locals ) return locals
def close ( self ) : """Close the connection to the SMTP server"""
self . is_closed = True try : self . smtp . quit ( ) except ( TypeError , AttributeError , smtplib . SMTPServerDisconnected ) : pass
def poll_while ( self , state , interval = 2 ) : """GET / : login / machines / : id : param state : ( assumed ) current state : type state : : py : class : ` basestring ` : param interval : pause in seconds between polls : type interval : : py : class : ` int ` Convenience method that continuously polls t...
while self . status ( ) == state : time . sleep ( interval )
def stickers_translate_get ( self , api_key , s , ** kwargs ) : """Sticker Translate Endpoint The translate API draws on search , but uses the Giphy ` special sauce ` to handle translating from one vocabulary to another . In this case , words and phrases to GIFs . This method makes a synchronous HTTP request by...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'callback' ) : return self . stickers_translate_get_with_http_info ( api_key , s , ** kwargs ) else : ( data ) = self . stickers_translate_get_with_http_info ( api_key , s , ** kwargs ) return data
def ssml_break ( self , strength = None , time = None , ** kwargs ) : """Create a < Break > element : param strength : Set a pause based on strength : param time : Set a pause to a specific length of time in seconds or milliseconds , available values : [ number ] s , [ number ] ms : param kwargs : additional ...
return self . nest ( SsmlBreak ( strength = strength , time = time , ** kwargs ) )
def _remove_multicast_group ( self , datapath , outport , dst ) : """remove flow entries about the group and send a LEAVE message if exists ."""
ofproto = datapath . ofproto parser = datapath . ofproto_parser dpid = datapath . id self . _send_event ( EventMulticastGroupStateChanged ( MG_GROUP_REMOVED , dst , outport , [ ] ) ) self . _del_flow_entry ( datapath , outport , dst ) for port in self . _to_hosts [ dpid ] [ dst ] [ 'ports' ] : self . _del_flow_entr...
def deprecated ( reason , replacement , gone_in , issue = None ) : # type : ( str , Optional [ str ] , Optional [ str ] , Optional [ int ] ) - > None """Helper to deprecate existing functionality . reason : Textual reason shown to the user about why this functionality has been deprecated . replacement : T...
# Construct a nice message . # This is purposely eagerly formatted as we want it to appear as if someone # typed this entire message out . message = "DEPRECATION: " + reason if replacement is not None : message += " A possible replacement is {}." . format ( replacement ) if issue is not None : url = "https://gi...
def align ( fastq_file , pair_file , index_dir , names , align_dir , data ) : """Perform piped alignment of fastq input files , generating sorted , deduplicated BAM ."""
umi_ext = "-cumi" if "umi_bam" in data else "" out_file = os . path . join ( align_dir , "{0}-sort{1}.bam" . format ( dd . get_sample_name ( data ) , umi_ext ) ) num_cores = data [ "config" ] [ "algorithm" ] . get ( "num_cores" , 1 ) rg_info = "rgid={rg} rgpl={pl} rgpu={pu} rgsm={sample}" . format ( ** names ) pair_fil...
def setRepoData ( self , searchString , category = "" , extension = "" , math = False , game = False , searchFiles = False ) : """Call this function with all the settings to use for future operations on a repository , must be called FIRST"""
self . searchString = searchString self . category = category self . math = math self . game = game self . searchFiles = searchFiles self . extension = extension
def _split_generators ( self , dl_manager ) : """Returns SplitGenerators ."""
image_tar_file = os . path . join ( dl_manager . manual_dir , self . builder_config . file_name ) if not tf . io . gfile . exists ( image_tar_file ) : # The current celebahq generation code depends on a concrete version of # pillow library and cannot be easily ported into tfds . msg = "You must download the dataset...
def pop_trigger ( data ) : """Pops trigger and trigger args from a given dict ."""
trigger_name = data . pop ( 'trigger' ) trigger_args = { } if trigger_name == 'date' : trigger_arg_names = ( 'run_date' , 'timezone' ) elif trigger_name == 'interval' : trigger_arg_names = ( 'weeks' , 'days' , 'hours' , 'minutes' , 'seconds' , 'start_date' , 'end_date' , 'timezone' ) elif trigger_name == 'cron'...
def _annotation_handler ( ion_type , length , ctx ) : """Handles annotations . ` ` ion _ type ` ` is ignored ."""
_ , self = yield self_handler = _create_delegate_handler ( self ) if ctx . annotations is not None : raise IonException ( 'Annotation cannot be nested in annotations' ) # We have to replace our context for annotations specifically to encapsulate the limit ctx = ctx . derive_container_context ( length , add_depth = ...
def convert_sed_cols ( tab ) : """Cast SED column names to lowercase ."""
# Update Column names for colname in list ( tab . columns . keys ( ) ) : newname = colname . lower ( ) newname = newname . replace ( 'dfde' , 'dnde' ) if tab . columns [ colname ] . name == newname : continue tab . columns [ colname ] . name = newname return tab
def set_kw_typeahead_input ( cls ) : """Map the typeahead input to remote dataset ."""
# get reference to parent element parent_id = cls . intput_el . parent . id if "typeahead" not in parent_id . lower ( ) : parent_id = cls . intput_el . parent . parent . id window . make_keyword_typeahead_tag ( "#" + parent_id , join ( settings . API_PATH , "kw_list.json" ) , cls . on_select_callback , )
def bash_rule ( bash , hostnames ) : """Cluster rule to process bash and hostname info ` ` bash ` ` and ` ` hostnames ` ` are Pandas DataFrames for the facts collected for each host in the cluster . See https : / / pandas . pydata . org / pandas - docs / stable / api . html # dataframe for information on av...
if isinstance ( bash , dict ) : return make_fail ( 'bash_rule' , error_message = "Run this rule with a cluster archive" ) return make_pass ( 'bash_rule' , bash = bash , hostname = hostnames )
def _setup_chassis ( self ) : """Sets up the router with the corresponding chassis ( create slots and insert default adapters ) ."""
if self . _chassis == "3620" : self . _create_slots ( 2 ) elif self . _chassis == "3640" : self . _create_slots ( 4 ) elif self . _chassis == "3660" : self . _create_slots ( 7 ) self . _slots [ 0 ] = Leopard_2FE ( )
def make_phase_space_list ( ) : """Extract all the phase space information ( due to ` ` EMIT ` ` commands in the input file ) , and create a list of PhaseSpace objects . The primary purpose of this is for interactive explorations of the data produced during Pynac simulations ."""
with open ( 'dynac.short' ) as f : data_str = '' . join ( line for line in f . readlines ( ) ) data_str_array = data_str . split ( 'beam (emit card)' ) [ 1 : ] data_str_matrix = [ [ j . strip ( ) . split ( ) for j in i ] for i in [ chunk . split ( '\n' ) [ 1 : 8 ] for chunk in data_str_array ] ] return ...
def uni ( key ) : '''as a crutch , we allow str - type keys , but they really should be unicode .'''
if isinstance ( key , str ) : logger . warn ( 'assuming utf8 on: %r' , key ) return unicode ( key , 'utf-8' ) elif isinstance ( key , unicode ) : return key else : raise NonUnicodeKeyError ( key )
def force_type ( cls , response , environ = None ) : """Enforce that the WSGI response is a response object of the current type . Werkzeug will use the : class : ` BaseResponse ` internally in many situations like the exceptions . If you call : meth : ` get _ response ` on an exception you will get back a reg...
if not isinstance ( response , BaseResponse ) : if environ is None : raise TypeError ( "cannot convert WSGI application into response" " objects without an environ" ) response = BaseResponse ( * _run_wsgi_app ( response , environ ) ) response . __class__ = cls return response
def load_backends_and_plugins ( plugins , working_set , backends , build_configuration = None ) : """Load named plugins and source backends : param list < str > plugins : Plugins to load ( see ` load _ plugins ` ) . Plugins are loaded after backends . : param WorkingSet working _ set : A pkg _ resources . Wor...
build_configuration = build_configuration or BuildConfiguration ( ) load_build_configuration_from_source ( build_configuration , backends ) load_plugins ( build_configuration , plugins or [ ] , working_set ) return build_configuration
def multigrid ( bounds , points_count ) : """Generates a multidimensional lattice : param bounds : box constraints : param points _ count : number of points per dimension ."""
if len ( bounds ) == 1 : return np . linspace ( bounds [ 0 ] [ 0 ] , bounds [ 0 ] [ 1 ] , points_count ) . reshape ( points_count , 1 ) x_grid_rows = np . meshgrid ( * [ np . linspace ( b [ 0 ] , b [ 1 ] , points_count ) for b in bounds ] ) x_grid_columns = np . vstack ( [ x . flatten ( order = 'F' ) for x in x_gri...
async def reply_document ( self , document : typing . Union [ base . InputFile , base . String ] , caption : typing . Union [ base . String , None ] = None , disable_notification : typing . Union [ base . Boolean , None ] = None , reply_markup = None , reply = True ) -> Message : """Use this method to send general ...
return await self . bot . send_document ( chat_id = self . chat . id , document = document , caption = caption , disable_notification = disable_notification , reply_to_message_id = self . message_id if reply else None , reply_markup = reply_markup )
def size ( self , minimum : int = 1 , maximum : int = 100 ) -> str : """Get size of file . : param minimum : Maximum value . : param maximum : Minimum value . : return : Size of file . : Example : 56 kB"""
num = self . random . randint ( minimum , maximum ) unit = self . random . choice ( [ 'bytes' , 'kB' , 'MB' , 'GB' , 'TB' ] ) return '{num} {unit}' . format ( num = num , unit = unit , )
def load_targets ( explanatory_rasters ) : """Parameters explanatory _ rasters : List of Paths to GDAL rasters containing explanatory variables Returns expl : Array of explanatory variables raster _ info : dict of raster info"""
explanatory_raster_arrays = [ ] aff = None shape = None crs = None for raster in explanatory_rasters : logger . debug ( raster ) with rasterio . open ( raster ) as src : ar = src . read ( 1 ) # TODO band num ? # Save or check the geotransform if not aff : aff = src . ...
def dAbr_dV ( dSf_dVa , dSf_dVm , dSt_dVa , dSt_dVm , Sf , St ) : """Partial derivatives of squared flow magnitudes w . r . t voltage . Computes partial derivatives of apparent power w . r . t active and reactive power flows . Partial derivative must equal 1 for lines with zero flow to avoid division by zero ...
dAf_dPf = spdiag ( 2 * Sf . real ( ) ) dAf_dQf = spdiag ( 2 * Sf . imag ( ) ) dAt_dPt = spdiag ( 2 * St . real ( ) ) dAt_dQt = spdiag ( 2 * St . imag ( ) ) # Partial derivative of apparent power magnitude w . r . t voltage # phase angle . dAf_dVa = dAf_dPf * dSf_dVa . real ( ) + dAf_dQf * dSf_dVa . imag ( ) dAt_dVa = d...
def _compute_example_enumerated_subtypes ( self , label ) : """Analogous to : meth : ` _ compute _ example _ flat _ helper ` but for structs with enumerated subtypes ."""
assert label in self . _raw_examples , label example = self . _raw_examples [ label ] example_field = list ( example . fields . values ( ) ) [ 0 ] for subtype_field in self . get_enumerated_subtypes ( ) : if subtype_field . name == example_field . name : data_type = subtype_field . data_type break r...
def get_start_of_line_position ( self , after_whitespace = False ) : """Relative position for the start of this line ."""
if after_whitespace : current_line = self . current_line return len ( current_line ) - len ( current_line . lstrip ( ) ) - self . cursor_position_col else : return - len ( self . current_line_before_cursor )
def _deploy_and_remember ( self , contract_name : str , arguments : List , deployed_contracts : 'DeployedContracts' , ) -> Contract : """Deploys contract _ name with arguments and store the result in deployed _ contracts ."""
receipt = self . deploy ( contract_name , arguments ) deployed_contracts [ 'contracts' ] [ contract_name ] = _deployed_data_from_receipt ( receipt = receipt , constructor_arguments = arguments , ) return self . web3 . eth . contract ( abi = self . contract_manager . get_contract_abi ( contract_name ) , address = deploy...
def instantiate_by_name ( self , object_name ) : """Instantiate object from the environment , possibly giving some extra arguments"""
if object_name not in self . instances : instance = self . instantiate_from_data ( self . environment [ object_name ] ) self . instances [ object_name ] = instance return instance else : return self . instances [ object_name ]
def parse_imethodresponse ( self , tup_tree ) : """Parse the tuple for an IMETHODRESPONE Element . I . e . < ! ELEMENT IMETHODRESPONSE ( ERROR | ( IRETURNVALUE ? , PARAMVALUE * ) ) > < ! ATTLIST IMETHODRESPONSE % CIMName ; >"""
self . check_node ( tup_tree , 'IMETHODRESPONSE' , ( 'NAME' , ) ) return ( name ( tup_tree ) , attrs ( tup_tree ) , self . list_of_various ( tup_tree , ( 'ERROR' , 'IRETURNVALUE' , 'PARAMVALUE' ) ) )
def pwm_array2pssm_array ( arr , background_probs = DEFAULT_BASE_BACKGROUND ) : """Convert pwm array to pssm array"""
b = background_probs2array ( background_probs ) b = b . reshape ( [ 1 , 4 , 1 ] ) return np . log ( arr / b ) . astype ( arr . dtype )
def _init_exons ( self ) : """Sets a list of position intervals for each exon . Only coding regions as defined by thickStart and thickEnd are kept . Exons are stored in the self . exons attribute ."""
exon_starts = [ self . chrom_start + int ( s ) for s in self . bed_tuple . blockStarts . strip ( ',' ) . split ( ',' ) ] exon_sizes = list ( map ( int , self . bed_tuple . blockSizes . strip ( ',' ) . split ( ',' ) ) ) # get chromosome intervals exons = [ ( exon_starts [ i ] , exon_starts [ i ] + exon_sizes [ i ] ) for...
def html_job_status ( job_name , job_type , refresh_interval , html_on_running , html_on_success ) : """create html representation of status of a job ( long running operation ) . Args : job _ name : the full name of the job . job _ type : type of job . Can be ' local ' or ' cloud ' . refresh _ interval : ho...
_HTML_TEMPLATE = """ <div class="jobstatus" id="%s"> </div> <script> require(['datalab/job', 'datalab/element!%s', 'base/js/events', 'datalab/style!/nbextensions/datalab/job.css'], function(job, dom, events) { job.render(dom, events, '%s', '%s', %s, '%s', '%s'); } ...
def get_tilt ( cont ) : """Compute tilt of raw contour relative to channel axis Parameters cont : ndarray or list of ndarrays of shape ( N , 2) A 2D array that holds the contour of an event ( in pixels ) e . g . obtained using ` mm . contour ` where ` mm ` is an instance of ` RTDCBase ` . The first and se...
if isinstance ( cont , np . ndarray ) : # If cont is an array , it is not a list of contours , # because contours can have different lengths . cont = [ cont ] ret_list = False else : ret_list = True length = len ( cont ) tilt = np . zeros ( length , dtype = float ) * np . nan for ii in range ( length ) : ...
def delete_review ( self , pub_name , ext_name , review_id ) : """DeleteReview . [ Preview API ] Deletes a review : param str pub _ name : Name of the pubilsher who published the extension : param str ext _ name : Name of the extension : param long review _ id : Id of the review which needs to be updated"""
route_values = { } if pub_name is not None : route_values [ 'pubName' ] = self . _serialize . url ( 'pub_name' , pub_name , 'str' ) if ext_name is not None : route_values [ 'extName' ] = self . _serialize . url ( 'ext_name' , ext_name , 'str' ) if review_id is not None : route_values [ 'reviewId' ] = self ....
def scoped_timeline ( self , * id , ** kwargs ) : """Returns the most recent promotable Tweets created by the specified Twitter user ."""
self . _validate_loaded ( ) params = { 'user_id' : id } params . update ( kwargs ) resource = self . SCOPED_TIMELINE . format ( id = self . id ) response = Request ( self . client , 'get' , resource , params = params ) . perform ( ) return response . body [ 'data' ]
def iter_tag_users ( self , tag_id , first_user_id = None ) : """获取标签下粉丝openid列表 : return : 返回一个迭代器 , 可以用for进行循环 , 得到openid 使用示例 : : from wechatpy import WeChatClient client = WeChatClient ( ' appid ' , ' secret ' ) for openid in client . tag . iter _ tag _ users ( 0 ) : print ( openid )"""
while True : follower_data = self . get_tag_users ( tag_id , first_user_id ) if 'data' not in follower_data : return for openid in follower_data [ 'data' ] [ 'openid' ] : yield openid first_user_id = follower_data . get ( 'next_openid' ) if not first_user_id : return
def selection_dialog ( self , courses ) : """opens a curses / picker based interface to select courses that should be downloaded ."""
selected = list ( filter ( lambda x : x . course . id in self . _settings [ "selected_courses" ] , courses ) ) selection = Picker ( title = "Select courses to download" , options = courses , checked = selected ) . getSelected ( ) if selection : self . _settings [ "selected_courses" ] = list ( map ( lambda x : x . c...
def containerIsRunning ( name_or_id ) : '''Check if container with the given name or ID ( str ) is running . No side effects . Idempotent . Returns True if running , False if not .'''
require_str ( "name_or_id" , name_or_id ) try : container = getContainer ( name_or_id ) # Refer to the latest status list here : https : / / docs . docker . com / engine / # api / v1.33 / # operation / ContainerList if container : if container . status == 'created' : return False ...
def read_tx_body ( ptr , tx ) : """Returns { ' ins ' : [ . . . ] , ' outs ' : [ . . . ] }"""
_obj = { "ins" : [ ] , "outs" : [ ] , 'locktime' : None } # number of inputs ins = read_var_int ( ptr , tx ) # all inputs for i in range ( ins ) : _obj [ "ins" ] . append ( { "outpoint" : { "hash" : read_bytes ( ptr , tx , 32 ) [ : : - 1 ] , "index" : read_as_int ( ptr , tx , 4 ) } , "script" : read_var_string ( pt...
def calc_gamma_from_energy_autocorrelation_fit ( self , GammaGuess = None , silent = False , MakeFig = True , show_fig = True ) : """Calculates the total damping , i . e . Gamma , by calculating the energy each point in time . This energy array is then used for the autocorrleation . The autocorrelation is fitte...
autocorrelation = calc_autocorrelation ( self . voltage [ : - 1 ] ** 2 * self . OmegaTrap . n ** 2 + ( _np . diff ( self . voltage ) * self . SampleFreq ) ** 2 ) time = self . time . get_array ( ) [ : len ( autocorrelation ) ] if GammaGuess == None : Gamma_Initial = ( time [ 4 ] - time [ 0 ] ) / ( autocorrelation [...
def add_to_emails ( self , * emails ) : """: calls : ` POST / user / emails < http : / / developer . github . com / v3 / users / emails > ` _ : param email : string : rtype : None"""
assert all ( isinstance ( element , ( str , unicode ) ) for element in emails ) , emails post_parameters = emails headers , data = self . _requester . requestJsonAndCheck ( "POST" , "/user/emails" , input = post_parameters )
def to_pb ( self ) : """Converts the intersection into a single GC rule as a protobuf . : rtype : : class : ` . table _ v2 _ pb2 . GcRule ` : returns : The converted current object ."""
intersection = table_v2_pb2 . GcRule . Intersection ( rules = [ rule . to_pb ( ) for rule in self . rules ] ) return table_v2_pb2 . GcRule ( intersection = intersection )
def get_version ( self ) : """: return :"""
tag = next ( ( tag for tag in self . repo . tags if tag . commit == self . repo . commit ( ) ) , None ) if tag : return tag return self . repo . rev_parse ( str ( self . repo . commit ( ) ) )
def upgrade ( ) : """Upgrade database ."""
# table ObjectVersion : modify primary _ key if op . get_context ( ) . dialect . name == 'mysql' : Fk = 'fk_files_object_bucket_id_files_bucket' op . execute ( 'ALTER TABLE files_object ' 'DROP FOREIGN KEY {0}, DROP PRIMARY KEY, ' 'ADD PRIMARY KEY(version_id), ' 'ADD FOREIGN KEY(bucket_id) ' 'REFERENCES files_b...
def _serve_runs ( self , request ) : """Serve a JSON array of run names , ordered by run started time . Sort order is by started time ( aka first event time ) with empty times sorted last , and then ties are broken by sorting on the run name ."""
if self . _db_connection_provider : db = self . _db_connection_provider ( ) cursor = db . execute ( ''' SELECT run_name, started_time IS NULL as started_time_nulls_last, started_time FROM Runs ORDER BY started_time_nulls_last, started_time, run_name ''...
def grid_slice ( amin , amax , shape , bmin , bmax ) : """Give a slice such that [ amin , amax ] is in [ bmin , bmax ] . Given a grid with shape , and begin and end coordinates amin , amax , what slice do we need to take such that it minimally covers bmin , bmax . amin , amax = 0 , 1 ; shape = 4 0 0.25 0.5 ...
width = amax - amin bmin , bmax = min ( bmin , bmax ) , max ( bmin , bmax ) # normalize the coordinates nmin = ( bmin - amin ) / width nmax = ( bmax - amin ) / width # grid indices if width < 0 : imin = max ( 0 , int ( np . floor ( nmax * shape ) ) ) imax = min ( shape , int ( np . ceil ( nmin * shape ) ) ) els...
def _collect_paths ( element ) : """Collect all possible path which leads to ` element ` . Function returns standard path from root element to this , reverse path , which uses negative indexes for path , also some pattern matches , like " this is element , which has neighbour with id 7 " and so on . Args : ...
output = [ ] # look for element by parameters - sometimes the ID is unique path = vectors . el_to_path_vector ( element ) root = path [ 0 ] params = element . params if element . params else None match = root . find ( element . getTagName ( ) , params ) if len ( match ) == 1 : output . append ( PathCall ( "find" , ...
def _get_element_by_id ( self , resource_name , eclass , id ) : """Get a single element matching an id"""
elements = self . _get_elements ( resource_name , eclass , id = id ) if not elements : raise ValueError ( "No resource matching: {0}" . format ( id ) ) if len ( elements ) == 1 : return elements [ 0 ] raise ValueError ( "Multiple resources matching: {0}" . format ( id ) )
def make_str ( value ) : """Converts a value into a valid string ."""
if isinstance ( value , bytes ) : try : return value . decode ( get_filesystem_encoding ( ) ) except UnicodeError : return value . decode ( 'utf-8' , 'replace' ) return text_type ( value )
def enqueue ( self , name = None , action = None , method = None , wait_url = None , wait_url_method = None , workflow_sid = None , ** kwargs ) : """Create a < Enqueue > element : param name : Friendly name : param action : Action URL : param method : Action URL method : param wait _ url : Wait URL : para...
return self . nest ( Enqueue ( name = name , action = action , method = method , wait_url = wait_url , wait_url_method = wait_url_method , workflow_sid = workflow_sid , ** kwargs ) )
def make_app ( ** kwargs ) : """Create a dummy Sphinx app , filling in various hardcoded assumptions . For example , Sphinx assumes the existence of various source / dest directories , even if you ' re only calling internals that never generate ( or sometimes , even read ! ) on - disk files . This function cr...
srcdir = kwargs . pop ( 'srcdir' , mkdtemp ( ) ) dstdir = kwargs . pop ( 'dstdir' , mkdtemp ( ) ) doctreedir = kwargs . pop ( 'doctreedir' , mkdtemp ( ) ) load_extensions = kwargs . pop ( 'load_extensions' , False ) real_conf = None try : # Sphinx < 1.6ish Sphinx . _log = lambda self , message , wfile , nonl = Fals...
def update_widget ( self , idx = None ) : """Forces the widget at given index to be updated from the property value . If index is not given , all controlled widgets will be updated . This method should be called directly by the user when the property is not observable , or in very unusual conditions ."""
if idx is None : for w in self . _widgets : idx = self . _get_idx_from_widget ( w ) self . _write_widget ( self . _read_property ( idx ) , idx ) pass else : self . _write_widget ( self . _read_property ( idx ) , idx ) return
def unregister_dependent_on ( self , tree ) : """unregistering tree that we are dependent on"""
if tree in self . dependent_on : self . dependent_on . remove ( tree )
def convert_collection_values_according_to_pep ( coll_to_convert : Union [ Dict , List , Set , Tuple ] , desired_type : Type [ T ] , conversion_finder : 'ConversionFinder' , logger : Logger , ** kwargs ) -> T : """Helper method to convert the values of a collection into the required ( pep - declared ) value type in...
base_desired_type = get_base_generic_type ( desired_type ) if issubclass ( base_desired_type , Mapping ) : # or issubclass ( base _ desired _ type , dict ) : # get the base collection type if provided ( this raises an error if key type is not str ) item_typ , _ = _extract_collection_base_type ( desired_type , excep...
def HeadList ( self ) : """Return a list of all the currently loaded repo HEAD objects ."""
return [ ( rname , repo . currenthead ) for rname , repo in self . repos . items ( ) ]
def use_plugin_preset ( self , preset ) : """Apply a preset to the hub . If there was a previously active preset , discard it . Preset can be either the string name of a preset or a PluginPreset instance ."""
if isinstance ( preset , str ) : try : preset = self . _presets [ preset ] except ( AttributeError , KeyError ) : raise AngrNoPluginError ( "There is no preset named %s" % preset ) elif not isinstance ( preset , PluginPreset ) : raise ValueError ( "Argument must be an instance of PluginPrese...
def normalize_extension ( extension ) : """Normalise a file name extension ."""
extension = decode_path ( extension ) if extension is None : return if extension . startswith ( '.' ) : extension = extension [ 1 : ] if '.' in extension : _ , extension = os . path . splitext ( extension ) extension = slugify ( extension , sep = '' ) if extension is None : return if len ( extension ) :...
def scroll_up ( self ) : """Returns the previous command , if any ."""
self . _index += 1 nb_commands = len ( self . _history ) if self . _index >= nb_commands : self . _index = nb_commands - 1 try : return self . _history [ self . _index ] except IndexError : return ''
def ngrams ( string , n = 3 , punctuation = PUNCTUATION , continuous = False ) : """Returns a list of n - grams ( tuples of n successive words ) from the given string . Alternatively , you can supply a Text or Sentence object . With continuous = False , n - grams will not run over sentence markers ( i . e . , ....
def strip_punctuation ( s , punctuation = set ( punctuation ) ) : return [ w for w in s if ( isinstance ( w , Word ) and w . string or w ) not in punctuation ] if n <= 0 : return [ ] if isinstance ( string , basestring ) : s = [ strip_punctuation ( s . split ( " " ) ) for s in tokenize ( string ) ] if isins...
def save_notebook ( self ) : """Saves the current notebook by injecting JavaScript to save to . ipynb file ."""
try : from IPython . display import display , Javascript except ImportError : log . warning ( "Could not import IPython Display Function" ) print ( "Make sure to save your notebook before sending it to OK!" ) return if self . mode == "jupyter" : display ( Javascript ( 'IPython.notebook.save_checkpoi...
def _log_posterior ( theta , counts , alpha , beta , n ) : """Log of the posterior probability and gradient Parameters theta : ndarray , shape = ( n _ params , ) The free parameters of the reversible rate matrix counts : ndarray , shape = ( n , n ) The count matrix ( sufficient statistics for the likielih...
# likelihood + grad logp1 , grad = loglikelihood ( theta , counts ) # exponential prior on s _ { ij } logp2 = lexponential ( theta [ : - n ] , beta , grad = grad [ : - n ] ) # dirichlet prior on \ pi logp3 = ldirichlet_softmax ( theta [ - n : ] , alpha = alpha , grad = grad [ - n : ] ) logp = logp1 + logp2 + logp3 retu...
def query_random ( ** kwargs ) : '''Return the random records of centain kind .'''
if 'limit' in kwargs : limit = kwargs [ 'limit' ] elif 'num' in kwargs : limit = kwargs [ 'num' ] else : limit = 10 kind = kwargs . get ( 'kind' , None ) if kind : rand_recs = TabPost . select ( ) . where ( ( TabPost . kind == kind ) & ( TabPost . valid == 1 ) ) . order_by ( peewee . fn . Random ( ) ) ....
def addButton ( self , fnc , states = ( "On" , "Off" ) , c = ( "w" , "w" ) , bc = ( "dg" , "dr" ) , pos = ( 20 , 40 ) , size = 24 , font = "arial" , bold = False , italic = False , alpha = 1 , angle = 0 , ) : """Add a button to the renderer window . : param list states : a list of possible states [ ' On ' , ' Off...
return addons . addButton ( fnc , states , c , bc , pos , size , font , bold , italic , alpha , angle )
def _tuplefy_namespace ( self , namespace ) : """Converts a mongodb namespace to a db , collection tuple"""
namespace_split = namespace . split ( '.' , 1 ) if len ( namespace_split ) is 1 : # we treat a single element as a collection name . # this also properly tuplefies ' * ' namespace_tuple = ( '*' , namespace_split [ 0 ] ) elif len ( namespace_split ) is 2 : namespace_tuple = ( namespace_split [ 0 ] , namespace_sp...
def _get_path ( self , filename ) : """Creates the cache directory if it doesn ' t already exist . Returns the full path to the specified file inside the cache directory ."""
tempdir = settings . _temp_directory if not os . path . exists ( tempdir ) : os . makedirs ( tempdir ) return os . path . join ( tempdir , filename )
def json_serializer ( data = None , code = 200 , headers = None , context = None , etag = None , task_result = None ) : """Build a json flask response using the given data . : param data : The data to serialize . ( Default : ` ` None ` ` ) : param code : The HTTP status code . ( Default : ` ` 200 ` ` ) : para...
schema_class , many = schema_from_context ( context or { } ) if data is not None : # Generate JSON response data = json . dumps ( schema_class ( context = context ) . dump ( data , many = many ) . data , ** _format_args ( ) ) interval = current_app . config [ 'FILES_REST_TASK_WAIT_INTERVAL' ] max_rounds = i...
def get_typecast_value ( self , value , type ) : """Helper method to determine actual value based on type of feature variable . Args : value : Value in string form as it was parsed from datafile . type : Type denoting the feature flag type . Return : Value type - casted based on type of feature variable ....
if type == entities . Variable . Type . BOOLEAN : return value == 'true' elif type == entities . Variable . Type . INTEGER : return int ( value ) elif type == entities . Variable . Type . DOUBLE : return float ( value ) else : return value
def _get_ntddi ( osvi ) : """Determines the current operating system . This function allows you to quickly tell apart major OS differences . For more detailed information call L { kernel32 . GetVersionEx } instead . @ note : Wine reports itself as Windows XP 32 bits ( even if the Linux host is 64 bits ) ....
if not osvi : osvi = GetVersionEx ( ) ntddi = 0 ntddi += ( osvi . dwMajorVersion & 0xFF ) << 24 ntddi += ( osvi . dwMinorVersion & 0xFF ) << 16 ntddi += ( osvi . wServicePackMajor & 0xFF ) << 8 ntddi += ( osvi . wServicePackMinor & 0xFF ) return ntddi
def vline ( self , x , y , height , color ) : """Draw a vertical line up to a given length ."""
self . rect ( x , y , 1 , height , color , fill = True )
def get_available_FIELD_transitions ( instance , field ) : """List of transitions available in current model state with all conditions met"""
curr_state = field . get_state ( instance ) transitions = field . transitions [ instance . __class__ ] for name , transition in transitions . items ( ) : meta = transition . _django_fsm if meta . has_transition ( curr_state ) and meta . conditions_met ( instance , curr_state ) : yield meta . get_transit...
def crossings_nonzero_pos2neg ( data ) : """Find ` indices of zero crossings from positive to negative values < http : / / stackoverflow . com / questions / 3843017 / efficiently - detect - sign - changes - in - python > ` _ . : param data : numpy array of floats : type data : numpy array of floats : return c...
import numpy as np if isinstance ( data , np . ndarray ) : pass elif isinstance ( data , list ) : data = np . asarray ( data ) else : raise IOError ( 'data should be a numpy array' ) pos = data > 0 crossings = ( pos [ : - 1 ] & ~ pos [ 1 : ] ) . nonzero ( ) [ 0 ] return crossings
def _bucket_exists ( self ) : """Check if the bucket exists ."""
try : self . s3client . get_bucket_location ( Bucket = self . bucket ) return True except ClientError as error : LOG . error ( error ) return False
def is_list_of_states ( self , arg ) : """A list of states example - [ ( ' x1 ' , ' easy ' ) , ( ' x2 ' , ' hard ' ) ] Returns True , if arg is a list of states else False ."""
return isinstance ( arg , list ) and all ( isinstance ( i , tuple ) for i in arg )
def maybe_start_recording ( tokens , index ) : """Return a new _ MultilineStringRecorder when its time to record ."""
if _is_begin_quoted_type ( tokens [ index ] . type ) : string_type = _get_string_type_from_token ( tokens [ index ] . type ) return _MultilineStringRecorder ( index , string_type ) return None
def _get_bounds ( self ) : """Subclasses may override this method ."""
from fontTools . pens . boundsPen import BoundsPen pen = BoundsPen ( self . layer ) self . draw ( pen ) return pen . bounds
def addNamespace ( self , namespace , ** context ) : """Creates a new namespace within this database . : param namespace : < str >"""
self . connection ( ) . addNamespace ( namespace , orb . Context ( ** context ) )
def save ( self , fname , compression = 'blosc' ) : """Save method for the Egg object The data will be saved as a ' egg ' file , which is a dictionary containing the elements of a Egg saved in the hd5 format using ` deepdish ` . Parameters fname : str A name for the file . If the file extension ( . egg ...
# put egg vars into a dict egg = { 'pres' : df2list ( self . pres ) , 'rec' : df2list ( self . rec ) , 'dist_funcs' : self . dist_funcs , 'subjgroup' : self . subjgroup , 'subjname' : self . subjname , 'listgroup' : self . listgroup , 'listname' : self . listname , 'date_created' : self . date_created , 'meta' : self ....
def replace_word_tokens ( string , language ) : """Given a string and an ISO 639-2 language code , return the string with the words replaced with an operational equivalent ."""
words = mathwords . word_groups_for_language ( language ) # Replace operator words with numeric operators operators = words [ 'binary_operators' ] . copy ( ) if 'unary_operators' in words : operators . update ( words [ 'unary_operators' ] ) for operator in list ( operators . keys ( ) ) : if operator in string :...
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'xpaths' ) and self . xpaths is not None : _dict [ 'xpaths' ] = self . xpaths return _dict
def c_func ( funcname , reverse = False , nans = False , scalar = False ) : """Fill c _ funcs with constructed code from the templates"""
varnames = [ 'group_idx' , 'a' , 'ret' , 'counter' ] codebase = c_base_reverse if reverse else c_base iteration = c_iter_scalar [ funcname ] if scalar else c_iter [ funcname ] if scalar : varnames . remove ( 'a' ) return codebase % dict ( init = c_init ( varnames ) , iter = iteration , finish = c_finish . get ( fun...
def send ( self , request , ordered = False ) : """This method enqueues the given request to be sent . Its send state will be saved until a response arrives , and a ` ` Future ` ` that will be resolved when the response arrives will be returned : . . code - block : : python async def method ( ) : # Sendin...
if not self . _user_connected : raise ConnectionError ( 'Cannot send requests while disconnected' ) if not utils . is_list_like ( request ) : state = RequestState ( request , self . _loop ) self . _send_queue . append ( state ) return state . future else : states = [ ] futures = [ ] state = ...
def find_char_color ( ansi_string , pos ) : """Determine what color a character is in the string . : param str ansi _ string : String with color codes ( ANSI escape sequences ) . : param int pos : Position of the character in the ansi _ string . : return : Character along with all surrounding color codes . ...
result = list ( ) position = 0 # Set to None when character is found . for item in ( i for i in RE_SPLIT . split ( ansi_string ) if i ) : if RE_SPLIT . match ( item ) : result . append ( item ) if position is not None : position += len ( item ) elif position is not None : for...
def p_expression_eql ( self , p ) : 'expression : expression EQL expression'
p [ 0 ] = Eql ( p [ 1 ] , p [ 3 ] , lineno = p . lineno ( 1 ) ) p . set_lineno ( 0 , p . lineno ( 1 ) )
def start ( self ) : """Start the node synchronously . Raises directly if anything went wrong on startup"""
assert self . stop_event . ready ( ) , f'Node already started. node:{self!r}' self . stop_event . clear ( ) self . greenlets = list ( ) self . ready_to_process_events = False # set to False because of restarts if self . database_dir is not None : self . db_lock . acquire ( timeout = 0 ) assert self . db_lock . ...
def V_vertical_conical ( D , a , h ) : r'''Calculates volume of a vertical tank with a convex conical bottom , according to [ 1 ] _ . No provision for the top of the tank is made here . . . math : : V _ f = \ frac { \ pi } { 4 } \ left ( \ frac { Dh } { a } \ right ) ^ 2 \ left ( \ frac { h } { 3 } \ right ) ...
if h < a : Vf = pi / 4 * ( D * h / a ) ** 2 * ( h / 3. ) else : Vf = pi * D ** 2 / 4 * ( h - 2 * a / 3. ) return Vf
def _get_ANSI_colored_font ( color ) : '''Returns an ANSI escape code ( a string ) corresponding to switching the font to given color , or None , if the given color could not be associated with the available colors . See also : https : / / en . wikipedia . org / wiki / ANSI _ escape _ code # Colors http :...
color = ( color . replace ( '-' , '' ) ) . lower ( ) # Bright colors : if color == 'white' : return '\033[97m' elif color in [ 'cyan' , 'aqua' ] : return '\033[96m' elif color in [ 'purple' , 'magneta' , 'fuchsia' ] : return '\033[95m' elif color == 'blue' : return '\033[94m' elif color in [ 'yellow' , ...
def _pad ( self , data ) : """Pad value with bytes so it ' s a multiple of 16 See : http : / / stackoverflow . com / questions / 14179784 / python - encrypting - with - pycrypto - aes : param data : : return data :"""
length = 16 - ( len ( data ) % 16 ) data += chr ( length ) * length return data
def build ( self , builder ) : """Build XML by appending to builder"""
builder . start ( "Annotations" ) # populate the flags for annotation in self . annotations : annotation . build ( builder ) builder . end ( "Annotations" )
def fmt_error_types ( hyps : Sequence [ Sequence [ str ] ] , refs : Sequence [ Sequence [ str ] ] ) -> str : """Format some information about different error types : insertions , deletions and substitutions ."""
alignments = [ min_edit_distance_align ( ref , hyp ) for hyp , ref in zip ( hyps , refs ) ] arrow_counter = Counter ( ) # type : Dict [ Tuple [ str , str ] , int ] for alignment in alignments : arrow_counter . update ( alignment ) sub_count = sum ( [ count for arrow , count in arrow_counter . items ( ) if arrow [ 0...