idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
14,500 | def intra_mean ( self , values ) : # TODO Check that quantity is valid if values . ndim > 1 : return np . array ( [ np . mean ( values [ x , : ] , axis = 0 ) for x in self . allocations_ ] ) else : return np . array ( [ np . mean ( values [ x ] ) for x in self . allocations_ ] ) | Calculate the mean of a quantity within strata | 82 | 11 |
14,501 | def reset ( self ) : self . _sampled = [ np . repeat ( False , x ) for x in self . sizes_ ] self . _n_sampled = np . zeros ( self . n_strata_ , dtype = int ) | Reset the instance to begin sampling from scratch | 55 | 9 |
14,502 | async def bluetooth_scan ( ) : devices = { } async with aiohttp . ClientSession ( ) as session : ghlocalapi = NetworkScan ( LOOP , session ) result = await ghlocalapi . scan_for_units ( IPRANGE ) for host in result : if host [ 'assistant_supported' ] : async with aiohttp . ClientSession ( ) as session : ghlocalapi = DeviceInfo ( LOOP , session , host [ 'host' ] ) await ghlocalapi . get_device_info ( ) ghname = ghlocalapi . device_info . get ( 'name' ) async with aiohttp . ClientSession ( ) as session : ghlocalapi = Bluetooth ( LOOP , session , host [ 'host' ] ) await ghlocalapi . scan_for_devices_multi_run ( ) await ghlocalapi . get_scan_result ( ) for device in ghlocalapi . devices : mac = device [ 'mac_address' ] if not devices . get ( mac , False ) : # New device devices [ mac ] = { } devices [ mac ] [ 'rssi' ] = device [ 'rssi' ] devices [ mac ] [ 'ghunit' ] = ghname elif devices [ mac ] [ 'rssi' ] < device [ 'rssi' ] : # Better RSSI value on this device devices [ mac ] [ 'rssi' ] = device [ 'rssi' ] devices [ mac ] [ 'ghunit' ] = ghname print ( devices ) | Get devices from all GH units on the network . | 327 | 10 |
14,503 | def get_queue_obj ( session , queue_url , log_url ) : skip = False if not queue_url : logger . error ( "The queue url is not configured, skipping submit verification" ) skip = True if not session : logger . error ( "Missing requests session, skipping submit verification" ) skip = True queue = QueueSearch ( session = session , queue_url = queue_url , log_url = log_url ) queue . skip = skip return queue | Checks that all the data that is needed for submit verification is available . | 101 | 15 |
14,504 | def download_queue ( self , job_ids ) : if self . skip : return None url = "{}?jobtype=completed&jobIds={}" . format ( self . queue_url , "," . join ( str ( x ) for x in job_ids ) ) try : response = self . session . get ( url , headers = { "Accept" : "application/json" } ) if response : response = response . json ( ) else : response = None # pylint: disable=broad-except except Exception as err : logger . error ( err ) response = None return response | Downloads data of completed jobs . | 128 | 7 |
14,505 | def find_jobs ( self , job_ids ) : matched_jobs = [ ] if self . skip : return matched_jobs json_data = self . download_queue ( job_ids ) if not json_data : return matched_jobs jobs = json_data [ "jobs" ] for job in jobs : if ( job . get ( "id" ) in job_ids and job . get ( "status" , "" ) . lower ( ) not in _NOT_FINISHED_STATUSES ) : matched_jobs . append ( job ) return matched_jobs | Finds the jobs in the completed job queue . | 121 | 10 |
14,506 | def wait_for_jobs ( self , job_ids , timeout , delay ) : if self . skip : return logger . debug ( "Waiting up to %d sec for completion of the job IDs %s" , timeout , job_ids ) remaining_job_ids = set ( job_ids ) found_jobs = [ ] countdown = timeout while countdown > 0 : matched_jobs = self . find_jobs ( remaining_job_ids ) if matched_jobs : remaining_job_ids . difference_update ( { job [ "id" ] for job in matched_jobs } ) found_jobs . extend ( matched_jobs ) if not remaining_job_ids : return found_jobs time . sleep ( delay ) countdown -= delay logger . error ( "Timed out while waiting for completion of the job IDs %s. Results not updated." , list ( remaining_job_ids ) , ) | Waits until the jobs appears in the completed job queue . | 189 | 12 |
14,507 | def _check_outcome ( self , jobs ) : if self . skip : return False if not jobs : logger . error ( "Import failed!" ) return False failed_jobs = [ ] for job in jobs : status = job . get ( "status" ) if not status : failed_jobs . append ( job ) continue if status . lower ( ) != "success" : failed_jobs . append ( job ) for job in failed_jobs : logger . error ( "job: %s; status: %s" , job . get ( "id" ) , job . get ( "status" ) ) if len ( failed_jobs ) == len ( jobs ) : logger . error ( "Import failed!" ) elif failed_jobs : logger . error ( "Some import jobs failed!" ) else : logger . info ( "Results successfully updated!" ) return not failed_jobs | Parses returned messages and checks submit outcome . | 184 | 10 |
14,508 | def _download_log ( self , url , output_file ) : logger . info ( "Saving log %s to %s" , url , output_file ) def _do_log_download ( ) : try : return self . session . get ( url ) # pylint: disable=broad-except except Exception as err : logger . error ( err ) # log file may not be ready yet, wait a bit for __ in range ( 5 ) : log_data = _do_log_download ( ) if log_data or log_data is None : break time . sleep ( 2 ) if not ( log_data and log_data . content ) : logger . error ( "Failed to download log file %s." , url ) return with open ( os . path . expanduser ( output_file ) , "ab" ) as out : out . write ( log_data . content ) | Saves log returned by the message bus . | 192 | 9 |
14,509 | def get_logs ( self , jobs , log_file = None ) : if not ( jobs and self . log_url ) : return for job in jobs : url = "{}?jobId={}" . format ( self . log_url , job . get ( "id" ) ) if log_file : self . _download_log ( "{}&download" . format ( url ) , log_file ) else : logger . info ( "Submit log for job %s: %s" , job . get ( "id" ) , url ) | Get log or log url of the jobs . | 118 | 9 |
14,510 | def submodules ( self ) : submodules = [ ] submodules . extend ( self . modules ) for p in self . packages : submodules . extend ( p . submodules ) return submodules | Property to return all sub - modules of the node recursively . | 41 | 14 |
14,511 | def get_target ( self , target ) : if target not in self . _target_cache : self . _target_cache [ target ] = self . _get_target ( target ) return self . _target_cache [ target ] | Get the result of _get_target cache it and return it . | 50 | 14 |
14,512 | def _get_target ( self , target ) : depth = target . count ( '.' ) + 1 parts = target . split ( '.' , 1 ) for m in self . modules : if parts [ 0 ] == m . name : if depth < 3 : return m for p in self . packages : if parts [ 0 ] == p . name : if depth == 1 : return p # pylama:ignore=W0212 target = p . _get_target ( parts [ 1 ] ) if target : return target # FIXME: can lead to internal dep instead of external # see example with django.contrib.auth.forms # importing forms from django # Idea: when parsing files with ast, record what objects # are defined in the module. Then check here if the given # part is one of these objects. if depth < 3 : return p return None | Get the Package or Module related to given target . | 183 | 10 |
14,513 | def build_dependencies ( self ) : for m in self . modules : m . build_dependencies ( ) for p in self . packages : p . build_dependencies ( ) | Recursively build the dependencies for sub - modules and sub - packages . | 39 | 15 |
14,514 | def print_graph ( self , format = None , output = sys . stdout , depth = 0 , * * kwargs ) : graph = self . as_graph ( depth = depth ) graph . print ( format = format , output = output , * * kwargs ) | Print the graph for self s nodes . | 59 | 8 |
14,515 | def as_graph ( self , depth = 0 ) : if depth in self . _graph_cache : return self . _graph_cache [ depth ] self . _graph_cache [ depth ] = graph = Graph ( self , depth = depth ) return graph | Create a graph with self as node cache it return it . | 54 | 12 |
14,516 | def as_matrix ( self , depth = 0 ) : if depth in self . _matrix_cache : return self . _matrix_cache [ depth ] self . _matrix_cache [ depth ] = matrix = Matrix ( self , depth = depth ) return matrix | Create a matrix with self as node cache it return it . | 58 | 12 |
14,517 | def as_treemap ( self ) : if self . _treemap_cache : return self . _treemap_cache self . _treemap_cache = treemap = TreeMap ( self ) return treemap | Return the dependencies as a TreeMap . | 51 | 8 |
14,518 | def root ( self ) : node = self while node . package is not None : node = node . package return node | Property to return the root of this node . | 24 | 9 |
14,519 | def depth ( self ) : if self . _depth_cache is not None : return self . _depth_cache depth , node = 1 , self while node . package is not None : depth += 1 node = node . package self . _depth_cache = depth return depth | Property to tell the depth of the node in the tree . | 57 | 12 |
14,520 | def absolute_name ( self , depth = 0 ) : node , node_depth = self , self . depth if depth < 1 : depth = node_depth while node_depth > depth and node . package is not None : node = node . package node_depth -= 1 names = [ ] while node is not None : names . append ( node . name ) node = node . package return '.' . join ( reversed ( names ) ) | Return the absolute name of the node . | 91 | 8 |
14,521 | def color_msg ( msg , color ) : return '' . join ( ( COLORS . get ( color , COLORS [ 'endc' ] ) , msg , COLORS [ 'endc' ] ) ) | Return colored message | 45 | 3 |
14,522 | def gen_files ( path , prefix = "_" ) : if op . isdir ( path ) : for name in listdir ( path ) : fpath = op . join ( path , name ) if is_parsed_file ( fpath ) : yield op . abspath ( fpath ) elif is_parsed_file ( path ) : yield op . abspath ( path ) | Return file generator | 85 | 3 |
14,523 | def pack ( args ) : from zetalibrary . packer import Packer args = parse_config ( args ) for path in gen_files ( args . source , prefix = args . prefix ) : Packer ( path , args ) . pack ( ) | Pack files . | 54 | 3 |
14,524 | def nonzero_monies ( self ) : return [ copy . copy ( m ) for m in self . _money_obs if m . amount != 0 ] | Get a list of the underlying Money instances that are not zero | 34 | 12 |
14,525 | def index ( pc ) : click . echo ( "Format Version: {0}" . format ( pc . idx [ 'formatVersion' ] ) ) click . echo ( "Publication Date: {0}" . format ( pc . idx [ 'publicationDate' ] ) ) olist = '' for i , o in enumerate ( pc . idx [ 'offers' ] ) : if i < len ( pc . idx [ 'offers' ] ) - 1 : olist += o + ", " else : olist += o click . echo ( "Services Offered: {0}" . format ( olist ) ) | Show details about the Pricing API Index . | 135 | 8 |
14,526 | def product ( pc , service , attrib , sku ) : pc . service = service . lower ( ) pc . sku = sku pc . add_attributes ( attribs = attrib ) click . echo ( "Service Alias: {0}" . format ( pc . service_alias ) ) click . echo ( "URL: {0}" . format ( pc . service_url ) ) click . echo ( "Region: {0}" . format ( pc . region ) ) click . echo ( "Product Terms: {0}" . format ( pc . terms ) ) click . echo ( "Filtering Attributes: {0}" . format ( pc . attributes ) ) prods = pyutu . find_products ( pc ) for p in prods : click . echo ( "Product SKU: {0} product: {1}" . format ( p , json . dumps ( prods [ p ] , indent = 2 , sort_keys = True ) ) ) click . echo ( "Total Products Found: {0}" . format ( len ( prods ) ) ) click . echo ( "Time: {0} secs" . format ( time . process_time ( ) ) ) | Get a list of a service s products . The list will be in the given region matching the specific terms and any given attribute filters or a SKU . | 253 | 31 |
14,527 | def price ( pc , service , attrib , sku ) : pc . service = service . lower ( ) pc . sku = sku pc . add_attributes ( attribs = attrib ) click . echo ( "Service Alias: {0}" . format ( pc . service_alias ) ) click . echo ( "URL: {0}" . format ( pc . service_url ) ) click . echo ( "Region: {0}" . format ( pc . region ) ) click . echo ( "Product Terms: {0}" . format ( pc . terms ) ) click . echo ( "Filtering Attributes: {0}" . format ( pc . attributes ) ) prices = pyutu . get_prices ( pc ) for p in prices : click . echo ( "Rate Code: {0} price: {1}" . format ( p , json . dumps ( prices [ p ] , indent = 2 , sort_keys = True ) ) ) click . echo ( "Total Prices Found: {0}" . format ( len ( prices ) ) ) if sys . version_info >= ( 3 , 3 ) : click . echo ( "Time: {0} secs" . format ( time . process_time ( ) ) ) | Get a list of a service s prices . The list will be in the given region matching the specific terms and any given attribute filters or a SKU . | 262 | 31 |
14,528 | def map_init ( interface , params ) : import numpy as np import random np . random . seed ( params [ 'seed' ] ) random . seed ( params [ 'seed' ] ) return params | Intialize random number generator with given seed params . seed . | 43 | 13 |
14,529 | def create_graph_name ( suffix = '' , dirname = None ) : if suffix : suffix = '-%s' % suffix caller = get_callers_name ( level = 3 ) name = '%s%s%s%s' % ( __prefix , caller , suffix , __suffix ) if dirname : name = os . path . join ( dirname , name ) return name | Create a graph name using the name of the caller . | 86 | 11 |
14,530 | def save_graph ( graph , suffix = '' , dirname = None , pdf = False ) : name = create_graph_name ( suffix , dirname ) graph . save ( name ) if pdf : graph . save_as_pdf ( name ) | Save a graph using caller s name . | 53 | 8 |
14,531 | def save_data ( data , suffix = '' , dirname = None ) : if type ( data ) == list : data = np . array ( data ) . T name = create_graph_name ( suffix , dirname ) + '.txt' np . savetxt ( name , data ) | Save a dataset using caller s name . | 61 | 8 |
14,532 | def read ( path , savedir ) : if path . startswith ( 'http://' ) : name = op . basename ( path ) save_path = op . join ( savedir , name ) if not op . exists ( save_path ) : src = urllib2 . urlopen ( path ) . read ( ) try : open ( save_path , 'w' ) . write ( src ) except IOError : return src path = save_path return open ( path , 'r' ) . read ( ) | Read file from path | 112 | 4 |
14,533 | def parse_imports ( self , src ) : result = [ ] def child ( obj ) : result . append ( obj . group ( 1 ) ) src = self . import_re . sub ( child , src ) return src , result | Parse imports from source . | 50 | 6 |
14,534 | def __get_users ( self ) : # pragma: no cover filter = [ '(objectclass=posixAccount)' ] results = self . client . search ( filter , [ 'uid' ] ) for result in results : yield result . uid . value | Get user list . | 55 | 4 |
14,535 | def by_user ( config ) : client = Client ( ) client . prepare_connection ( ) audit_api = API ( client ) CLI . parse_membership ( 'Groups by User' , audit_api . by_user ( ) ) | Display LDAP group membership sorted by user . | 52 | 9 |
14,536 | def raw ( config ) : # pragma: no cover client = Client ( ) client . prepare_connection ( ) audit_api = API ( client ) print ( audit_api . raw ( ) ) | Dump the contents of LDAP to console in raw format . | 42 | 13 |
14,537 | def get_sql_state ( self , state ) : if not hasattr ( state , 'sql_state' ) : setattr ( state , 'sql_state' , SQLStateGraph ( ) ) return state . sql_state | Get SQLStateGraph from state . | 49 | 7 |
14,538 | def get_sortkey ( table ) : # Just pick the first column in the table in alphabetical order. # Ideally we would get the primary key from bcdc api, but it doesn't # seem to be available wfs = WebFeatureService ( url = bcdata . OWS_URL , version = "2.0.0" ) return sorted ( wfs . get_schema ( "pub:" + table ) [ "properties" ] . keys ( ) ) [ 0 ] | Get a field to sort by | 103 | 6 |
14,539 | def check_cache ( path ) : if not os . path . exists ( path ) : return True else : # check the age mod_date = datetime . fromtimestamp ( os . path . getmtime ( path ) ) if mod_date < ( datetime . now ( ) - timedelta ( days = 30 ) ) : return True else : return False | Return true if the cache file holding list of all datasets does not exist or is older than 30 days | 77 | 20 |
14,540 | def bcdc_package_show ( package ) : params = { "id" : package } r = requests . get ( bcdata . BCDC_API_URL + "package_show" , params = params ) if r . status_code != 200 : raise ValueError ( "{d} is not present in DataBC API list" . format ( d = package ) ) return r . json ( ) [ "result" ] | Query DataBC Catalogue API about given package | 91 | 9 |
14,541 | def list_tables ( refresh = False , cache_file = None ) : # default cache listing all objects available is # ~/.bcdata if not cache_file : cache_file = os . path . join ( str ( Path . home ( ) ) , ".bcdata" ) # regenerate the cache if: # - the cache file doesn't exist # - we force a refresh # - the cache is older than 1 month if refresh or check_cache ( cache_file ) : wfs = WebFeatureService ( url = bcdata . OWS_URL , version = "2.0.0" ) bcdata_objects = [ i . strip ( "pub:" ) for i in list ( wfs . contents ) ] with open ( cache_file , "w" ) as outfile : json . dump ( sorted ( bcdata_objects ) , outfile ) else : with open ( cache_file , "r" ) as infile : bcdata_objects = json . load ( infile ) return bcdata_objects | Return a list of all datasets available via WFS | 216 | 10 |
14,542 | def make_request ( parameters ) : r = requests . get ( bcdata . WFS_URL , params = parameters ) return r . json ( ) [ "features" ] | Submit a getfeature request to DataBC WFS and return features | 37 | 13 |
14,543 | def define_request ( dataset , query = None , crs = "epsg:4326" , bounds = None , sortby = None , pagesize = 10000 ) : # validate the table name and find out how many features it holds table = validate_name ( dataset ) n = bcdata . get_count ( table , query = query ) # DataBC WFS getcapabilities says that it supports paging, # and the spec says that responses should include 'next URI' # (section 7.7.4.4.1).... # But I do not see any next uri in the responses. Instead of following # the paged urls, for datasets with >10k records, just generate urls # based on number of features in the dataset. chunks = math . ceil ( n / pagesize ) # if making several requests, we need to sort by something if chunks > 1 and not sortby : sortby = get_sortkey ( table ) # build the request parameters for each chunk param_dicts = [ ] for i in range ( chunks ) : request = { "service" : "WFS" , "version" : "2.0.0" , "request" : "GetFeature" , "typeName" : table , "outputFormat" : "json" , "SRSNAME" : crs , } if sortby : request [ "sortby" ] = sortby if query : request [ "CQL_FILTER" ] = query if bounds : request [ "bbox" ] = "," . join ( [ str ( b ) for b in bounds ] ) if chunks > 1 : request [ "startIndex" ] = i * pagesize request [ "count" ] = pagesize param_dicts . append ( request ) return param_dicts | Define the getfeature request parameters required to download a dataset | 382 | 12 |
14,544 | def get_data ( dataset , query = None , crs = "epsg:4326" , bounds = None , sortby = None , pagesize = 10000 , max_workers = 5 , ) : param_dicts = define_request ( dataset , query , crs , bounds , sortby , pagesize ) with ThreadPoolExecutor ( max_workers = max_workers ) as executor : results = executor . map ( make_request , param_dicts ) outjson = dict ( type = "FeatureCollection" , features = [ ] ) for result in results : outjson [ "features" ] += result return outjson | Get GeoJSON featurecollection from DataBC WFS | 136 | 10 |
14,545 | def get_features ( dataset , query = None , crs = "epsg:4326" , bounds = None , sortby = None , pagesize = 10000 , max_workers = 5 , ) : param_dicts = define_request ( dataset , query , crs , bounds , sortby , pagesize ) with ThreadPoolExecutor ( max_workers = max_workers ) as executor : for result in executor . map ( make_request , param_dicts ) : for feature in result : yield feature | Yield features from DataBC WFS | 111 | 8 |
14,546 | def _get_sorted ( self , resources ) : tmp = [ ] for resource in resources : path = resource . _path # Each slash counts as 10 priority, each variable takes one away priority = path . count ( '/' ) * 10 - path . count ( '{' ) tmp . append ( ( priority , resource ) ) return [ resource for prio , resource in reversed ( sorted ( tmp ) ) ] | Order the resources by priority - the most specific paths come first . | 87 | 13 |
14,547 | def set_cfme_caselevel ( testcase , caselevels ) : tier = testcase . get ( "caselevel" ) if tier is None : return try : caselevel = caselevels [ int ( tier ) ] except IndexError : # invalid value caselevel = "component" except ValueError : # there's already string value return testcase [ "caselevel" ] = caselevel | Converts tier to caselevel . | 82 | 7 |
14,548 | def get_requirements_transform_cfme ( config ) : def requirement_transform ( requirement ) : """Requirements transform for CFME.""" requirement = copy . deepcopy ( requirement ) if "id" in requirement : del requirement [ "id" ] return requirement return requirement_transform | Return requirement transformation function for CFME . | 59 | 8 |
14,549 | def get_requirements_transform_cloudtp ( config ) : def requirement_transform ( requirement ) : """Requirements transform for CLOUDTP.""" requirement = copy . deepcopy ( requirement ) if "id" in requirement : del requirement [ "id" ] # TODO: testing purposes, remove once ready if not requirement . get ( "assignee-id" ) : requirement [ "assignee-id" ] = "mkourim" if not requirement . get ( "approver-ids" ) : requirement [ "approver-ids" ] = "mkourim:approved" return requirement return requirement_transform | Return requirement transformation function for CLOUDTP . | 133 | 10 |
14,550 | def render_archive ( entries ) : context = GLOBAL_TEMPLATE_CONTEXT . copy ( ) context [ 'entries' ] = entries _render ( context , 'archive_index.html' , os . path . join ( CONFIG [ 'output_to' ] , 'archive/index.html' ) ) , | Creates the archive page | 72 | 5 |
14,551 | def find_new_posts_and_pages ( db ) : Q = Query ( ) for root , dirs , files in os . walk ( CONFIG [ 'content_root' ] ) : for filename in sorted ( [ f for f in files if f . endswith ( ( 'md' , 'markdown' ) ) ] ) : fullpath = os . path . join ( root , filename ) _p = fullpath . split ( CONFIG [ 'content_root' ] ) [ - 1 ] . lstrip ( '/' ) new_mtime = int ( os . path . getmtime ( fullpath ) ) e , item = None , None for collection in [ 'posts' , 'pages' ] : item = db [ collection ] . get ( Q . filename == _p ) if item : if new_mtime > item [ 'mtime' ] : db [ collection ] . update ( { 'mtime' : new_mtime } , doc_ids = [ item . doc_id ] ) e = Entry ( fullpath , doc_id = item . doc_id ) break if not item : e = Entry ( fullpath ) if e : yield e , e . id | Walk content dir put each post and page in the database | 255 | 11 |
14,552 | def _get_last_entries ( db , qty ) : doc_ids = [ post . doc_id for post in db . posts . all ( ) ] doc_ids = sorted ( doc_ids , reverse = True ) # bug: here we shoud only render doc_ids[:qty] # but we can't use mtimes for sorting. We'll need to add ptime for the # database (publish time) entries = [ Entry ( os . path . join ( CONFIG [ 'content_root' ] , db . posts . get ( doc_id = doc_id ) [ 'filename' ] ) , doc_id ) for doc_id in doc_ids ] # return _sort_entries(entries)[:qty] entries . sort ( key = operator . attrgetter ( 'date' ) , reverse = True ) return entries [ : qty ] , entries | get all entries and the last qty entries | 194 | 9 |
14,553 | def update_index ( entries ) : context = GLOBAL_TEMPLATE_CONTEXT . copy ( ) context [ 'entries' ] = entries context [ 'last_build' ] = datetime . datetime . now ( ) . strftime ( "%Y-%m-%dT%H:%M:%SZ" ) list ( map ( lambda x : _render ( context , x [ 0 ] , os . path . join ( CONFIG [ 'output_to' ] , x [ 1 ] ) ) , ( ( 'entry_index.html' , 'index.html' ) , ( 'atom.xml' , 'atom.xml' ) ) ) ) | find the last 10 entries in the database and create the main page . Each entry in has an doc_id so we only get the last 10 doc_ids . | 148 | 33 |
14,554 | def build ( config ) : logger . info ( "\nRendering website now...\n" ) logger . info ( "entries:" ) tags = dict ( ) entries = list ( ) for post , post_id in find_new_posts_and_pages ( DB ) : # this method will also parse the post's tags and # update the db collection containing the tags. if post . render ( ) : if post . header [ 'kind' ] in [ 'writing' , 'link' ] : for tag in post . tags : tag . posts = [ post_id ] tags [ tag . name ] = tag entries . append ( post ) logger . info ( "%s" % post . path ) for name , to in tags . items ( ) : logger . info ( "updating tag %s" % name ) to . render ( ) # This is expensive, we should insert only the recent entries # to the index using BeautifulSoup # update index logger . info ( "Updating index" ) last_entries , all_entries = _get_last_entries ( DB , config [ 'INDEX_SIZE' ] ) last_entries = list ( _filter_none_public ( last_entries ) ) update_index ( last_entries ) # update archive logger . info ( "Updating archive" ) # This is expensive, we should insert only the recent entries # to the archive using BeautifulSoup entries = [ Entry . entry_from_db ( os . path . join ( CONFIG [ 'content_root' ] , e . get ( 'filename' ) ) , e . doc_id ) for e in DB . posts . all ( ) ] all_entries = list ( _filter_none_public ( all_entries ) ) all_entries . sort ( key = operator . attrgetter ( 'date' ) , reverse = True ) render_archive ( all_entries [ config [ 'ARCHIVE_SIZE' ] : ] ) | Incremental build of the website | 424 | 6 |
14,555 | def preview ( ) : # pragma: no coverage Handler = http . server . SimpleHTTPRequestHandler socketserver . TCPServer . allow_reuse_address = True port = CONFIG [ 'http_port' ] httpd = socketserver . TCPServer ( ( "" , port ) , Handler ) os . chdir ( CONFIG [ 'output_to' ] ) try : logger . info ( "and ready to test at " "http://127.0.0.1:%d" % CONFIG [ 'http_port' ] ) logger . info ( "Hit Ctrl+C to exit" ) httpd . serve_forever ( ) except KeyboardInterrupt : httpd . shutdown ( ) | launch an HTTP to preview the website | 148 | 7 |
14,556 | def entries ( self ) : Tags = Query ( ) tag = self . table . get ( Tags . name == self . name ) posts = tag [ 'post_ids' ] for id in posts : post = self . db . posts . get ( doc_id = id ) if not post : # pragma: no coverage raise ValueError ( "No post found for doc_id %s" % id ) yield Entry ( os . path . join ( CONFIG [ 'content_root' ] , post [ 'filename' ] ) , id ) | return the actual lists of entries tagged with | 114 | 8 |
14,557 | def render ( self ) : context = GLOBAL_TEMPLATE_CONTEXT . copy ( ) context [ 'tag' ] = self entries = list ( self . entries ) entries . sort ( key = operator . attrgetter ( 'date' ) , reverse = True ) context [ 'entries' ] = entries # render html page render_to = os . path . join ( CONFIG [ 'output_to' ] , 'tags' , self . slug ) if not os . path . exists ( render_to ) : # pragma: no coverage os . makedirs ( render_to ) _render ( context , 'tag_index.html' , os . path . join ( render_to , 'index.html' ) ) # noqa # render atom.xml context [ 'entries' ] = context [ 'entries' ] [ : 10 ] context [ 'last_build' ] = datetime . datetime . now ( ) . strftime ( "%Y-%m-%dT%H:%M:%SZ" ) # noqa _render ( context , 'atom.xml' , os . path . join ( render_to , 'atom.xml' ) ) return True | Render html page and atom feed | 262 | 6 |
14,558 | def tags ( self ) : if 'tags' in self . header : tags = [ Tag ( t ) for t in self . header [ 'tags' ] ] list ( map ( lambda t : setattr ( t , 'posts' , [ self . id ] ) , tags ) ) return tags else : return [ ] | this property is always called after prepare | 67 | 7 |
14,559 | def prepare ( self ) : self . body_html = markdown ( codecs . open ( self . abspath , 'r' ) . read ( ) , extras = [ 'fenced-code-blocks' , 'hilite' , 'tables' , 'metadata' ] ) self . header = self . body_html . metadata if 'tags' in self . header : # pages can lack tags self . header [ 'tags' ] = [ t . strip ( ) . lower ( ) for t in self . header [ 'tags' ] . split ( ',' ) ] else : self . header [ 'tags' ] = ( "" , ) self . date = self . header . get ( 'published' , datetime . datetime . now ( ) ) if isinstance ( self . date , str ) : self . date = datetime . datetime . strptime ( self . date , "%Y-%m-%d" ) for k , v in self . header . items ( ) : try : setattr ( self , k , v ) except AttributeError : pass if self . id : return rec = { 'filename' : self . path , 'mtime' : int ( os . path . getmtime ( self . abspath ) ) } if self . header [ 'kind' ] == 'writing' : _id = Entry . db . posts . insert ( rec ) elif self . header [ 'kind' ] == 'page' : _id = Entry . db . pages . insert ( rec ) self . id = _id | a blog post without tags causes an error ... | 332 | 9 |
14,560 | def tracker ( ) : application = mmi . tracker . app ( ) application . listen ( 22222 ) logger . info ( 'serving at port 22222' ) tornado . ioloop . IOLoop . instance ( ) . start ( ) | start a tracker to register running models | 51 | 7 |
14,561 | def runner ( engine , configfile , output_vars , interval , pause , mpi , tracker , port , bmi_class ) : # keep track of info # update mpi information or use rank 0 runner = mmi . runner . Runner ( engine = engine , configfile = configfile , output_vars = output_vars , interval = interval , pause = pause , mpi = mpi , tracker = tracker , port = port , bmi_class = bmi_class ) runner . run ( ) | run a BMI compatible model | 110 | 5 |
14,562 | def do_extra_polishing ( self ) : for f in self . EXTRA_POLISH_FUNCTIONS : if not hasattr ( f , 'polish_commit_indexes' ) : if hasattr ( f , 'polish_urls' ) and self . URL in f . polish_urls : f ( ) if not hasattr ( f , 'polish_urls' ) : if hasattr ( f , 'polish_commit_indexes' ) and self . CURRENT_COMMIT_INDEX in f . polish_commit_indexes : f ( ) if hasattr ( f , 'polish_commit_indexes' ) and hasattr ( f , 'polish_urls' ) : if self . URL in f . polish_urls and self . CURRENT_COMMIT_INDEX in f . polish_commit_indexes : f ( ) | Goes over each EXTRA_POLISH_FUNCTION to see if it applies to this page if so calls it | 195 | 25 |
14,563 | def total_charges ( self ) : selected_charges = Charge . objects . filter ( invoice = self ) . charges ( ) . exclude ( product_code = CARRIED_FORWARD ) return total_amount ( selected_charges ) | Represents the goods acquired in the invoice . | 49 | 9 |
14,564 | def due ( self ) : invoice_charges = Charge . objects . filter ( invoice = self ) invoice_transactions = Transaction . successful . filter ( invoice = self ) return total_amount ( invoice_charges ) - total_amount ( invoice_transactions ) | The amount due for this invoice . Takes into account all entities in the invoice . Can be < 0 if the invoice was overpaid . | 54 | 27 |
14,565 | def setup ( ) : install_requirements = [ "attrdict" ] if sys . version_info [ : 2 ] < ( 3 , 4 ) : install_requirements . append ( "pathlib" ) setup_requirements = [ 'six' , 'setuptools>=17.1' , 'setuptools_scm' ] needs_sphinx = { 'build_sphinx' , 'docs' , 'upload_docs' , } . intersection ( sys . argv ) if needs_sphinx : setup_requirements . append ( 'sphinx' ) setuptools . setup ( author = "David Gidwani" , author_email = "david.gidwani@gmail.com" , classifiers = [ "Development Status :: 4 - Beta" , "Intended Audience :: Developers" , "License :: OSI Approved :: BSD License" , "Operating System :: OS Independent" , "Programming Language :: Python" , "Programming Language :: Python :: 2" , "Programming Language :: Python :: 2.7" , "Programming Language :: Python :: 3" , "Programming Language :: Python :: 3.3" , "Programming Language :: Python :: 3.4" , "Topic :: Software Development" , "Topic :: Software Development :: Libraries :: Python Modules" , ] , description = "Painless access to namespaced environment variables" , download_url = "https://github.com/darvid/biome/tarball/0.1" , install_requires = install_requirements , keywords = "conf config configuration environment" , license = "BSD" , long_description = readme ( ) , name = "biome" , package_dir = { '' : 'src' } , packages = setuptools . find_packages ( './src' ) , setup_requires = setup_requirements , tests_require = [ "pytest" ] , url = "https://github.com/darvid/biome" , use_scm_version = True , ) | Package setup entrypoint . | 446 | 5 |
14,566 | def preprocessor ( accepts , exports , flag = None ) : def decorator ( f ) : preprocessors . append ( ( accepts , exports , flag , f ) ) return f return decorator | Decorator to add a new preprocessor | 41 | 9 |
14,567 | def postprocessor ( accepts , flag = None ) : def decorator ( f ) : postprocessors . append ( ( accepts , flag , f ) ) return f return decorator | Decorator to add a new postprocessor | 37 | 9 |
14,568 | def coffee ( input , output , * * kw ) : subprocess . call ( [ current_app . config . get ( 'COFFEE_BIN' ) , '-c' , '-o' , output , input ] ) | Process CoffeeScript files | 52 | 4 |
14,569 | def cancel_charge ( charge_id : str ) -> None : logger . info ( 'cancelling-charge' , charge_id = charge_id ) with transaction . atomic ( ) : charge = Charge . all_charges . get ( pk = charge_id ) if charge . deleted : raise ChargeAlreadyCancelledError ( "Cannot cancel deleted charge." ) if Charge . all_charges . filter ( reverses = charge_id ) . exists ( ) : raise ChargeAlreadyCancelledError ( "Cannot cancel reversed charge." ) if charge . invoice is None : charge . deleted = True charge . save ( ) else : add_charge ( account_id = charge . account_id , reverses_id = charge_id , amount = - charge . amount , product_code = REVERSAL_PRODUCT_CODE ) | Cancels an existing charge . | 179 | 7 |
14,570 | def _log_request ( self , request ) : msg = [ ] for d in self . LOG_DATA : val = getattr ( request , d ) if val : msg . append ( d + ': ' + repr ( val ) ) for d in self . LOG_HEADERS : if d in request . headers and request . headers [ d ] : msg . append ( d + ': ' + repr ( request . headers [ d ] ) ) logger . info ( "Request information: %s" , ', ' . join ( msg ) ) | Log the most important parts of this request . | 115 | 9 |
14,571 | def get_mortgage_payment_per_payment_frequency ( self ) : # Calculate the interest rate per the payment parameters: r = self . get_interest_rate_per_payment_frequency ( ) # Calculate the total number of payments given the parameters: n = self . get_total_number_of_payments_per_frequency ( ) # Variables used as number holders. p = self . _loan_amount mortgage = None top = None bottom = None top = r + 1 top = math . pow ( top , n ) top = r * top bottom = r + 1 bottom = math . pow ( bottom , n ) bottom = bottom - 1 if bottom == 0 : return Money ( amount = 0.00 , currency = self . _currency ) mortgage = ( top / bottom ) mortgage = mortgage * p return mortgage | Function will return the amount paid per payment based on the frequency . | 178 | 13 |
14,572 | def info ( self ) : url = self . api_url + self . info_url resp = self . session . get ( url ) if resp . status_code != 200 : error = { 'description' : "Info HTTP response not valid" } raise CFException ( error , resp . status_code ) try : info = resp . json ( ) except ValueError as e : error = { 'description' : "Info HTTP response not valid, %s" % str ( e ) } raise CFException ( error , resp . status_code ) return info | Gets info endpoint . Used to perform login auth . | 117 | 11 |
14,573 | def clean_blobstore_cache ( self ) : url = self . api_url + self . blobstores_builpack_cache_url resp , rcode = self . request ( 'DELETE' , url ) if rcode != 202 : raise CFException ( resp , rcode ) return resp | Deletes all of the existing buildpack caches in the blobstore | 66 | 13 |
14,574 | def search ( self , query , locations : list = None ) : cas_number = re . search ( r"\b[1-9]{1}[0-9]{1,5}-\d{2}-\d\b" , str ( query ) ) if cas_number : query = cas_number [ 0 ] search_type = 'cas' else : try : query = int ( query ) search_type = 'barcode' except ValueError : query = f"%{query}%" search_type = 'name' if not locations : locations = self . get_locations ( filter_to_my_group = True ) locations = [ loc . inventory_id for loc in locations ] data = { 'groupid' : self . groupid , 'searchtype' : search_type , 'searchterm' : query , 'limitlocations' : locations . append ( 1 ) } r = self . _post ( 'search-search' , referer_path = 'search' , data = data ) #return a list of container objects if r [ 'searchresults' ] [ 'containers' ] : containers = [ ] for container in r [ 'searchresults' ] [ 'containers' ] : loc = Location ( name = container . get ( 'location' ) ) ct = Container ( inventory_id = container . get ( 'id' ) , compound_id = container . get ( 'sid' ) , name = container . get ( 'containername' ) , location = loc , size = container . get ( 'size' ) , smiles = container . get ( 'smiles' ) , cas = container . get ( 'cas' ) , comments = container . get ( 'comments' ) , barcode = container . get ( 'barcode' ) , supplier = container . get ( 'supplier' ) , date_acquired = container . get ( 'dateacquired' ) , owner = container . get ( 'owner' ) ) containers . append ( ct ) return containers else : return [ ] | Search using the CAS number barcode or chemical name | 443 | 10 |
14,575 | def get_groups ( self ) : resp = self . _post ( 'general-retrievelocations' , 'locations' ) final_resp = [ ] if resp [ 'groupinfo' ] : for group in resp [ 'groupinfo' ] : final_resp . append ( Group ( name = group . get ( 'name' ) , inventory_id = group . get ( 'id' ) ) ) return final_resp | Retrieve groups listed in ChemInventory | 92 | 8 |
14,576 | def get_locations ( self , filter_to_my_group = False ) : resp = self . _post ( 'general-retrievelocations' , 'locations' ) groups = { } if resp [ 'groupinfo' ] : for group in resp [ 'groupinfo' ] : groups [ group [ 'id' ] ] = Group ( name = group . get ( 'name' ) , inventory_id = group . get ( 'id' ) ) final_resp = [ ] if resp [ 'data' ] : if filter_to_my_group : resp [ 'data' ] = { self . groupid : resp [ 'data' ] [ self . groupid ] } for groupid , sublocation in resp [ 'data' ] . items ( ) : if type ( sublocation ) is dict : sublocation = [ loc for _ , loc in sublocation . items ( ) ] sublocation = flatten_list ( sublocation ) if type ( sublocation ) is list : sublocation = flatten_list ( sublocation ) for location in sublocation : group = groups [ groupid ] final_resp . append ( Location ( name = location . get ( 'name' ) , inventory_id = location . get ( 'id' ) , parent = location . get ( 'parent' ) , group = group , barcode = location . get ( 'barcode' ) ) ) return final_resp | Retrieve Locations listed in ChemInventory | 303 | 8 |
14,577 | def get_containers ( self , include_only = [ ] ) : locations = self . get_locations ( ) if len ( locations ) == 0 : raise ValueError ( "No locations for containers exist in Cheminventory" ) final_locations = [ ] if include_only : for location in locations : check = location in include_only or location . group in include_only if check : final_locations . append ( location ) if len ( final_locations ) == 0 : raise ValueError ( f"Location(s) or group(s) {include_only} is/are not in the database." ) else : final_locations = locations containers = [ ] for location in final_locations : containers += self . _get_location_containers ( location . inventory_id ) return containers | Download all the containers owned by a group | 174 | 8 |
14,578 | def get_unicode_str ( obj ) : if isinstance ( obj , six . text_type ) : return obj if isinstance ( obj , six . binary_type ) : return obj . decode ( "utf-8" , errors = "ignore" ) return six . text_type ( obj ) | Makes sure obj is a unicode string . | 65 | 10 |
14,579 | def init_log ( log_level ) : log_level = log_level or "INFO" logging . basicConfig ( format = "%(name)s:%(levelname)s:%(message)s" , level = getattr ( logging , log_level . upper ( ) , logging . INFO ) , ) | Initializes logging . | 69 | 4 |
14,580 | def get_xml_root ( xml_file ) : try : xml_root = etree . parse ( os . path . expanduser ( xml_file ) , NO_BLANKS_PARSER ) . getroot ( ) # pylint: disable=broad-except except Exception as err : raise Dump2PolarionException ( "Failed to parse XML file '{}': {}" . format ( xml_file , err ) ) return xml_root | Returns XML root . | 100 | 4 |
14,581 | def get_xml_root_from_str ( xml_str ) : try : xml_root = etree . fromstring ( xml_str . encode ( "utf-8" ) , NO_BLANKS_PARSER ) # pylint: disable=broad-except except Exception as err : raise Dump2PolarionException ( "Failed to parse XML string: {}" . format ( err ) ) return xml_root | Returns XML root from string . | 94 | 6 |
14,582 | def prettify_xml ( xml_root ) : xml_string = etree . tostring ( xml_root , encoding = "utf-8" , xml_declaration = True , pretty_print = True ) return get_unicode_str ( xml_string ) | Returns pretty - printed string representation of element tree . | 58 | 10 |
14,583 | def get_session ( credentials , config ) : session = requests . Session ( ) session . verify = False auth_url = config . get ( "auth_url" ) if auth_url : cookie = session . post ( auth_url , data = { "j_username" : credentials [ 0 ] , "j_password" : credentials [ 1 ] , "submit" : "Log In" , "rememberme" : "true" , } , headers = { "Content-Type" : "application/x-www-form-urlencoded" } , ) if not cookie : raise Dump2PolarionException ( "Cookie was not retrieved from {}." . format ( auth_url ) ) else : # TODO: can be removed once basic auth is discontinued on prod session . auth = credentials return session | Gets requests session . | 174 | 5 |
14,584 | def find_vcs_root ( path , dirs = ( ".git" , ) ) : prev , path = None , os . path . abspath ( path ) while prev != path : if any ( os . path . exists ( os . path . join ( path , d ) ) for d in dirs ) : return path prev , path = path , os . path . abspath ( os . path . join ( path , os . pardir ) ) return None | Searches up from a given path to find the project root . | 99 | 14 |
14,585 | def pack ( self ) : pack_name = self . args . prefix + op . basename ( self . path ) pack_path = op . join ( self . args . output or self . basedir , pack_name ) self . out ( "Packing: %s" % self . path ) self . out ( "Output: %s" % pack_path ) if self . args . format : ext = self . get_ext ( self . path ) self . parsers [ ext ] = self . args . format out = "" . join ( self . merge ( self . parse ( self . path ) ) ) try : open ( pack_path , 'w' ) . write ( out ) self . out ( "Linked file saved as: '%s'." % pack_path ) except IOError , ex : raise ZetaError ( ex ) | Pack and save file | 181 | 4 |
14,586 | def parse_path ( self , path , curdir ) : if path . startswith ( 'http://' ) : return path elif path . startswith ( 'zeta://' ) : zpath = op . join ( LIBDIR , path [ len ( 'zeta://' ) : ] ) if self . args . directory and not op . exists ( zpath ) : return op . join ( self . args . directory , path [ len ( 'zeta://' ) : ] ) return zpath return op . abspath ( op . normpath ( op . join ( curdir , path ) ) ) | Normilize path . | 131 | 5 |
14,587 | def out ( msg , error = False ) : pipe = stdout if error : pipe = stderr msg = color_msg ( msg , "warning" ) pipe . write ( "%s\n" % msg ) | Send message to shell | 46 | 4 |
14,588 | def _image_url ( image , dst_color = None , src_color = None ) : if src_color and dst_color : if not Image : raise Exception ( "Images manipulation require PIL" ) file = StringValue ( image ) . value path = None if callable ( STATIC_ROOT ) : try : _file , _storage = list ( STATIC_ROOT ( file ) ) [ 0 ] d_obj = _storage . modified_time ( _file ) filetime = int ( time . mktime ( d_obj . timetuple ( ) ) ) if dst_color : path = _storage . open ( _file ) except : filetime = 'NA' else : _path = os . path . join ( STATIC_ROOT , file ) if os . path . exists ( _path ) : filetime = int ( os . path . getmtime ( _path ) ) if dst_color : path = open ( _path , 'rb' ) else : filetime = 'NA' BASE_URL = STATIC_URL if path : src_color = tuple ( int ( round ( c ) ) for c in ColorValue ( src_color ) . value [ : 3 ] ) if src_color else ( 0 , 0 , 0 ) dst_color = [ int ( round ( c ) ) for c in ColorValue ( dst_color ) . value [ : 3 ] ] file_name , file_ext = os . path . splitext ( os . path . normpath ( file ) . replace ( '\\' , '_' ) . replace ( '/' , '_' ) ) key = ( filetime , src_color , dst_color ) key = file_name + '-' + base64 . urlsafe_b64encode ( hashlib . md5 ( repr ( key ) ) . digest ( ) ) . rstrip ( '=' ) . replace ( '-' , '_' ) asset_file = key + file_ext asset_path = os . path . join ( ASSETS_ROOT , asset_file ) if os . path . exists ( asset_path ) : file = asset_file BASE_URL = ASSETS_URL filetime = int ( os . path . getmtime ( asset_path ) ) else : image = Image . open ( path ) image = image . convert ( "RGBA" ) pixdata = image . load ( ) for y in xrange ( image . size [ 1 ] ) : for x in xrange ( image . size [ 0 ] ) : if pixdata [ x , y ] [ : 3 ] == src_color : new_color = tuple ( dst_color + [ pixdata [ x , y ] [ 3 ] ] ) pixdata [ x , y ] = new_color try : image . save ( asset_path ) file = asset_file BASE_URL = ASSETS_URL except IOError : log . exception ( "Error while saving image" ) url = 'url("%s%s?_=%s")' % ( BASE_URL , file , filetime ) return StringValue ( url ) | Generates a path to an asset found relative to the project s images directory . | 670 | 16 |
14,589 | def _image_width ( image ) : if not Image : raise Exception ( "Images manipulation require PIL" ) file = StringValue ( image ) . value path = None try : width = sprite_images [ file ] [ 0 ] except KeyError : width = 0 if callable ( STATIC_ROOT ) : try : _file , _storage = list ( STATIC_ROOT ( file ) ) [ 0 ] path = _storage . open ( _file ) except : pass else : _path = os . path . join ( STATIC_ROOT , file ) if os . path . exists ( _path ) : path = open ( _path , 'rb' ) if path : image = Image . open ( path ) size = image . size width = size [ 0 ] sprite_images [ file ] = size return NumberValue ( width , 'px' ) | Returns the width of the image found at the path supplied by image relative to your project s images directory . | 183 | 21 |
14,590 | def _nth ( lst , n = 1 ) : n = StringValue ( n ) . value lst = ListValue ( lst ) . value try : n = int ( float ( n ) ) - 1 n = n % len ( lst ) except : if n . lower ( ) == 'first' : n = 0 elif n . lower ( ) == 'last' : n = - 1 try : ret = lst [ n ] except KeyError : lst = [ v for k , v in sorted ( lst . items ( ) ) if isinstance ( k , int ) ] try : ret = lst [ n ] except : ret = '' return ret . __class__ ( ret ) | Return the Nth item in the string | 151 | 8 |
14,591 | def normalize_selectors ( self , _selectors , extra_selectors = None , extra_parents = None ) : # Fixe tabs and spaces in selectors _selectors = _spaces_re . sub ( ' ' , _selectors ) if isinstance ( extra_selectors , basestring ) : extra_selectors = extra_selectors . split ( ',' ) if isinstance ( extra_parents , basestring ) : extra_parents = extra_parents . split ( '&' ) parents = set ( ) if ' extends ' in _selectors : selectors = set ( ) for key in _selectors . split ( ',' ) : child , _ , parent = key . partition ( ' extends ' ) child = child . strip ( ) parent = parent . strip ( ) selectors . add ( child ) parents . update ( s . strip ( ) for s in parent . split ( '&' ) if s . strip ( ) ) else : selectors = set ( s . strip ( ) for s in _selectors . split ( ',' ) if s . strip ( ) ) if extra_selectors : selectors . update ( s . strip ( ) for s in extra_selectors if s . strip ( ) ) selectors . discard ( '' ) if not selectors : return '' if extra_parents : parents . update ( s . strip ( ) for s in extra_parents if s . strip ( ) ) parents . discard ( '' ) if parents : return ',' . join ( sorted ( selectors ) ) + ' extends ' + '&' . join ( sorted ( parents ) ) return ',' . join ( sorted ( selectors ) ) | Normalizes or extends selectors in a string . An optional extra parameter that can be a list of extra selectors to be added to the final normalized selectors string . | 357 | 34 |
14,592 | def _get_properties ( self , rule , p_selectors , p_parents , p_children , scope , media , c_lineno , c_property , c_codestr ) : prop , value = ( _prop_split_re . split ( c_property , 1 ) + [ None ] ) [ : 2 ] try : is_var = ( c_property [ len ( prop ) ] == '=' ) except IndexError : is_var = False prop = prop . strip ( ) prop = self . do_glob_math ( prop , rule [ CONTEXT ] , rule [ OPTIONS ] , rule , True ) if prop : if value : value = value . strip ( ) value = self . calculate ( value , rule [ CONTEXT ] , rule [ OPTIONS ] , rule ) _prop = ( scope or '' ) + prop if is_var or prop . startswith ( '$' ) and value is not None : if isinstance ( value , basestring ) : if '!default' in value : if _prop in rule [ CONTEXT ] : value = None else : value = value . replace ( '!default' , '' ) . replace ( ' ' , ' ' ) . strip ( ) elif isinstance ( value , ListValue ) : value = ListValue ( value ) for k , v in value . value . items ( ) : if v == '!default' : if _prop in rule [ CONTEXT ] : value = None else : del value . value [ k ] value = value . first ( ) if len ( value ) == 1 else value break if value is not None : rule [ CONTEXT ] [ _prop ] = value else : _prop = self . apply_vars ( _prop , rule [ CONTEXT ] , rule [ OPTIONS ] , rule , True ) rule [ PROPERTIES ] . append ( ( c_lineno , _prop , to_str ( value ) if value is not None else None ) ) | Implements properties and variables extraction | 423 | 7 |
14,593 | def link_with_parents ( self , parent , c_selectors , c_rules ) : parent_found = None for p_selectors , p_rules in self . parts . items ( ) : _p_selectors , _ , _ = p_selectors . partition ( ' extends ' ) _p_selectors = _p_selectors . split ( ',' ) new_selectors = set ( ) found = False # Finds all the parent selectors and parent selectors with another # bind selectors behind. For example, if `.specialClass extends # .baseClass`, # and there is a `.baseClass` selector, the extension should create # `.specialClass` for that rule, but if there's also a `.baseClass # a` # it also should create `.specialClass a` for p_selector in _p_selectors : if parent in p_selector : # get the new child selector to add (same as the parent # selector but with the child name) # since selectors can be together, separated with # or . # (i.e. something.parent) check that too: for c_selector in c_selectors . split ( ',' ) : # Get whatever is different between the two selectors: _c_selector , _parent = c_selector , parent lcp = self . longest_common_prefix ( _c_selector , _parent ) if lcp : _c_selector = _c_selector [ lcp : ] _parent = _parent [ lcp : ] lcs = self . longest_common_suffix ( _c_selector , _parent ) if lcs : _c_selector = _c_selector [ : - lcs ] _parent = _parent [ : - lcs ] if _c_selector and _parent : # Get the new selectors: prev_symbol = '(?<![#.:])' if _parent [ 0 ] in ( '#' , '.' , ':' ) else r'(?<![-\w#.:])' post_symbol = r'(?![-\w])' new_parent = re . sub ( prev_symbol + _parent + post_symbol , _c_selector , p_selector ) if p_selector != new_parent : new_selectors . add ( new_parent ) found = True if found : # add parent: parent_found = parent_found or [ ] parent_found . extend ( p_rules ) if new_selectors : new_selectors = self . normalize_selectors ( p_selectors , new_selectors ) # rename node: if new_selectors != p_selectors : del self . parts [ p_selectors ] self . parts . setdefault ( new_selectors , [ ] ) self . parts [ new_selectors ] . extend ( p_rules ) deps = set ( ) # save child dependencies: for c_rule in c_rules or [ ] : c_rule [ SELECTORS ] = c_selectors # re-set the SELECTORS for the rules deps . add ( c_rule [ POSITION ] ) for p_rule in p_rules : p_rule [ SELECTORS ] = new_selectors # re-set the SELECTORS for the rules p_rule [ DEPS ] . update ( deps ) # position is the "index" of the object return parent_found | Link with a parent for the current child rule . If parents found returns a list of parent rules to the child | 754 | 22 |
14,594 | def parse_extends ( self ) : # To be able to manage multiple extends, you need to # destroy the actual node and create many nodes that have # mono extend. The first one gets all the css rules for _selectors , rules in self . parts . items ( ) : if ' extends ' in _selectors : selectors , _ , parent = _selectors . partition ( ' extends ' ) parents = parent . split ( '&' ) del self . parts [ _selectors ] for parent in parents : new_selectors = selectors + ' extends ' + parent self . parts . setdefault ( new_selectors , [ ] ) self . parts [ new_selectors ] . extend ( rules ) rules = [ ] # further rules extending other parents will be empty cnt = 0 parents_left = True while parents_left and cnt < 10 : cnt += 1 parents_left = False for _selectors in self . parts . keys ( ) : selectors , _ , parent = _selectors . partition ( ' extends ' ) if parent : parents_left = True if _selectors not in self . parts : continue # Nodes might have been renamed while linking parents... rules = self . parts [ _selectors ] del self . parts [ _selectors ] self . parts . setdefault ( selectors , [ ] ) self . parts [ selectors ] . extend ( rules ) parents = self . link_with_parents ( parent , selectors , rules ) if parents is None : log . warn ( "Parent rule not found: %s" , parent ) else : # from the parent, inherit the context and the options: new_context = { } new_options = { } for parent in parents : new_context . update ( parent [ CONTEXT ] ) new_options . update ( parent [ OPTIONS ] ) for rule in rules : _new_context = new_context . copy ( ) _new_context . update ( rule [ CONTEXT ] ) rule [ CONTEXT ] = _new_context _new_options = new_options . copy ( ) _new_options . update ( rule [ OPTIONS ] ) rule [ OPTIONS ] = _new_options | For each part create the inheritance parts from the extends | 465 | 10 |
14,595 | def _wrap ( fn ) : def _func ( * args ) : merged = None _args = [ ] for arg in args : if merged . __class__ != arg . __class__ : if merged is None : merged = arg . __class__ ( None ) else : merged = Value . _merge_type ( merged , arg ) ( None ) merged . merge ( arg ) if isinstance ( arg , Value ) : arg = arg . value _args . append ( arg ) merged . value = fn ( * _args ) return merged return _func | Wrapper function to allow calling any function using Value objects as parameters . | 117 | 14 |
14,596 | def token ( self , i , restrict = None ) : tokens_len = len ( self . tokens ) if i == tokens_len : # We are at the end, ge the next... tokens_len += self . scan ( restrict ) if i < tokens_len : if restrict and self . restrictions [ i ] and restrict > self . restrictions [ i ] : raise NotImplementedError ( "Unimplemented: restriction set changed" ) return self . tokens [ i ] raise NoMoreTokens ( ) | Get the i th token and if i is one past the end then scan for another token ; restrict is a list of tokens that are allowed or 0 for any token . | 107 | 34 |
14,597 | def scan ( self , restrict ) : # Keep looking for a token, ignoring any in self.ignore while True : # Search the patterns for a match, with earlier # tokens in the list having preference best_pat = None best_pat_len = 0 for p , regexp in self . patterns : # First check to see if we're restricting to this token if restrict and p not in restrict and p not in self . ignore : continue m = regexp . match ( self . input , self . pos ) if m : # We got a match best_pat = p best_pat_len = len ( m . group ( 0 ) ) break # If we didn't find anything, raise an error if best_pat is None : msg = "Bad Token" if restrict : msg = "Trying to find one of " + ", " . join ( restrict ) raise SyntaxError ( self . pos , msg ) # If we found something that isn't to be ignored, return it if best_pat in self . ignore : # This token should be ignored .. self . pos += best_pat_len else : end_pos = self . pos + best_pat_len # Create a token with this data token = ( self . pos , end_pos , best_pat , self . input [ self . pos : end_pos ] ) self . pos = end_pos # Only add this token if it's not in the list # (to prevent looping) if not self . tokens or token != self . tokens [ - 1 ] : self . tokens . append ( token ) self . restrictions . append ( restrict ) return 1 break return 0 | Should scan another token and add it to the list self . tokens and add the restriction to self . restrictions | 343 | 21 |
14,598 | def main ( ) : # Detector positions in ENU relative to the station GPS x = [ - 6.34 , - 2.23 , - 3.6 , 3.46 ] y = [ 6.34 , 2.23 , - 3.6 , 3.46 ] # Scale mips to fit the graph n = [ 35.0 , 51.9 , 35.8 , 78.9 ] # Make times relative to first detection t = [ 15. , 17.5 , 20. , 27.5 ] dt = [ ti - min ( t ) for ti in t ] plot = Plot ( ) plot . scatter ( [ 0 ] , [ 0 ] , mark = 'triangle' ) plot . add_pin_at_xy ( 0 , 0 , 'Station 503' , use_arrow = False , location = 'below' ) plot . scatter_table ( x , y , dt , n ) plot . set_scalebar ( location = "lower right" ) plot . set_colorbar ( '$\Delta$t [ns]' ) plot . set_axis_equal ( ) plot . set_mlimits ( max = 16. ) plot . set_slimits ( min = 10. , max = 100. ) plot . set_xlabel ( 'x [m]' ) plot . set_ylabel ( 'y [m]' ) plot . save ( 'event_display' ) # Add event by Station 508 # Detector positions in ENU relative to the station GPS x508 = [ 6.12 , 0.00 , - 3.54 , 3.54 ] y508 = [ - 6.12 , - 13.23 , - 3.54 , 3.54 ] # Event GPS timestamp: 1371498167.016412100 # MIPS n508 = [ 5.6 , 16.7 , 36.6 , 9.0 ] # Arrival Times t508 = [ 15. , 22.5 , 22.5 , 30. ] dt508 = [ ti - min ( t508 ) for ti in t508 ] plot = MultiPlot ( 1 , 2 , width = r'.33\linewidth' ) plot . set_xlimits_for_all ( min = - 10 , max = 15 ) plot . set_ylimits_for_all ( min = - 15 , max = 10 ) plot . set_mlimits_for_all ( min = 0. , max = 16. ) plot . set_colorbar ( '$\Delta$t [ns]' , False ) plot . set_colormap ( 'blackwhite' ) plot . set_scalebar_for_all ( location = "upper right" ) p = plot . get_subplot_at ( 0 , 0 ) p . scatter ( [ 0 ] , [ 0 ] , mark = 'triangle' ) p . add_pin_at_xy ( 0 , 0 , 'Station 503' , use_arrow = False , location = 'below' ) p . scatter_table ( x , y , dt , n ) p . set_axis_equal ( ) p = plot . get_subplot_at ( 0 , 1 ) p . scatter ( [ 0 ] , [ 0 ] , mark = 'triangle' ) p . add_pin_at_xy ( 0 , 0 , 'Station 508' , use_arrow = False , location = 'below' ) p . scatter_table ( x508 , y508 , dt508 , n508 ) p . set_axis_equal ( ) plot . show_yticklabels_for_all ( [ ( 0 , 0 ) ] ) plot . show_xticklabels_for_all ( [ ( 0 , 0 ) , ( 0 , 1 ) ] ) plot . set_xlabel ( 'x [m]' ) plot . set_ylabel ( 'y [m]' ) plot . save ( 'multi_event_display' ) | Event display for an event of station 503 | 840 | 8 |
14,599 | def _model_unpickle ( cls , data ) : auto_field_value = data [ 'pk' ] try : obj = cls . objects . get ( pk = auto_field_value ) except Exception as e : if isinstance ( e , OperationalError ) : # Attempt reconnect, we've probably hit; # OperationalError(2006, 'MySQL server has gone away') logger . debug ( "Caught OperationalError, closing database connection." , exc_info = e ) from django . db import connection connection . close ( ) obj = cls . objects . get ( pk = auto_field_value ) else : raise return obj | Unpickle a model by retrieving it from the database . | 144 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.