idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
48,600
def write_record ( self , warc_record ) : warc_record . write_to ( self . fileobj ) if isinstance ( self . fileobj , gzip2 . GzipFile ) : self . fileobj . close_member ( )
Adds a warc record to this WARC file .
48,601
def tell ( self ) : if isinstance ( self . fileobj , gzip2 . GzipFile ) : return self . fileobj . fileobj . tell ( ) else : return self . fileobj . tell ( )
Returns the file offset . If this is a compressed file then the offset in the compressed file is returned .
48,602
def close_member ( self ) : if self . _new_member : return self . fileobj . write ( self . compress . flush ( ) ) write32u ( self . fileobj , self . crc ) write32u ( self . fileobj , self . size & 0xffffffffL ) self . size = 0 self . compress = zlib . compressobj ( 9 , zlib . DEFLATED , - zlib . MAX_WBITS , zlib . DEF_...
Closes the current member being written .
48,603
def _start_member ( self ) : if self . _new_member : self . _init_write ( self . name ) self . _write_gzip_header ( ) self . _new_member = False
Starts writing a new member if required .
48,604
def close ( self ) : if self . fileobj is None : return if self . mode == WRITE : self . close_member ( ) self . fileobj = None elif self . mode == READ : self . fileobj = None if self . myfileobj : self . myfileobj . close ( ) self . myfileobj = None
Closes the gzip with care to handle multiple members .
48,605
def read_member ( self ) : if self . _member_lock is False : self . _member_lock = True if self . _new_member : try : BaseGzipFile . _read ( self , 1 ) assert self . _new_member is False except EOFError : return None return self
Returns a file - like object to read one member from the gzip file .
48,606
def write_member ( self , data ) : if isinstance ( data , basestring ) : self . write ( data ) else : for text in data : self . write ( text ) self . close_member ( )
Writes the given data as one gzip member . The data can be a string an iterator that gives strings or a file - like object .
48,607
def write_to ( self , f , version = None ) : if not version : version = self . version if version == 1 : header = "%(url)s %(ip_address)s %(date)s %(content_type)s %(length)s" elif version == 2 : header = "%(url)s %(ip_address)s %(date)s %(content_type)s %(result_code)s %(checksum)s %(location)s %(offset)s %(filename)s...
Writes out the arc header to the file like object f .
48,608
def from_string ( cls , string , version ) : header , payload = string . split ( "\n" , 1 ) if payload [ 0 ] == '\n' : payload = payload [ 1 : ] if int ( version ) == 1 : arc_header_re = ARC1_HEADER_RE elif int ( version ) == 2 : arc_header_re = ARC2_HEADER_RE matches = arc_header_re . search ( header ) headers = match...
Constructs an ARC record from a string and returns it .
48,609
def _write_header ( self ) : "Writes out an ARC header" if "org" not in self . file_headers : warnings . warn ( "Using 'unknown' for Archiving organisation name" ) self . file_headers [ 'org' ] = "Unknown" if "date" not in self . file_headers : now = datetime . datetime . utcnow ( ) warnings . warn ( "Using '%s' for Ar...
Writes out an ARC header
48,610
def write ( self , arc_record ) : "Writes out the given arc record to the file" if not self . version : self . version = 2 if not self . header_written : self . header_written = True self . _write_header ( ) arc_record . write_to ( self . fileobj , self . version ) self . fileobj . write ( "\n" )
Writes out the given arc record to the file
48,611
def _read_file_header ( self ) : header = self . fileobj . readline ( ) payload1 = self . fileobj . readline ( ) payload2 = self . fileobj . readline ( ) version , reserved , organisation = payload1 . split ( None , 2 ) self . fileobj . readline ( ) self . header_read = True if self . version and int ( self . version )...
Reads out the file header for the arc file . If version was not provided this will autopopulate it .
48,612
def _read_arc_record ( self ) : "Reads out an arc record, formats it and returns it" header = self . fileobj . readline ( ) while header and header . strip ( ) == "" : header = self . fileobj . readline ( ) if header == "" : return None if int ( self . version ) == 1 : arc_header_re = ARC1_HEADER_RE elif int ( self . v...
Reads out an arc record formats it and returns it
48,613
def from_bank_code ( cls , country_code , bank_code ) : try : return cls ( registry . get ( 'bank_code' ) [ ( country_code , bank_code ) ] [ 'bic' ] ) except KeyError : raise ValueError ( "Invalid bank code {!r} for country {!r}" . format ( bank_code , country_code ) )
Create a new BIC object from country - and bank - code .
48,614
def generate ( cls , country_code , bank_code , account_code ) : spec = _get_iban_spec ( country_code ) bank_code_length = code_length ( spec , 'bank_code' ) branch_code_length = code_length ( spec , 'branch_code' ) bank_and_branch_code_length = bank_code_length + branch_code_length account_code_length = code_length ( ...
Generate an IBAN from it s components .
48,615
def tdms2rtdc ( ) : parser = tdms2rtdc_parser ( ) args = parser . parse_args ( ) path_tdms = pathlib . Path ( args . tdms_path ) . resolve ( ) path_rtdc = pathlib . Path ( args . rtdc_path ) if path_tdms . is_dir ( ) : files_tdms = fmt_tdms . get_tdms_files ( path_tdms ) if path_rtdc . is_file ( ) : raise ValueError ( ...
Convert . tdms datasets to the hdf5 - based . rtdc file format
48,616
def verify_dataset ( ) : parser = verify_dataset_parser ( ) args = parser . parse_args ( ) path_in = pathlib . Path ( args . path ) . resolve ( ) viol , aler , info = load . check_dataset ( path_in ) print_info ( "Checking {}" . format ( path_in ) ) for inf in info : print_info ( inf ) for ale in aler : print_alert ( a...
Perform checks on experimental datasets
48,617
def load_from_file ( cfg_file ) : path = pathlib . Path ( cfg_file ) . resolve ( ) with path . open ( 'r' ) as f : code = f . readlines ( ) cfg = CaseInsensitiveDict ( ) for line in code : line = line . split ( "#" ) [ 0 ] . strip ( ) if len ( line ) != 0 : if line . startswith ( "[" ) and line . endswith ( "]" ) : sec...
Load the configuration from a file
48,618
def keyval_str2typ ( var , val ) : if not ( isinstance ( val , str_types ) ) : return var . strip ( ) , val var = var . strip ( ) . lower ( ) val = val . strip ( ) if len ( var ) != 0 and len ( val ) != 0 : if val . startswith ( "[" ) and val . endswith ( "]" ) : if len ( val . strip ( "[]," ) ) == 0 : values = [ ] els...
Convert a variable from a string to its correct type
48,619
def keyval_typ2str ( var , val ) : varout = var . strip ( ) if isinstance ( val , list ) : data = ", " . join ( [ keyval_typ2str ( var , it ) [ 1 ] for it in val ] ) valout = "[" + data + "]" elif isinstance ( val , float ) : valout = "{:.12f}" . format ( val ) else : valout = "{}" . format ( val ) return varout , valo...
Convert a variable to a string
48,620
def _init_default_values ( self ) : self [ "filtering" ] [ "remove invalid events" ] = False self [ "filtering" ] [ "enable filters" ] = True self [ "filtering" ] [ "limit events" ] = 0 self [ "filtering" ] [ "polygon filters" ] = [ ] self [ "filtering" ] [ "hierarchy parent" ] = "none" for item in dfn . scalar_feature...
Set default initial values
48,621
def save ( self , filename ) : filename = pathlib . Path ( filename ) out = [ ] keys = sorted ( list ( self . keys ( ) ) ) for key in keys : out . append ( "[{}]" . format ( key ) ) section = self [ key ] ikeys = list ( section . keys ( ) ) ikeys . sort ( ) for ikey in ikeys : var , val = keyval_typ2str ( ikey , sectio...
Save the configuration to a file
48,622
def update ( self , newcfg ) : for key in newcfg . keys ( ) : if key not in self . _cfg : self . _cfg [ key ] = CaseInsensitiveDict ( ) for skey in newcfg [ key ] : self . _cfg [ key ] [ skey ] = newcfg [ key ] [ skey ]
Update current config with a dictionary
48,623
def convert ( area_um , deform , emodulus , channel_width_in , channel_width_out , flow_rate_in , flow_rate_out , viscosity_in , viscosity_out , inplace = False ) : copy = not inplace area_um_corr = np . array ( area_um , dtype = float , copy = copy ) deform_corr = np . array ( deform , copy = copy ) emodulus_corr = np...
convert area - deformation - emodulus triplet
48,624
def corrpix_deform_delta ( area_um , px_um = 0.34 ) : pxcorr = ( .34 / px_um ) ** 2 offs = 0.0012 exp1 = 0.020 * np . exp ( - area_um * pxcorr / 7.1 ) exp2 = 0.010 * np . exp ( - area_um * pxcorr / 38.6 ) exp3 = 0.005 * np . exp ( - area_um * pxcorr / 296 ) delta = offs + exp1 + exp2 + exp3 return delta
Deformation correction term for pixelation effects
48,625
def get_emodulus ( area_um , deform , medium = "CellCarrier" , channel_width = 20.0 , flow_rate = 0.16 , px_um = 0.34 , temperature = 23.0 , copy = True ) : deform = np . array ( deform , copy = copy , dtype = float ) area_um = np . array ( area_um , copy = copy , dtype = float ) lut_path = resource_filename ( "dclab.f...
Compute apparent Young s modulus using a look - up table
48,626
def make_exception ( method , e ) : x = e . details ( ) name = x [ : x . find ( ':' ) ] . split ( '.' ) [ - 1 ] if name in globals ( ) : cls = globals ( ) [ name ] else : cls = UnknownRpcException return cls ( method , e . code ( ) , e . details ( ) )
Creates an exception for a given method and RpcError .
48,627
def text_to_int ( text , default_base = "hex" ) : if text . startswith ( "0x" ) : value = int ( text [ 2 : ] , 16 ) elif text . startswith ( "$" ) : value = int ( text [ 1 : ] , 16 ) elif text . startswith ( "#" ) : value = int ( text [ 1 : ] , 10 ) elif text . startswith ( "%" ) : value = int ( text [ 1 : ] , 2 ) else...
Convert text to int raising exeception on invalid input
48,628
def assign_sector_numbers ( self , dirent , sector_list ) : num = len ( sector_list ) order = self . reserve_space ( num ) if len ( order ) != num : raise errors . InvalidFile ( "VTOC reserved space for %d sectors. Sectors needed: %d" % ( len ( order ) , num ) ) file_length = 0 last_sector = None for sector , sector_nu...
Map out the sectors and link the sectors together
48,629
def downsample_rand ( a , samples , remove_invalid = False , ret_idx = False ) : rs = np . random . RandomState ( seed = 47 ) . get_state ( ) np . random . set_state ( rs ) samples = int ( samples ) if remove_invalid : bad = np . isnan ( a ) | np . isinf ( a ) pool = a [ ~ bad ] else : pool = a if samples and ( samples...
Downsampling by randomly removing points
48,630
def downsample_grid ( a , b , samples , ret_idx = False ) : rs = np . random . RandomState ( seed = 47 ) . get_state ( ) samples = int ( samples ) if samples and samples < a . size : keep = np . zeros_like ( a , dtype = bool ) grid_size = 300 xpx = norm ( a , a , b ) * grid_size ypx = norm ( b , b , a ) * grid_size top...
Content - based downsampling for faster visualization
48,631
def valid ( a , b ) : return ~ ( np . isnan ( a ) | np . isinf ( a ) | np . isnan ( b ) | np . isinf ( b ) )
Check whether a and b are not inf or nan
48,632
def parse_config ( h5path ) : with h5py . File ( h5path , mode = "r" ) as fh5 : h5attrs = dict ( fh5 . attrs ) for key in h5attrs : if isinstance ( h5attrs [ key ] , bytes ) : h5attrs [ key ] = h5attrs [ key ] . decode ( "utf-8" ) config = Configuration ( ) for key in h5attrs : section , pname = key . split ( ":" ) if ...
Parse the RT - DC configuration of an hdf5 file
48,633
def hash ( self ) : if self . _hash is None : tohash = [ self . path . name ] tohash . append ( hashfile ( self . path , blocksize = 65536 , count = 20 ) ) self . _hash = hashobj ( tohash ) return self . _hash
Hash value based on file name and content
48,634
def bin_num_doane ( a ) : bad = np . isnan ( a ) | np . isinf ( a ) data = a [ ~ bad ] acc = bin_width_doane ( a ) num = np . int ( np . round ( ( data . max ( ) - data . min ( ) ) / acc ) ) return num
Compute number of bins based on Doane s formula
48,635
def ignore_nan_inf ( kde_method ) : def new_kde_method ( events_x , events_y , xout = None , yout = None , * args , ** kwargs ) : bad_in = get_bad_vals ( events_x , events_y ) if xout is None : density = np . zeros_like ( events_x , dtype = float ) bad_out = bad_in xo = yo = None else : density = np . zeros_like ( xout...
Ignores nans and infs from the input data
48,636
def kde_gauss ( events_x , events_y , xout = None , yout = None ) : valid_combi = ( ( xout is None and yout is None ) or ( xout is not None and yout is not None ) ) if not valid_combi : raise ValueError ( "Both `xout` and `yout` must be (un)set." ) if yout is None and yout is None : xout = events_x yout = events_y try ...
Gaussian Kernel Density Estimation
48,637
def kde_histogram ( events_x , events_y , xout = None , yout = None , bins = None ) : valid_combi = ( ( xout is None and yout is None ) or ( xout is not None and yout is not None ) ) if not valid_combi : raise ValueError ( "Both `xout` and `yout` must be (un)set." ) if yout is None and yout is None : xout = events_x yo...
Histogram - based Kernel Density Estimation
48,638
def kde_none ( events_x , events_y , xout = None , yout = None ) : valid_combi = ( ( xout is None and yout is None ) or ( xout is not None and yout is not None ) ) if not valid_combi : raise ValueError ( "Both `xout` and `yout` must be (un)set." ) if yout is None and yout is None : xout = events_x yout = events_y retur...
No Kernel Density Estimation
48,639
def kde_multivariate ( events_x , events_y , xout = None , yout = None , bw = None ) : valid_combi = ( ( xout is None and yout is None ) or ( xout is not None and yout is not None ) ) if not valid_combi : raise ValueError ( "Both `xout` and `yout` must be (un)set." ) if yout is None and yout is None : xout = events_x y...
Multivariate Kernel Density Estimation
48,640
def _add ( self , isoel , col1 , col2 , method , meta ) : self . _data [ method ] [ col1 ] [ col2 ] [ "isoelastics" ] = isoel self . _data [ method ] [ col1 ] [ col2 ] [ "meta" ] = meta isoel_flip = [ iso [ : , [ 1 , 0 , 2 ] ] for iso in isoel ] self . _data [ method ] [ col2 ] [ col1 ] [ "isoelastics" ] = isoel_flip s...
Convenience method for population self . _data
48,641
def add_px_err ( isoel , col1 , col2 , px_um , inplace = False ) : Isoelastics . check_col12 ( col1 , col2 ) if "deform" in [ col1 , col2 ] : sign = + 1 else : sign = - 1 if col1 == "area_um" : area_ax = 0 deci_ax = 1 else : area_ax = 1 deci_ax = 0 new_isoel = [ ] for iso in isoel : iso = np . array ( iso , copy = not ...
Undo pixelation correction
48,642
def convert ( isoel , col1 , col2 , channel_width_in , channel_width_out , flow_rate_in , flow_rate_out , viscosity_in , viscosity_out , inplace = False ) : Isoelastics . check_col12 ( col1 , col2 ) if col1 == "area_um" : area_ax = 0 defo_ax = 1 else : area_ax = 1 defo_ax = 0 new_isoel = [ ] for iso in isoel : iso = np...
Convert isoelastics in area_um - deform space
48,643
def get_with_rtdcbase ( self , col1 , col2 , method , dataset , viscosity = None , add_px_err = False ) : cfg = dataset . config return self . get ( col1 = col1 , col2 = col2 , method = method , channel_width = cfg [ "setup" ] [ "channel width" ] , flow_rate = cfg [ "setup" ] [ "flow rate" ] , viscosity = viscosity , a...
Convenience method that extracts the metadata from RTDCBase
48,644
def load_data ( self , path ) : path = pathlib . Path ( path ) . resolve ( ) meta = { } with path . open ( ) as fd : while True : line = fd . readline ( ) . strip ( ) if line . startswith ( "# - " ) : line = line . strip ( "#- " ) var , val = line . split ( ":" ) if val . strip ( ) . replace ( "." , "" ) . isdigit ( ) ...
Load isoelastics from a text file
48,645
def get_compensation_matrix ( ct21 , ct31 , ct12 , ct32 , ct13 , ct23 ) : ct11 = 1 ct22 = 1 ct33 = 1 if ct21 < 0 : raise ValueError ( "ct21 matrix element must not be negative!" ) if ct31 < 0 : raise ValueError ( "ct31 matrix element must not be negative!" ) if ct12 < 0 : raise ValueError ( "ct12 matrix element must no...
Compute crosstalk inversion matrix
48,646
def correct_crosstalk ( fl1 , fl2 , fl3 , fl_channel , ct21 = 0 , ct31 = 0 , ct12 = 0 , ct32 = 0 , ct13 = 0 , ct23 = 0 ) : fl_channel = int ( fl_channel ) if fl_channel not in [ 1 , 2 , 3 ] : raise ValueError ( "`fl_channel` must be 1, 2, or 3!" ) minv = get_compensation_matrix ( ct21 = ct21 , ct31 = ct31 , ct12 = ct12...
Perform crosstalk correction
48,647
def get_inert_ratio_cvx ( cont ) : if isinstance ( cont , np . ndarray ) : cont = [ cont ] ret_list = False else : ret_list = True length = len ( cont ) inert_ratio_cvx = np . zeros ( length , dtype = float ) * np . nan for ii in range ( length ) : try : chull = ssp . ConvexHull ( cont [ ii ] ) except ssp . qhull . Qhu...
Compute the inertia ratio of the convex hull of a contour
48,648
def get_inert_ratio_prnc ( cont ) : if isinstance ( cont , np . ndarray ) : cont = [ cont ] ret_list = False else : ret_list = True length = len ( cont ) inert_ratio_prnc = np . zeros ( length , dtype = float ) * np . nan for ii in range ( length ) : moments = cont_moments_cv ( cont [ ii ] ) if moments is not None : or...
Compute principal inertia ratio of a contour
48,649
def get_inert_ratio_raw ( cont ) : if isinstance ( cont , np . ndarray ) : cont = [ cont ] ret_list = False else : ret_list = True length = len ( cont ) inert_ratio_raw = np . zeros ( length , dtype = float ) * np . nan for ii in range ( length ) : moments = cont_moments_cv ( cont [ ii ] ) if moments is not None : iner...
Compute the inertia ratio of a contour
48,650
def get_tilt ( cont ) : if isinstance ( cont , np . ndarray ) : cont = [ cont ] ret_list = False else : ret_list = True length = len ( cont ) tilt = np . zeros ( length , dtype = float ) * np . nan for ii in range ( length ) : moments = cont_moments_cv ( cont [ ii ] ) if moments is not None : oii = 0.5 * np . arctan2 (...
Compute tilt of raw contour relative to channel axis
48,651
def tag ( * tags ) : def dfn ( fn ) : _tags = getattr ( fn , 'tags' , set ( ) ) _tags . update ( tags ) fn . tags = _tags return fn return dfn
Constructs a decorator that tags a function with specified strings (
48,652
def raw ( mime = 'application/octet-stream' ) : def dfn ( fn ) : tags = getattr ( fn , 'tags' , set ( ) ) tags . add ( 'raw' ) fn . tags = tags fn . mime = getattr ( fn , 'mime' , mime ) return fn return dfn
Constructs a decorator that marks the fn as raw response format
48,653
def open ( self , pysession_id ) : self . id = id ( self ) self . funcserver = self . application . funcserver self . pysession_id = pysession_id self . state = self . funcserver . websocks [ self . id ] = { 'id' : self . id , 'sock' : self }
Called when client opens connection . Initialization is done here .
48,654
def on_message ( self , msg ) : msg = json . loads ( msg ) psession = self . funcserver . pysessions . get ( self . pysession_id , None ) if psession is None : interpreter = PyInterpreter ( self . funcserver . define_python_namespace ( ) ) psession = dict ( interpreter = interpreter , socks = set ( [ self . id ] ) ) se...
Called when client sends a message .
48,655
def on_close ( self ) : if self . id in self . funcserver . websocks : self . funcserver . websocks [ self . id ] = None ioloop = tornado . ioloop . IOLoop . instance ( ) ioloop . add_callback ( lambda : self . funcserver . websocks . pop ( self . id , None ) ) psession = self . funcserver . pysessions . get ( self . p...
Called when client closes this connection . Cleanup is done here .
48,656
def _clean_kwargs ( self , kwargs , fn ) : if not self . server . IGNORE_UNEXPECTED_KWARGS : return kwargs expected_kwargs = set ( inspect . getargspec ( fn ) . args ) got_kwargs = set ( kwargs . keys ( ) ) unexpected_kwargs = got_kwargs - expected_kwargs for k in unexpected_kwargs : del kwargs [ k ] return kwargs
Remove unexpected keyword arguments from the set of received keyword arguments .
48,657
def dump_stacks ( self ) : dump = [ ] threads = dict ( [ ( th . ident , th . name ) for th in threading . enumerate ( ) ] ) for thread , frame in sys . _current_frames ( ) . items ( ) : if thread not in threads : continue dump . append ( 'Thread 0x%x (%s)\n' % ( thread , threads [ thread ] ) ) dump . append ( '' . join...
Dumps the stack of all threads . This function is meant for debugging . Useful when a deadlock happens .
48,658
def define_log_pre_format_hooks ( self ) : hooks = super ( Server , self ) . define_log_pre_format_hooks ( ) if self . args . func == self . run and self . args . debug : hooks . append ( self . _send_log_to_ws ) return hooks
adds a hook to send to websocket if the run command was selected
48,659
def run ( self ) : self . log_id = 0 self . websocks = { } self . pysessions = { } if self . DISABLE_REQUESTS_DEBUG_LOGS : disable_requests_debug_logs ( ) self . threadpool = ThreadPool ( self . THREADPOOL_WORKERS ) self . api = None base_handlers = self . prepare_base_handlers ( ) handlers = self . prepare_handlers ( ...
prepares the api and starts the tornado funcserver
48,660
def _get_sql ( filename ) : with open ( os . path . join ( SQL_DIR , filename ) , 'r' ) as f : return f . read ( )
Returns the contents of the sql file from the given filename .
48,661
def verify_id_n_version ( id , version ) : stmt = _get_sql ( 'verify-id-and-version.sql' ) args = dict ( id = id , version = version ) with db_connect ( ) as db_conn : with db_conn . cursor ( ) as cursor : cursor . execute ( stmt , args ) try : valid = cursor . fetchone ( ) [ 0 ] except TypeError : raise NotFound ( joi...
Given an id and version verify the identified content exists .
48,662
def get_id_n_version ( ident_hash ) : try : id , version = split_ident_hash ( ident_hash ) except IdentHashMissingVersion : from pyramid . httpexceptions import HTTPNotFound from cnxarchive . views . helpers import get_latest_version try : version = get_latest_version ( ident_hash ) except HTTPNotFound : raise NotFound...
From the given ident_hash return the id and version .
48,663
def get_type ( ident_hash ) : id , version = get_id_n_version ( ident_hash ) stmt = _get_sql ( 'get-type.sql' ) args = dict ( id = id , version = version ) with db_connect ( ) as db_conn : with db_conn . cursor ( ) as cursor : cursor . execute ( stmt , args ) type = cursor . fetchone ( ) [ 0 ] return type
Return the database type for the given ident_hash As of now this could either be a Module or Collection .
48,664
def get_metadata ( ident_hash ) : id , version = get_id_n_version ( ident_hash ) stmt = _get_sql ( 'get-metadata.sql' ) args = dict ( id = id , version = version ) with db_connect ( ) as db_conn : with db_conn . cursor ( ) as cursor : cursor . execute ( stmt , args ) try : metadata = cursor . fetchone ( ) [ 0 ] except ...
Return the dictionary of metadata from the database . This data is keyed using the cnx - epub data structure .
48,665
def get_content ( ident_hash , context = None ) : id , version = get_id_n_version ( ident_hash ) filename = 'index.cnxml.html' if context is not None : stmt = _get_sql ( 'get-baked-content.sql' ) args = dict ( id = id , version = version , context = context ) else : stmt = _get_sql ( 'get-content.sql' ) args = dict ( i...
Returns the content for the given ident_hash . context is optionally ident - hash used to find the content within the context of a Collection ident_hash .
48,666
def get_file ( hash ) : stmt = _get_sql ( 'get-file.sql' ) args = dict ( hash = hash ) with db_connect ( ) as db_conn : with db_conn . cursor ( ) as cursor : cursor . execute ( stmt , args ) try : file , _ = cursor . fetchone ( ) except TypeError : raise FileNotFound ( hash ) return memoryview ( file [ : ] )
Return the contents of the file as a memoryview .
48,667
def get_registered_files ( ident_hash ) : id , version = get_id_n_version ( ident_hash ) stmt = _get_sql ( 'get-registered-files-info.sql' ) args = dict ( id = id , version = version ) with db_connect ( ) as db_conn : with db_conn . cursor ( ) as cursor : cursor . execute ( stmt , args ) rows = cursor . fetchall ( ) if...
Returns a list SHA1 hashes for registered file entries identified by the given module ident_hash .
48,668
def get_tree ( ident_hash , baked = False ) : id , version = get_id_n_version ( ident_hash ) stmt = _get_sql ( 'get-tree.sql' ) args = dict ( id = id , version = version , baked = baked ) with db_connect ( ) as db_conn : with db_conn . cursor ( ) as cursor : cursor . execute ( stmt , args ) try : tree = cursor . fetcho...
Return a tree structure of the Collection
48,669
def guess_media_type ( filepath ) : o = subprocess . check_output ( [ 'file' , '--mime-type' , '-Lb' , filepath ] ) o = o . strip ( ) return o
Returns the media - type of the file at the given filepath
48,670
def lookup_module_ident ( id , version ) : with db_connect ( ) as db_conn : with db_conn . cursor ( ) as cursor : cursor . execute ( "SELECT module_ident FROM modules " "WHERE uuid = %s " "AND CONCAT_WS('.', major_version, minor_version) = %s" , ( id , version ) ) try : mident = cursor . fetchone ( ) [ 0 ] except ( Ind...
Return the module_ident for the given id & major and minor version as a tuple .
48,671
def insert_file ( file , media_type ) : resource_hash = get_file_sha1 ( file ) with db_connect ( ) as db_conn : with db_conn . cursor ( ) as cursor : cursor . execute ( "SELECT fileid FROM files WHERE sha1 = %s" , ( resource_hash , ) ) try : fileid = cursor . fetchone ( ) [ 0 ] except ( IndexError , TypeError ) : curso...
Upsert the file and media_type into the files table . Returns the fileid and sha1 of the upserted file .
48,672
def upsert_module_file ( module_ident , fileid , filename ) : with db_connect ( ) as db_conn : with db_conn . cursor ( ) as cursor : cursor . execute ( "SELECT true FROM module_files " "WHERE module_ident = %s " "AND filename = %s" , ( module_ident , filename , ) ) try : cursor . fetchone ( ) [ 0 ] except ( IndexError ...
Upsert a file associated with fileid with filename as a module_files entry associated with content at module_ident .
48,673
def get_contour ( mask ) : if isinstance ( mask , np . ndarray ) and len ( mask . shape ) == 2 : mask = [ mask ] ret_list = False else : ret_list = True contours = [ ] for mi in mask : c0 = find_contours ( mi . transpose ( ) , level = .9999 , positive_orientation = "low" , fully_connected = "high" ) [ 0 ] c1 = np . asa...
Compute the image contour from a mask
48,674
def scan ( self , stop_on_first = True , base_ip = 0 ) : tvs = [ ] if base_ip == 0 : sock = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM ) sock . connect ( ( "8.8.8.8" , 80 ) ) ip = sock . getsockname ( ) [ 0 ] sock . close ( ) ip_parts = ip . split ( '.' ) base_ip = ip_parts [ 0 ] + '.' + ip_parts [ 1 ] + ...
Scans the local network for TVs .
48,675
def check_ip ( ip , log = False ) : if log : print ( 'Checking ip: {}...' . format ( ip ) ) request_timeout = 0.1 try : tv_url = 'http://{}:6095/request?action=isalive' . format ( ip ) request = requests . get ( tv_url , timeout = request_timeout ) except requests . exceptions . ConnectTimeout : return False return req...
Attempts a connection to the TV and checks if there really is a TV .
48,676
def get_field_type ( f ) : types = ( t [ 5 : ] for t in dir ( f ) if t [ : 4 ] == 'TYPE' and getattr ( f , t ) == f . type ) return next ( types )
Obtain the type name of a GRPC Message field .
48,677
def get_field_description ( f ) : type_name = get_field_type ( f ) if type_name == 'MESSAGE' and { sf . name for sf in f . message_type . fields } == { 'key' , 'value' } : return 'map<string, string>' elif type_name == 'MESSAGE' : return f . message_type . full_name elif type_name == 'ENUM' : return f . enum_type . ful...
Get the type description of a GRPC Message field .
48,678
def make_static_request ( method , * args , ** kwargs ) : if args and not use_signature : raise NotImplementedError ( "Only keyword arguments allowed in Python2" ) if use_signature : new_kwargs = { kw : unwrap ( value ) for kw , value in kwargs . items ( ) } new_args = tuple ( unwrap ( value ) for value in args ) bound...
Creates a request from a static method function call .
48,679
def make_request ( self , method , * args , ** kwargs ) : if args and not use_signature : raise NotImplementedError ( "Only keyword arguments allowed in Python2" ) new_kwargs = { kw : unwrap ( value ) for kw , value in kwargs . items ( ) } if use_signature : new_args = tuple ( unwrap ( value ) for value in args ) bound...
Creates a request from a method function call .
48,680
def method_wrapper ( m ) : if m . is_simple : def simple_method ( self ) : return apply_transform ( self . __service__ , m . output_transform , grpc_call ( self . __service__ , m , unwrap ( self ) ) ) return simple_method elif m . input_transform is not None : def transform_method ( self , * args , ** kwargs ) : reques...
Generates a method from a GrpcMethod definition .
48,681
def request_name ( self ) : if self . static and not self . uses_request : return 'Empty' if not self . uses_request : return None if isinstance ( self . uses_request , str ) : return self . uses_request return to_camel_case ( self . name ) + "Request"
Generate the name of the request .
48,682
def request_type ( self ) : if self . static and not self . uses_request : return getattr ( xenon_pb2 , 'Empty' ) if not self . uses_request : return None return getattr ( xenon_pb2 , self . request_name )
Retrieve the type of the request by fetching it from xenon . proto . xenon_pb2 .
48,683
def signature ( self ) : if not use_signature : raise NotImplementedError ( "Python 3 only." ) if self . static : parameters = ( Parameter ( name = 'cls' , kind = Parameter . POSITIONAL_ONLY ) , ) else : parameters = ( Parameter ( name = 'self' , kind = Parameter . POSITIONAL_ONLY ) , ) if self . input_transform : retu...
Create a signature for this method only in Python > 3 . 4
48,684
def docstring ( self , servicer ) : s = getattr ( servicer , to_lower_camel_case ( self . name ) ) . __doc__ or "TODO: no docstring in .proto file" if self . uses_request : s += "\n" for field in get_fields ( self . request_type ) : if field != self . field_name : type_info = get_field_description ( self . request_type...
Generate a doc - string .
48,685
def slugify ( string ) : filtered_string = [ ] if isinstance ( string , str ) : string = unicode ( string , 'utf-8' ) for i in unicodedata . normalize ( 'NFKC' , string ) : cat = unicodedata . category ( i ) [ 0 ] if cat in 'LN' or i in '-_' : filtered_string . append ( i ) elif cat in 'Z' : filtered_string . append ( ...
Return a slug for the unicode_string .
48,686
def find_contours ( array , level , fully_connected = 'low' , positive_orientation = 'low' ) : array = np . asarray ( array , dtype = np . double ) if array . ndim != 2 : raise ValueError ( 'Only 2D arrays are supported.' ) level = float ( level ) if ( fully_connected not in _param_options or positive_orientation not i...
Find iso - valued contours in a 2D array for a given level value .
48,687
def get_module_ident_from_ident_hash ( ident_hash , cursor ) : try : uuid , ( mj_ver , mn_ver ) = split_ident_hash ( ident_hash , split_version = True ) except IdentHashMissingVersion as e : uuid , mj_ver , mn_ver = e . id , None , None args = [ uuid ] stmt = "SELECT module_ident FROM {} WHERE uuid = %s" table_name = '...
Return the moduleid for a given ident_hash .
48,688
def get_tree ( ident_hash , cursor , as_collated = False ) : uuid , version = split_ident_hash ( ident_hash ) cursor . execute ( SQL [ 'get-tree-by-uuid-n-version' ] , ( uuid , version , as_collated , ) ) try : tree = cursor . fetchone ( ) [ 0 ] except TypeError : raise ContentNotFound ( ) if type ( tree ) in ( type ( ...
Return a JSON representation of the binder tree for ident_hash .
48,689
def get_collated_content ( ident_hash , context_ident_hash , cursor ) : cursor . execute ( SQL [ 'get-collated-content' ] , ( ident_hash , context_ident_hash , ) ) try : return cursor . fetchone ( ) [ 0 ] except TypeError : return
Return collated content for ident_hash .
48,690
def get_module_uuid ( plpy , moduleid ) : plan = plpy . prepare ( "SELECT uuid FROM modules WHERE moduleid = $1;" , ( 'text' , ) ) result = plpy . execute ( plan , ( moduleid , ) , 1 ) if result : return result [ 0 ] [ 'uuid' ]
Retrieve page uuid from legacy moduleid .
48,691
def set_version ( portal_type , legacy_version , td ) : modified = 'OK' legacy_major , legacy_minor = legacy_version . split ( '.' ) if portal_type == 'Collection' : modified = 'MODIFY' td [ 'new' ] [ 'major_version' ] = int ( legacy_minor ) if td [ 'new' ] [ 'minor_version' ] is None : td [ 'new' ] [ 'minor_version' ]...
Set the major_version and minor_version if they are not set .
48,692
def republish_module ( td , plpy ) : portal_type = td [ 'new' ] [ 'portal_type' ] modified = 'OK' moduleid = td [ 'new' ] [ 'moduleid' ] legacy_version = td [ 'new' ] [ 'version' ] submitter = td [ 'new' ] [ 'submitter' ] submitlog = td [ 'new' ] [ 'submitlog' ] modified = set_version ( portal_type , legacy_version , t...
When a module is republished create new minor versions of collections .
48,693
def republish_module_trigger ( plpy , td ) : is_legacy_publication = td [ 'new' ] [ 'version' ] is not None if not is_legacy_publication : return "OK" plpy . log ( 'Trigger fired on %s' % ( td [ 'new' ] [ 'moduleid' ] , ) ) modified = republish_module ( td , plpy ) plpy . log ( 'modified: {}' . format ( modified ) ) pl...
Trigger called from postgres database when republishing a module .
48,694
def assign_version_default_trigger ( plpy , td ) : modified_state = "OK" portal_type = td [ 'new' ] [ 'portal_type' ] version = td [ 'new' ] [ 'version' ] minor_version = td [ 'new' ] [ 'minor_version' ] if minor_version is None and portal_type in ( 'Collection' , 'SubCollection' ) : modified_state = "MODIFY" td [ 'new...
Trigger to fill in legacy data fields .
48,695
def get_export ( request ) : settings = get_current_registry ( ) . settings exports_dirs = settings [ 'exports-directories' ] . split ( ) args = request . matchdict ident_hash , type = args [ 'ident_hash' ] , args [ 'type' ] id , version = split_ident_hash ( ident_hash ) with db_connect ( ) as db_connection : with db_c...
Retrieve an export file .
48,696
def get_export_files ( cursor , id , version , types , exports_dirs , read_file = True ) : request = get_current_request ( ) type_info = dict ( request . registry . settings [ '_type_info' ] ) metadata = get_content_metadata ( id , version , cursor ) legacy_id = metadata [ 'legacy_id' ] legacy_version = metadata [ 'leg...
Retrieve files associated with document .
48,697
def get_content_metadata ( id , version , cursor ) : args = dict ( id = id , version = version ) cursor . execute ( SQL [ 'get-module-metadata' ] , args ) try : result = cursor . fetchone ( ) [ 0 ] result [ 'version' ] = result . pop ( 'current_version' ) result [ 'mediaType' ] = portaltype_to_mimetype ( result [ 'medi...
Return metadata related to the content from the database .
48,698
def find_contours_level ( density , x , y , level , closed = False ) : if level >= 1 or level <= 0 : raise ValueError ( "`level` must be in (0,1), got '{}'!" . format ( level ) ) level = level * density . max ( ) if len ( x . shape ) == 2 : assert np . all ( x [ : , 0 ] == x [ : , 1 ] ) x = x [ : , 0 ] if len ( y . sha...
Find iso - valued density contours for a given level value
48,699
def get_quantile_levels ( density , x , y , xp , yp , q , normalize = True ) : if len ( x . shape ) == 2 : assert np . all ( x [ : , 0 ] == x [ : , 1 ] ) x = x [ : , 0 ] if len ( y . shape ) == 2 : assert np . all ( y [ 0 , : ] == y [ 1 , : ] ) y = y [ 0 , : ] bad = get_bad_vals ( xp , yp ) xp = xp [ ~ bad ] yp = yp [ ...
Compute density levels for given quantiles by interpolation