idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
58,100
def execute ( self , mold_id , data , wrapper_tag = 'div' ) : template = self . load_mold ( mold_id ) kwargs = { } kwargs . update ( data ) kwargs [ '_nunja_data_' ] = 'data-nunja="%s"' % mold_id kwargs [ '_template_' ] = template kwargs [ '_wrapper_tag_' ] = wrapper_tag return self . _core_template_ . render ( ** kwar...
Execute a mold mold_id by rendering through env .
58,101
def render ( self , mold_id , data ) : template = self . load_mold ( mold_id ) return template . render ( ** data )
Render a mold mold_id . No wrappers are applied as only the default template defined for the mold is rendered .
58,102
def _get_model_table ( self , part ) : rows = self . parser . find ( part ) . find_children ( 'tr' ) . list_results ( ) table = [ ] for row in rows : table . append ( self . _get_model_row ( self . parser . find ( row ) . find_children ( 'td,th' ) . list_results ( ) ) ) return self . _get_valid_model_table ( table )
Returns a list that represents the table .
58,103
def _get_valid_model_table ( self , ros ) : new_table = [ ] if bool ( ros ) : length_table = len ( ros ) for row_index in range ( 0 , length_table ) : cells_added = 0 original_row = [ ] + ros [ row_index ] if len ( new_table ) <= row_index : new_table . append ( [ ] ) length_row = len ( original_row ) for cell_index in...
Returns a list that represents the table with the rowspans .
58,104
def _get_model_row ( self , row ) : new_row = [ ] + row size = len ( row ) for i in range ( 0 , size ) : cell = row [ i ] if cell . has_attribute ( 'colspan' ) : colspan = int ( cell . get_attribute ( 'colspan' ) ) if colspan > 1 : for j in range ( 1 , colspan ) : new_row . insert ( i + j , cell ) return new_row
Returns a list that represents the line of table with the colspans .
58,105
def _validate_header ( self , hed ) : if not bool ( hed ) : return False length = - 1 for row in hed : if not bool ( row ) : return False elif length == - 1 : length = len ( row ) elif len ( row ) != length : return False return True
Validate the list that represents the table header .
58,106
def _get_cells_headers_ids ( self , hed , index ) : ids = [ ] for row in hed : if row [ index ] . get_tag_name ( ) == 'TH' : ids . append ( row [ index ] . get_attribute ( 'id' ) ) return ids
Returns a list with ids of rows of same column .
58,107
def _associate_data_cells_with_header_cells_of_row ( self , element ) : table = self . _get_model_table ( element ) for row in table : headers_ids = [ ] for cell in row : if cell . get_tag_name ( ) == 'TH' : self . id_generator . generate_id ( cell ) headers_ids . append ( cell . get_attribute ( 'id' ) ) cell . set_att...
Associate the data cell with header cell of row .
58,108
def _prepare_header_cells ( self , table_header ) : cells = self . parser . find ( table_header ) . find_children ( 'tr' ) . find_children ( 'th' ) . list_results ( ) for cell in cells : self . id_generator . generate_id ( cell ) cell . set_attribute ( 'scope' , 'col' )
Set the scope of header cells of table header .
58,109
def encrypt ( clear_text ) -> str : if not isinstance ( clear_text , bytes ) : clear_text = str . encode ( clear_text ) cipher = Fernet ( current_app . config [ 'KEY' ] ) return cipher . encrypt ( clear_text ) . decode ( "utf-8" )
Use config . json key to encrypt
58,110
def decrypt ( crypt_text ) -> str : cipher = Fernet ( current_app . config [ 'KEY' ] ) if not isinstance ( crypt_text , bytes ) : crypt_text = str . encode ( crypt_text ) return cipher . decrypt ( crypt_text ) . decode ( "utf-8" )
Use config . json key to decrypt
58,111
def get_volume ( self , id ) : if exists ( id ) : with open ( id ) as file : size = os . lseek ( file . fileno ( ) , 0 , os . SEEK_END ) return { 'path' : id , 'size' : size } return self . volume . get ( id )
return volume information if the argument is an id or a path
58,112
def randomize ( self , device = None , percent = 100 , silent = False ) : volume = self . get_volume ( device ) blocks = int ( volume [ 'size' ] / BLOCK_SIZE ) num_writes = int ( blocks * percent * 0.01 ) offsets = sorted ( random . sample ( range ( blocks ) , num_writes ) ) total = 0 if not silent : print ( 'Writing u...
Writes random data to the beginning of each 4MB block on a block device this is useful when performance testing the backup process
58,113
def backup ( self , id = None , src = None , timestamp = None ) : logging . basicConfig ( ) log = logger . get_logger ( ) log . logger . setLevel ( logging . DEBUG ) conf = LunrConfig . from_storage_conf ( ) timestamp = timestamp or time ( ) volume = VolumeHelper ( conf ) backup = BackupHelper ( conf ) try : snapshot =...
This runs a backup job outside of the storage api which is useful for performance testing backups
58,114
def get_ip ( request ) : if getsetting ( 'LOCAL_GEOLOCATION_IP' ) : return getsetting ( 'LOCAL_GEOLOCATION_IP' ) forwarded_for = request . META . get ( 'HTTP_X_FORWARDED_FOR' ) if not forwarded_for : return UNKNOWN_IP for ip in forwarded_for . split ( ',' ) : ip = ip . strip ( ) if not ip . startswith ( '10.' ) and not...
Return the IP address inside the HTTP_X_FORWARDED_FOR var inside the request object .
58,115
def get_connection ( self ) : if self . conn : return self . conn redis_configs = getsetting ( 'REDIS_CONNECTIONS' ) if redis_configs : config_name = getsetting ( 'EVENTLIB_REDIS_CONFIG_NAME' , 'default' ) config = redis_configs [ config_name ] host = config [ 'HOST' ] port = config [ 'PORT' ] self . conn = redis . Str...
Return a valid redis connection based on the following settings
58,116
def _run_setup_py ( self , args , echo = True , echo2 = True , ff = '' ) : python = self . python if ff : setup_py = '-c"%s"' % ( RUN_SETUP % locals ( ) ) else : setup_py = 'setup.py %s' % ' ' . join ( args ) rc , lines = self . process . popen ( '"%(python)s" %(setup_py)s' % locals ( ) , echo = echo , echo2 = echo2 ) ...
Run setup . py with monkey - patched setuptools .
58,117
def app_factory ( global_settings , ** local_settings ) : config = Configurator ( ) config . setup_registry ( settings = local_settings , root_factory = RootFactory ( ) ) if 'configure_zcml' in local_settings : config . load_zcml ( local_settings [ 'configure_zcml' ] ) app = config . make_wsgi_app ( ) app_name = app_na...
Default factory for creating a WSGI application using the everest configurator and root factory .
58,118
async def fetch_page ( session , host ) : await asyncio . sleep ( random . randint ( 0 , 25 ) * 0.1 ) start = time . time ( ) logger . info ( 'Fetch from {}' . format ( host ) ) try : response = await session . get ( host , allow_redirects = False ) except aiohttp . ClientResponseError as err : results_tuple = ( host ,...
Perform the page fetch from an individual host .
58,119
async def asynchronous ( urls = None , re_filter = None ) : class _URLBase ( str ) : @ property def hostname ( self ) : return urlsplit ( self ) . hostname http_devices = { } qualified_devices = [ ] connection = aiohttp . TCPConnector ( limit = 0 ) async with aiohttp . ClientSession ( connector = connection , conn_time...
Asynchronous request manager for session . Returns list of responses that match the filter .
58,120
def url_generator ( network = None , path = '' ) : network_object = ipaddress . ip_network ( network ) if network_object . num_addresses > 256 : logger . error ( 'Scan limited to 256 addresses, requested %d.' , network_object . num_addresses ) raise NotImplementedError elif network_object . num_addresses > 1 : network_...
Return a tuple of URLs with path one for each host on network
58,121
def survey ( network = None , path = '' , pattern = '' , log = False ) : if log : logger . setLevel ( logging . DEBUG ) else : logger . setLevel ( logging . CRITICAL ) network_scan = asyncio . ensure_future ( asynchronous ( urls = url_generator ( network = network , path = path ) , re_filter = re . compile ( pattern ) ...
Search network for hosts with a response to path that matches pattern
58,122
def hidden_cursor ( ) : if sys . stdout . isatty ( ) : _LOGGER . debug ( 'Hiding cursor.' ) print ( '\x1B[?25l' , end = '' ) sys . stdout . flush ( ) try : yield finally : if sys . stdout . isatty ( ) : _LOGGER . debug ( 'Showing cursor.' ) print ( '\n\x1B[?25h' , end = '' ) sys . stdout . flush ( )
Temporarily hide the terminal cursor .
58,123
def display_status ( ) : def print_status ( msg , color ) : print ( '\r' if sys . stdout . isatty ( ) else '\t' , end = '' ) print ( '{}{}[{color}{msg}{}]{}' . format ( Cursor . FORWARD ( _ncols ( ) - 8 ) , Style . BRIGHT , Fore . RESET , Style . RESET_ALL , color = color , msg = msg [ : 6 ] . upper ( ) . center ( 6 ) ...
Display an OK or FAILED message for the context block .
58,124
def _pusher_connect_handler ( self , data ) : self . channel = self . pusher . subscribe ( self . pos_callback_chan ) for listener in self . pusher_connected_listeners : listener ( data )
Event handler for the connection_established event . Binds the shortlink_scanned event
58,125
def _runForever ( self , stop_event ) : while ( not stop_event . is_set ( ) ) : state = self . pusher . connection . state if ( state is not "connecting" and state is not "connected" ) : self . logger . warning ( "Pusher seems to be disconnected, trying to reconnect" ) self . pusher . connect ( ) stop_event . wait ( 0....
Runs the main loop
58,126
def stop ( self ) : self . pusherthread_stop . set ( ) self . pusher . disconnect ( ) while self . pusher . connection . state is "connected" : sleep ( 0.1 ) logging . info ( "shutting down pusher connector thread" )
Stops the pusherclient cleanly
58,127
def load ( self , filename , bs = 512 ) : with open ( filename , 'rb' ) as f : f . seek ( GPT_HEADER_OFFSET + 0x0C ) header_size = struct . unpack ( "<I" , f . read ( 4 ) ) [ 0 ] f . seek ( GPT_HEADER_OFFSET ) header_data = f . read ( header_size ) self . header = GPT_HEADER ( header_data ) if ( self . header . signatu...
Loads GPT partition table .
58,128
def global_to_local ( self , index ) : if ( type ( index ) is int ) or ( type ( index ) is slice ) : if len ( self . __mask ) > 1 : raise IndexError ( 'check length of parameter index' ) if type ( index ) is int : return self . int_global_to_local ( index ) elif type ( index ) is slice : return self . slice_global_to_l...
Calculate local index from global index
58,129
def int_global_to_local_start ( self , index , axis = 0 ) : if index >= self . __mask [ axis ] . stop - self . __halos [ 1 ] [ axis ] : return None if index < self . __mask [ axis ] . start : return 0 return index - self . __mask [ axis ] . start
Calculate local index from global index from start_index
58,130
def int_global_to_local_stop ( self , index , axis = 0 ) : if index < self . __mask [ axis ] . start + self . __halos [ 0 ] [ axis ] : return None if index > self . __mask [ axis ] . stop : return self . __mask [ axis ] . stop - self . __mask [ axis ] . start return index - self . __mask [ axis ] . start
Calculate local index from global index from stop_index
58,131
def int_global_to_local ( self , index , axis = 0 ) : if index >= self . __mask [ axis ] . stop - self . __halos [ 1 ] [ axis ] : return None if index < self . __mask [ axis ] . start + self . __halos [ 0 ] [ axis ] : return None return index - self . __mask [ axis ] . start
Calculate local index from global index for integer input
58,132
def int_out_of_bounds ( self , index , axis = 0 ) : if index > self . _global_shape [ axis ] : raise IndexError ( 'index is larger than the upper bound' ) if index < 0 : index += self . _global_shape [ axis ] if index < 0 : raise IndexError ( 'index is smaller than the lower bound' ) return index
examples if index is out of local processing bounds
58,133
def out_of_bounds ( self , index ) : if type ( index ) is int : return self . int_out_of_bounds ( index ) elif type ( index ) is slice : return self . slice_out_of_bounds ( index ) elif type ( index ) is tuple : local_index = [ ] for k , item in enumerate ( index ) : if type ( item ) is slice : temp_index = self . slic...
Check index for out of bounds
58,134
def get_server_setting ( self , protocol , host = '127.0.0.1' , port = 8000 , debug = False , ssl = None , sock = None , workers = 1 , loop = None , backlog = 100 , has_log = True ) : if isinstance ( ssl , dict ) : cert = ssl . get ( 'cert' ) or ssl . get ( 'certificate' ) key = ssl . get ( 'key' ) or ssl . get ( 'keyf...
Helper function used by run .
58,135
def verify ( path ) : valid = False try : h5 = h5py . File ( path , mode = "r" ) qpi0 = h5 [ "qpi_0" ] except ( OSError , KeyError ) : pass else : if ( "qpimage version" in qpi0 . attrs and "phase" in qpi0 and "amplitude" in qpi0 and "bg_data" in qpi0 [ "phase" ] and "bg_data" in qpi0 [ "amplitude" ] ) : valid = True r...
Verify that path has the qpimage series file format
58,136
def generate_requirements ( output_path = None ) : from django . conf import settings reqs = set ( ) for app in settings . INSTALLED_APPS : if app in mapping . keys ( ) : reqs |= set ( mapping [ app ] ) if output_path is None : print "--extra-index-url=http://opensource.washingtontimes.com/pypi/simple/" for item in req...
Loop through the INSTALLED_APPS and create a set of requirements for pip . if output_path is None then write to standard out otherwise write to the path .
58,137
def register_mbr_plugin ( self , fs_id , plugin ) : self . logger . debug ( 'MBR: {}, FS ID: {}' . format ( self . __get_plugin_name ( plugin ) , fs_id ) ) self . __mbr_plugins [ fs_id ] . append ( plugin )
Used in plugin s registration routine to associate it s detection method with given filesystem id
58,138
def register_gpt_plugin ( self , fs_guid , plugin ) : key = uuid . UUID ( fs_guid . lower ( ) ) self . logger . debug ( 'GPT: {}, GUID: {}' . format ( self . __get_plugin_name ( plugin ) , fs_guid ) ) self . __gpt_plugins [ key ] . append ( plugin )
Used in plugin s registration routine to associate it s detection method with given filesystem guid
58,139
def detect_mbr ( self , filename , offset , fs_id ) : self . logger . debug ( 'Detecting MBR partition type' ) if fs_id not in self . __mbr_plugins : return None else : plugins = self . __mbr_plugins . get ( fs_id ) for plugin in plugins : if plugin . detect ( filename , offset ) : return plugin . get_volume_object ( )...
Used by rawdisk . session . Session to match mbr partitions against filesystem plugins .
58,140
def detect_gpt ( self , filename , offset , fs_guid ) : self . logger . debug ( 'Detecting GPT partition type' ) if fs_guid not in self . __gpt_plugins : return None else : plugins = self . __gpt_plugins . get ( fs_guid ) for plugin in plugins : if plugin . detect ( filename , offset ) : return plugin . get_volume_obje...
Used by rawdisk . session . Session to match gpt partitions agains filesystem plugins .
58,141
def inject_documentation ( ** options ) : import cog loader = ConfigLoader ( ** options ) cog . out ( "\n" + loader . documentation + "\n\n" )
Generate configuration documentation in reStructuredText_ syntax .
58,142
def read_file ( self , filename ) : logger . info ( "Reading file: %s" , format_path ( filename ) ) contents = self . context . read_file ( filename ) num_lines = len ( contents . splitlines ( ) ) logger . debug ( "Read %s from %s." , pluralize ( num_lines , 'line' ) , format_path ( filename ) ) return contents . rstri...
Read a text file and provide feedback to the user .
58,143
def execute_file ( self , filename ) : logger . info ( "Executing file: %s" , format_path ( filename ) ) contents = self . context . execute ( filename , capture = True ) . stdout num_lines = len ( contents . splitlines ( ) ) logger . debug ( "Execution of %s yielded % of output." , format_path ( filename ) , pluralize...
Execute a file and provide feedback to the user .
58,144
def write_file ( self , filename , contents ) : logger . info ( "Writing file: %s" , format_path ( filename ) ) contents = contents . rstrip ( ) + b"\n" self . context . write_file ( filename , contents ) logger . debug ( "Wrote %s to %s." , pluralize ( len ( contents . splitlines ( ) ) , "line" ) , format_path ( filen...
Write a text file and provide feedback to the user .
58,145
def validate_input ( function ) : @ wraps ( function ) def wrapper ( * args , ** kwargs ) : try : name = function . __name__ + '_validator' globals ( ) [ name ] ( kwargs ) return function ( * args , ** kwargs ) except KeyError : raise Exception ( "Could not find validation schema for the" " function " + function . __na...
Decorator that validates the kwargs of the function passed to it .
58,146
def getModulePath ( project_path , module_name , verbose ) : if not module_name : return None sys . path . append ( project_path ) try : package = pkgutil . get_loader ( module_name ) except ImportError : if verbose : print ( "Parent module for " + module_name + " not found." ) return None except : if verbose : print (...
Searches for module_name in searchpath and returns the filepath . If no filepath was found returns None .
58,147
def getImportFromObjects ( node ) : somenames = [ x . asname for x in node . names if x . asname ] othernames = [ x . name for x in node . names if not x . asname ] return somenames + othernames
Returns a list of objects referenced by import from node
58,148
def as_slug_expression ( attr ) : slug_expr = sa_func . replace ( attr , ' ' , '-' ) slug_expr = sa_func . replace ( slug_expr , '_' , '-' ) slug_expr = sa_func . lower ( slug_expr ) return slug_expr
Converts the given instrumented string attribute into an SQL expression that can be used as a slug .
58,149
def mapper ( class_ , local_table = None , id_attribute = 'id' , slug_expression = None , * args , ** kwargs ) : mpr = sa_mapper ( class_ , local_table = local_table , * args , ** kwargs ) if id_attribute != 'id' : if 'id' in mpr . columns : mpr . dispose ( ) raise ValueError ( 'Attempting to overwrite the mapped "id" ...
Convenience wrapper around the SA mapper which will set up the hybrid id and slug attributes required by everest after calling the SA mapper .
58,150
def synonym ( name ) : return hybrid_property ( lambda inst : getattr ( inst , name ) , lambda inst , value : setattr ( inst , name , value ) , expr = lambda cls : getattr ( cls , name ) )
Utility function mimicking the behavior of the old SA synonym function with the new hybrid property semantics .
58,151
def map_system_entities ( engine , metadata , reset ) : msg_tbl = Table ( '_user_messages' , metadata , Column ( 'guid' , String , nullable = False , primary_key = True ) , Column ( 'text' , String , nullable = False ) , Column ( 'time_stamp' , DateTime ( timezone = True ) , nullable = False , default = sa_func . now (...
Maps all system entities .
58,152
def schematron ( self , fn = None , outfn = None , ext = '.sch' ) : from . xslt import XSLT from . import PATH , XML , etree fn = fn or self . fn if os . path . splitext ( fn ) [ - 1 ] . lower ( ) == ext : return fn elif os . path . splitext ( fn ) [ - 1 ] . lower ( ) != '.rng' : fn = Schema ( fn = fn ) . trang ( ext =...
convert the Schema to schematron and save at the given output filename or with the given extension .
58,153
def xhtml ( self , outfn = None , ext = '.xhtml' , css = None , ** params ) : from markdown import markdown from copy import deepcopy from bl . file import File from . xslt import XSLT from . rng import RNG from . import XML , PATH , etree rncfn = os . path . splitext ( self . fn ) [ 0 ] + '.rnc' rngfn = os . path . sp...
convert the Schema to XHTML with the given output filename or with the given extension .
58,154
def from_tag ( cls , tag , schemas , ext = '.rnc' ) : return cls ( fn = cls . filename ( tag , schemas , ext = ext ) )
load a schema using an element s tag . schemas can be a string or a list of strings
58,155
def filename ( cls , tag , schemas , ext = '.rnc' ) : if type ( schemas ) == str : schemas = re . split ( "\s*,\s*" , schemas ) for schema in schemas : fn = os . path . join ( schema , cls . dirname ( tag ) , cls . basename ( tag , ext = ext ) ) if os . path . exists ( fn ) : return fn
given a tag and a list of schemas return the filename of the schema . If schemas is a string treat it as a comma - separated list .
58,156
def errors_as_text ( self ) : errors = [ ] errors . append ( self . non_field_errors ( ) . as_text ( ) ) errors_data = self . errors . as_data ( ) for key , value in errors_data . items ( ) : field_label = self . fields [ key ] . label err_descn = '' . join ( [ force_text ( e . message ) for e in value ] ) error = "%s ...
only available to Django 1 . 7 +
58,157
def add_attr2fields ( self , attr_name , attr_val , fields = [ ] , exclude = [ ] , include_all_if_empty = True ) : for f in self . filter_fields ( fields , exclude , include_all_if_empty ) : f = self . fields [ f . name ] org_val = f . widget . attrs . get ( attr_name , '' ) f . widget . attrs [ attr_name ] = '%s %s' %...
add attr to fields
58,158
def add_class2fields ( self , html_class , fields = [ ] , exclude = [ ] , include_all_if_empty = True ) : self . add_attr2fields ( 'class' , html_class , fields , exclude )
add class to html widgets .
58,159
def as_required_fields ( self , fields = [ ] ) : fields = self . filter_fields ( fields ) for f in fields : f = self . fields [ f . name ] f . required = True
set required to True
58,160
def check_uniqe ( self , obj_class , error_msg = _ ( 'Must be unique' ) , ** kwargs ) : if obj_class . objects . filter ( ** kwargs ) . exclude ( pk = self . instance . pk ) : raise forms . ValidationError ( error_msg )
check if this object is unique
58,161
def get_info ( pyfile ) : info = { } info_re = re . compile ( r"^__(\w+)__ = ['\"](.*)['\"]" ) with open ( pyfile , 'r' ) as f : for line in f . readlines ( ) : match = info_re . search ( line ) if match : info [ match . group ( 1 ) ] = match . group ( 2 ) return info
Retrieve dunder values from a pyfile
58,162
def main ( ) : args = parse_args ( ) config_logger ( args ) logger = structlog . get_logger ( __name__ ) if args . show_version : print_version ( ) sys . exit ( 0 ) version = pkg_resources . get_distribution ( 'lander' ) . version logger . info ( 'Lander version {0}' . format ( version ) ) config = Configuration ( args...
Entrypoint for lander executable .
58,163
def insert_node ( self , node ) : if self . _is_node_reserved ( node ) : return False self . _node_map [ node . get_id ( ) ] = node return True
Adds node if name is available or pre - existing node returns True if added returns False if not added
58,164
def join ( self , distbase , location ) : sep = '' if distbase and distbase [ - 1 ] not in ( ':' , '/' ) : sep = '/' return distbase + sep + location
Join distbase and location in such way that the result is a valid scp destination .
58,165
def get_location ( self , location , depth = 0 ) : if not location : return [ ] if location in self . aliases : res = [ ] if depth > MAXALIASDEPTH : err_exit ( 'Maximum alias depth exceeded: %(location)s' % locals ( ) ) for loc in self . aliases [ location ] : res . extend ( self . get_location ( loc , depth + 1 ) ) re...
Resolve aliases and apply distbase .
58,166
def get_default_location ( self ) : res = [ ] for location in self . distdefault : res . extend ( self . get_location ( location ) ) return res
Return the default location .
58,167
def check_empty_locations ( self , locations = None ) : if locations is None : locations = self . locations if not locations : err_exit ( 'mkrelease: option -d is required\n%s' % USAGE )
Fail if locations is empty .
58,168
def check_valid_locations ( self , locations = None ) : if locations is None : locations = self . locations for location in locations : if ( not self . is_server ( location ) and not self . is_ssh_url ( location ) and not self . has_host ( location ) ) : err_exit ( 'Unknown location: %(location)s' % locals ( ) )
Fail if locations contains bad destinations .
58,169
def list_locations ( self ) : known = self . defaults . get_known_locations ( ) for default in self . defaults . distdefault : if default not in known : known . add ( default ) if not known : err_exit ( 'No locations' , 0 ) for location in sorted ( known ) : if location in self . defaults . distdefault : print ( locati...
Print known dist - locations and exit .
58,170
def get_uploadflags ( self , location ) : uploadflags = [ ] server = self . defaults . servers [ location ] if self . sign : uploadflags . append ( '--sign' ) elif server . sign is not None : if server . sign : uploadflags . append ( '--sign' ) elif self . defaults . sign : uploadflags . append ( '--sign' ) if self . i...
Return uploadflags for the given server .
58,171
def get_options ( self ) : args = self . parse_options ( self . args ) if args : self . directory = args [ 0 ] if self . develop : self . skiptag = True if not self . develop : self . develop = self . defaults . develop if not self . develop : self . infoflags = self . setuptools . infoflags if not self . formats : sel...
Process the command line .
58,172
def get_package ( self ) : directory = self . directory develop = self . develop scmtype = self . scmtype self . scm = self . scms . get_scm ( scmtype , directory ) if self . scm . is_valid_url ( directory ) : directory = self . urlparser . abspath ( directory ) self . remoteurl = directory self . isremote = self . pus...
Get the URL or sandbox to release .
58,173
def make_release ( self ) : directory = self . directory infoflags = self . infoflags branch = self . branch develop = self . develop scmtype = self . scm . name tempdir = abspath ( tempfile . mkdtemp ( prefix = 'mkrelease-' ) ) try : if self . isremote : directory = join ( tempdir , 'build' ) self . scm . clone_url ( ...
Build and distribute the package .
58,174
def configure_gateway ( cls , launch_jvm : bool = True , gateway : Union [ GatewayParameters , Dict [ str , Any ] ] = None , callback_server : Union [ CallbackServerParameters , Dict [ str , Any ] ] = False , javaopts : Iterable [ str ] = ( ) , classpath : Iterable [ str ] = '' ) : assert check_argument_types ( ) class...
Configure a Py4J gateway .
58,175
def load ( self , filename , offset ) : self . offset = offset self . filename = filename self . bootsector = BootSector ( filename = filename , length = NTFS_BOOTSECTOR_SIZE , offset = self . offset ) self . mft_table = MftTable ( mft_entry_size = self . bootsector . mft_record_size , filename = self . filename , offs...
Loads NTFS volume information
58,176
def _get_mft_zone_size ( self , num_clusters , mft_zone_multiplier = 1 ) : sizes = { 4 : num_clusters >> 1 , 3 : ( num_clusters * 3 ) >> 3 , 2 : num_clusters >> 2 , } return sizes . get ( mft_zone_multiplier , num_clusters >> 3 )
Returns mft zone size in clusters . From ntfs_progs . 1 . 22 .
58,177
def close ( self ) : if hasattr ( self , 'iterators' ) : for it in self . iterators : if hasattr ( it , 'close' ) : it . close ( )
Closes all the iterators .
58,178
def _update_sorting ( self ) : key = self . key sorted_tops = self . sorted_tops tops = self . tops iterators = self . iterators for idx in self . idxs : try : tops [ idx ] = next ( iterators [ idx ] ) top_key = key ( tops [ idx ] ) if top_key not in sorted_tops : sorted_tops [ top_key ] = [ ] sorted_tops [ top_key ] ....
Insert new entries into the merged iterator .
58,179
def domain_user_stats ( ) : fname = os . path . join ( os . path . dirname ( __file__ ) , "email_domain_users.csv" ) stats = pd . read_csv ( fname , header = 0 , squeeze = True , index_col = 0 ) return stats [ pd . notnull ( stats . index ) ]
Get number of distinct email addresses in observed domains
58,180
def is_university ( addr ) : addr_domain = domain ( addr ) if not addr_domain : return False chunks = addr_domain . split ( "." ) if len ( chunks ) < 2 : return False domains = university_domains ( ) return ( chunks [ - 1 ] == "edu" and chunks [ - 2 ] not in ( "england" , "australia" ) ) or chunks [ - 2 ] == "edu" or a...
Check if provided email has a university domain
58,181
def is_public ( addr ) : addr_domain = domain ( addr ) if not addr_domain : return True chunks = addr_domain . rsplit ( "." , 1 ) return len ( chunks ) < 2 or addr_domain . endswith ( "local" ) or addr_domain in public_domains ( )
Check if the passed email registered at a free pubic mail server
58,182
def write_color ( self , text , attr = None ) : log ( u'write_color("%s", %s)' % ( text , attr ) ) chunks = self . terminal_escape . split ( text ) log ( u'chunks=%s' % repr ( chunks ) ) bg = self . savebg n = 0 if attr is None : attr = self . attr try : fg = self . trtable [ ( 0x000f & attr ) ] bg = self . trtable [ (...
write text at current cursor position and interpret color escapes . return the number of characters written .
58,183
def files ( self ) : if self . _files is None : self . _files = SeriesZipTifHolo . _index_files ( self . path ) return self . _files
List of hologram data file names in the input zip file
58,184
def get_time ( self , idx ) : ds = self . _get_dataset ( idx ) thetime = ds . get_time ( ) if np . isnan ( thetime ) : zf = zipfile . ZipFile ( self . path ) info = zf . getinfo ( self . files [ idx ] ) timetuple = tuple ( list ( info . date_time ) + [ 0 , 0 , 0 ] ) thetime = time . mktime ( timetuple ) return thetime
Time for each TIFF file
58,185
def get_remote_data ( self , localvars , remotevars , inds , shape ) : if self . horiz_size == 'all' : y , y_1 = 0 , shape [ - 2 ] x , x_1 = 0 , shape [ - 1 ] else : r = self . horiz_size x , x_1 = self . point_get . value [ 2 ] - r , self . point_get . value [ 2 ] + r + 1 y , y_1 = self . point_get . value [ 1 ] - r ,...
Method that does the updating of local netcdf cache with remote data
58,186
def need_data ( self , i ) : if self . caching is False : return False logger . debug ( "Checking cache for data availability at %s." % self . part . location . logstring ( ) ) try : with self . read_lock : self . read_count . value += 1 self . has_read_lock . append ( os . getpid ( ) ) self . dataset . opennc ( ) cach...
Method to test if cache contains the data that the particle needs
58,187
def linterp ( self , setx , sety , x ) : if math . isnan ( sety [ 0 ] ) or math . isnan ( setx [ 0 ] ) : return np . nan return sety [ 0 ] + ( x - setx [ 0 ] ) * ( ( sety [ 1 ] - sety [ 0 ] ) / ( setx [ 1 ] - setx [ 0 ] ) )
Linear interp of model data values between time steps
58,188
def boundary_interaction ( self , ** kwargs ) : particle = kwargs . pop ( 'particle' ) starting = kwargs . pop ( 'starting' ) ending = kwargs . pop ( 'ending' ) if self . useshore : intersection_point = self . _shoreline . intersect ( start_point = starting . point , end_point = ending . point ) if intersection_point :...
Returns a list of Location4D objects
58,189
def get_buildfile_path ( settings ) : base = os . path . basename ( settings . build_url ) return os . path . join ( BUILDS_ROOT , base )
Path to which a build tarball should be downloaded .
58,190
def prior_dates ( * args , ** kwargs ) : try : chron = args [ 0 ] except IndexError : chron = kwargs [ 'coredates' ] d_r = np . array ( kwargs [ 'd_r' ] ) d_std = np . array ( kwargs [ 'd_std' ] ) t_a = np . array ( kwargs [ 't_a' ] ) t_b = np . array ( kwargs [ 't_b' ] ) try : normal_distr = kwargs [ 'normal_distr' ] ...
Get the prior distribution of calibrated radiocarbon dates
58,191
def prior_sediment_rate ( * args , ** kwargs ) : acc_mean = kwargs [ 'acc_mean' ] acc_shape = kwargs [ 'acc_shape' ] x = np . linspace ( 0 , 6 * np . max ( acc_mean ) , 100 ) y = stats . gamma . pdf ( x , a = acc_shape , scale = 1 / ( acc_shape / acc_mean ) ) return y , x
Get the prior density of sediment rates
58,192
def prior_sediment_memory ( * args , ** kwargs ) : mem_shape = kwargs [ 'mem_strength' ] mem_mean = kwargs [ 'mem_mean' ] x = np . linspace ( 0 , 1 , 100 ) y = stats . beta . pdf ( x , a = mem_shape * mem_mean , b = mem_shape * ( 1 - mem_mean ) ) return y , x
Get the prior density of sediment memory
58,193
def _init_browser ( self ) : self . browser = splinter . Browser ( 'phantomjs' ) self . browser . visit ( self . server_url ) self . browser . find_link_by_partial_text ( "Sign in" ) . click ( ) self . browser . fill ( 'ctl00$ctl00$NICEMasterPageBodyContent$SiteContentPlaceholder$' 'txtFormsLogin' , self . user ) self ...
Update this everytime the CERN SSO login form is refactored .
58,194
def download ( self , directory = '~/Music' , song_name = '%a - %s - %A' ) : formatted = self . format ( song_name ) path = os . path . expanduser ( directory ) + os . path . sep + formatted + '.mp3' try : raw = self . safe_download ( ) with open ( path , 'wb' ) as f : f . write ( raw ) except : raise return formatted
Download a song to a directory .
58,195
def safe_download ( self ) : def _markStreamKeyOver30Seconds ( stream ) : self . _connection . request ( 'markStreamKeyOver30Seconds' , { 'streamServerID' : stream . ip , 'artistID' : self . artist . id , 'songQueueID' : self . _connection . session . queue , 'songID' : self . id , 'songQueueSongID' : 1 , 'streamKey' :...
Download a song respecting Grooveshark s API .
58,196
def copy ( self ) : return self . __class__ ( options = self . __options , attribute_options = self . __attribute_options )
Return a copy of this configuration .
58,197
def get_option ( self , name ) : self . __validate_option_name ( name ) return self . __options . get ( name , None )
Returns the value for the specified generic configuration option .
58,198
def set_option ( self , name , value ) : self . __validate_option_name ( name ) self . __options [ name ] = value
Sets the specified generic configuration option to the given value .
58,199
def set_attribute_option ( self , attribute , option_name , option_value ) : self . __validate_attribute_option_name ( option_name ) attribute_key = self . __make_key ( attribute ) mp_options = self . __attribute_options . setdefault ( attribute_key , { } ) mp_options [ option_name ] = option_value
Sets the given attribute option to the given value for the specified attribute .