idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
235,600
def read ( filename , data_wrapper = DataWrapper ) : data = np . loadtxt ( filename ) if len ( np . shape ( data ) ) == 1 : data = np . reshape ( data , ( 1 , - 1 ) ) data = data [ : , [ X , Y , Z , R , TYPE , ID , P ] ] return data_wrapper ( data , 'SWC' , None )
Read an SWC file and return a tuple of data format .
235,601
def _merge_sections ( sec_a , sec_b ) : sec_b . ids = list ( sec_a . ids ) + list ( sec_b . ids [ 1 : ] ) sec_b . ntype = sec_a . ntype sec_b . pid = sec_a . pid sec_a . ids = [ ] sec_a . pid = - 1 sec_a . ntype = 0
Merge two sections
235,602
def _section_end_points ( structure_block , id_map ) : soma_idx = structure_block [ : , TYPE ] == POINT_TYPE . SOMA soma_ids = structure_block [ soma_idx , ID ] neurite_idx = structure_block [ : , TYPE ] != POINT_TYPE . SOMA neurite_rows = structure_block [ neurite_idx , : ] soma_end_pts = set ( id_map [ id_ ] for id_ ...
Get the section end - points
235,603
def _extract_sections ( data_block ) : structure_block = data_block [ : , COLS . TYPE : COLS . COL_COUNT ] . astype ( np . int ) id_map = { - 1 : - 1 } for i , row in enumerate ( structure_block ) : id_map [ row [ ID ] ] = i sec_end_pts = _section_end_points ( structure_block , id_map ) gap_sections = set ( ) sections ...
Make a list of sections from an SWC - style data wrapper block
235,604
def neurite_root_section_ids ( self ) : sec = self . sections return [ i for i , ss in enumerate ( sec ) if ss . pid > - 1 and ( sec [ ss . pid ] . ntype == POINT_TYPE . SOMA and ss . ntype != POINT_TYPE . SOMA ) ]
Get the section IDs of the intitial neurite sections
235,605
def soma_points ( self ) : db = self . data_block return db [ db [ : , COLS . TYPE ] == POINT_TYPE . SOMA ]
Get the soma points
235,606
def add_section ( self , id_ , parent_id , section_type , points ) : assert id_ not in self . sections , 'id %s already exists in sections' % id_ self . sections [ id_ ] = BlockNeuronBuilder . BlockSection ( parent_id , section_type , points )
add a section
235,607
def _make_datablock ( self ) : section_ids = sorted ( self . sections ) id_to_insert_id = { } row_count = 0 for section_id in section_ids : row_count += len ( self . sections [ section_id ] . points ) id_to_insert_id [ section_id ] = row_count - 1 datablock = np . empty ( ( row_count , COLS . COL_COUNT ) , dtype = np ....
Make a data_block and sections list as required by DataWrapper
235,608
def _check_consistency ( self ) : type_count = defaultdict ( int ) for _ , section in sorted ( self . sections . items ( ) ) : type_count [ section . section_type ] += 1 if type_count [ POINT_TYPE . SOMA ] != 1 : L . info ( 'Have %d somas, expected 1' , type_count [ POINT_TYPE . SOMA ] )
see if the sections have obvious errors
235,609
def get_datawrapper ( self , file_format = 'BlockNeuronBuilder' , data_wrapper = DataWrapper ) : self . _check_consistency ( ) datablock , sections = self . _make_datablock ( ) return data_wrapper ( datablock , file_format , sections )
returns a DataWrapper
235,610
def _is_morphology_file ( filepath ) : return ( os . path . isfile ( filepath ) and os . path . splitext ( filepath ) [ 1 ] . lower ( ) in ( '.swc' , '.h5' , '.asc' ) )
Check if filepath is a file with one of morphology file extensions .
235,611
def get_morph_files ( directory ) : lsdir = ( os . path . join ( directory , m ) for m in os . listdir ( directory ) ) return list ( filter ( _is_morphology_file , lsdir ) )
Get a list of all morphology files in a directory
235,612
def get_files_by_path ( path ) : if os . path . isfile ( path ) : return [ path ] if os . path . isdir ( path ) : return get_morph_files ( path ) raise IOError ( 'Invalid data path %s' % path )
Get a file or set of files from a file path
235,613
def load_neuron ( handle , reader = None ) : rdw = load_data ( handle , reader ) if isinstance ( handle , StringType ) : name = os . path . splitext ( os . path . basename ( handle ) ) [ 0 ] else : name = None return FstNeuron ( rdw , name )
Build section trees from an h5 or swc file
235,614
def load_neurons ( neurons , neuron_loader = load_neuron , name = None , population_class = Population , ignored_exceptions = ( ) ) : if isinstance ( neurons , ( list , tuple ) ) : files = neurons name = name if name is not None else 'Population' elif isinstance ( neurons , StringType ) : files = get_files_by_path ( ne...
Create a population object from all morphologies in a directory \ of from morphologies in a list of file names
235,615
def _get_file ( handle ) : if not isinstance ( handle , IOBase ) : return handle fd , temp_file = tempfile . mkstemp ( str ( uuid . uuid4 ( ) ) , prefix = 'neurom-' ) os . close ( fd ) with open ( temp_file , 'w' ) as fd : handle . seek ( 0 ) shutil . copyfileobj ( handle , fd ) return temp_file
Returns the filename of the file to read
235,616
def load_data ( handle , reader = None ) : if not reader : reader = os . path . splitext ( handle ) [ 1 ] [ 1 : ] . lower ( ) if reader not in _READERS : raise NeuroMError ( 'Do not have a loader for "%s" extension' % reader ) filename = _get_file ( handle ) try : return _READERS [ reader ] ( filename ) except Exceptio...
Unpack data into a raw data wrapper
235,617
def _load_h5 ( filename ) : from neurom . io import hdf5 return hdf5 . read ( filename , remove_duplicates = False , data_wrapper = DataWrapper )
Delay loading of h5py until it is needed
235,618
def _filepath ( self , name ) : if self . file_ext is None : candidates = glob . glob ( os . path . join ( self . directory , name + ".*" ) ) try : return next ( filter ( _is_morphology_file , candidates ) ) except StopIteration : raise NeuroMError ( "Can not find morphology file for '%s' " % name ) else : return os . ...
File path to name morphology file .
235,619
def draw ( obj , mode = '2d' , ** kwargs ) : if mode not in MODES : raise InvalidDrawModeError ( 'Invalid drawing mode %s' % mode ) if mode in ( '2d' , 'dendrogram' ) : fig , ax = common . get_figure ( ) else : fig , ax = common . get_figure ( params = { 'projection' : '3d' } ) if isinstance ( obj , Neuron ) : tag = 'n...
Draw a morphology object
235,620
def population_feature_values ( pops , feature ) : pops_feature_values = [ ] for pop in pops : feature_values = [ getattr ( neu , 'get_' + feature ) ( ) for neu in pop . neurons ] if any ( [ isinstance ( p , ( list , np . ndarray ) ) for p in feature_values ] ) : feature_values = list ( chain ( * feature_values ) ) pop...
Extracts feature values per population
235,621
def get_segment ( neuron , section_id , segment_id ) : sec = neuron . sections [ section_id ] return sec . points [ segment_id : segment_id + 2 ] [ : , COLS . XYZR ]
Get a segment given a section and segment id
235,622
def extract_data ( data_path , feature ) : population = nm . load_neurons ( data_path ) feature_data = [ nm . get ( feature , n ) for n in population ] feature_data = list ( chain ( * feature_data ) ) return stats . optimal_distribution ( feature_data )
Loads a list of neurons extracts feature and transforms the fitted distribution in the correct format . Returns the optimal distribution corresponding parameters minimun and maximum values .
235,623
def bifurcation_partition ( bif_point ) : assert len ( bif_point . children ) == 2 , 'A bifurcation point must have exactly 2 children' n = float ( sum ( 1 for _ in bif_point . children [ 0 ] . ipreorder ( ) ) ) m = float ( sum ( 1 for _ in bif_point . children [ 1 ] . ipreorder ( ) ) ) return max ( n , m ) / min ( n ,...
Calculate the partition at a bifurcation point
235,624
def partition_pair ( bif_point ) : n = float ( sum ( 1 for _ in bif_point . children [ 0 ] . ipreorder ( ) ) ) m = float ( sum ( 1 for _ in bif_point . children [ 1 ] . ipreorder ( ) ) ) return ( n , m )
Calculate the partition pairs at a bifurcation point
235,625
def _match_section ( section , match ) : for i in range ( 5 ) : if i >= len ( section ) : return None if isinstance ( section [ i ] , StringType ) and section [ i ] in match : return match [ section [ i ] ] return None
checks whether the type of section is in the match dictionary
235,626
def _parse_section ( token_iter ) : sexp = [ ] for token in token_iter : if token == '(' : new_sexp = _parse_section ( token_iter ) if not _match_section ( new_sexp , UNWANTED_SECTIONS ) : sexp . append ( new_sexp ) elif token == ')' : return sexp else : sexp . append ( token ) return sexp
take a stream of tokens and create the tree structure that is defined by the s - expressions
235,627
def _parse_sections ( morph_fd ) : sections = [ ] token_iter = _get_tokens ( morph_fd ) for token in token_iter : if token == '(' : section = _parse_section ( token_iter ) if not _match_section ( section , UNWANTED_SECTIONS ) : sections . append ( section ) return sections
returns array of all the sections that exist
235,628
def _flatten_subsection ( subsection , _type , offset , parent ) : for row in subsection : if row in ( 'Low' , 'Generated' , 'High' , ) : continue elif isinstance ( row [ 0 ] , StringType ) : if len ( row ) in ( 4 , 5 , ) : if len ( row ) == 5 : assert row [ 4 ] [ 0 ] == 'S' , 'Only known usage of a fifth member is Sn,...
Flatten a subsection from its nested version
235,629
def _extract_section ( section ) : if len ( section ) == 1 : assert section [ 0 ] == 'Sections' , ( 'Only known usage of a single Section content is "Sections", found %s' % section [ 0 ] ) return None _type = WANTED_SECTIONS . get ( section [ 0 ] [ 0 ] , None ) start = 1 if _type is None : _type = WANTED_SECTIONS . get...
Find top level sections and get their flat contents and append them all
235,630
def _sections_to_raw_data ( sections ) : soma = None neurites = [ ] for section in sections : neurite = _extract_section ( section ) if neurite is None : continue elif neurite [ 0 ] [ COLS . TYPE ] == POINT_TYPE . SOMA : assert soma is None , 'Multiple somas defined in file' soma = neurite else : neurites . append ( ne...
convert list of sections into the raw_data format used in neurom
235,631
def read ( morph_file , data_wrapper = DataWrapper ) : msg = ( 'This is an experimental reader. ' 'There are no guarantees regarding ability to parse ' 'Neurolucida .asc files or correctness of output.' ) warnings . warn ( msg ) L . warning ( msg ) with open ( morph_file , encoding = 'utf-8' , errors = 'replace' ) as m...
return a raw_data np . array with the full neuron and the format of the file suitable to be wrapped by DataWrapper
235,632
def stats ( data ) : return { 'len' : len ( data ) , 'mean' : np . mean ( data ) , 'sum' : np . sum ( data ) , 'std' : np . std ( data ) , 'min' : np . min ( data ) , 'max' : np . max ( data ) }
Dictionary with summary stats for data
235,633
def get_config ( config , default_config ) : if not config : logging . warning ( 'Using default config: %s' , default_config ) config = default_config try : with open ( config , 'r' ) as config_file : return yaml . load ( config_file ) except ( yaml . reader . ReaderError , yaml . parser . ParserError , yaml . scanner ...
Load configuration from file if in config else use default
235,634
def soma_surface_area ( nrn , neurite_type = NeuriteType . soma ) : assert neurite_type == NeuriteType . soma , 'Neurite type must be soma' return 4 * math . pi * nrn . soma . radius ** 2
Get the surface area of a neuron s soma .
235,635
def soma_surface_areas ( nrn_pop , neurite_type = NeuriteType . soma ) : nrns = neuron_population ( nrn_pop ) assert neurite_type == NeuriteType . soma , 'Neurite type must be soma' return [ soma_surface_area ( n ) for n in nrns ]
Get the surface areas of the somata in a population of neurons
235,636
def soma_radii ( nrn_pop , neurite_type = NeuriteType . soma ) : assert neurite_type == NeuriteType . soma , 'Neurite type must be soma' nrns = neuron_population ( nrn_pop ) return [ n . soma . radius for n in nrns ]
Get the radii of the somata of a population of neurons
235,637
def trunk_section_lengths ( nrn , neurite_type = NeuriteType . all ) : neurite_filter = is_type ( neurite_type ) return [ morphmath . section_length ( s . root_node . points ) for s in nrn . neurites if neurite_filter ( s ) ]
list of lengths of trunk sections of neurites in a neuron
235,638
def trunk_origin_radii ( nrn , neurite_type = NeuriteType . all ) : neurite_filter = is_type ( neurite_type ) return [ s . root_node . points [ 0 ] [ COLS . R ] for s in nrn . neurites if neurite_filter ( s ) ]
radii of the trunk sections of neurites in a neuron
235,639
def trunk_origin_azimuths ( nrn , neurite_type = NeuriteType . all ) : neurite_filter = is_type ( neurite_type ) nrns = neuron_population ( nrn ) def _azimuth ( section , soma ) : vector = morphmath . vector ( section [ 0 ] , soma . center ) return np . arctan2 ( vector [ COLS . Z ] , vector [ COLS . X ] ) return [ _az...
Get a list of all the trunk origin azimuths of a neuron or population
235,640
def trunk_origin_elevations ( nrn , neurite_type = NeuriteType . all ) : neurite_filter = is_type ( neurite_type ) nrns = neuron_population ( nrn ) def _elevation ( section , soma ) : vector = morphmath . vector ( section [ 0 ] , soma . center ) norm_vector = np . linalg . norm ( vector ) if norm_vector >= np . finfo (...
Get a list of all the trunk origin elevations of a neuron or population
235,641
def trunk_vectors ( nrn , neurite_type = NeuriteType . all ) : neurite_filter = is_type ( neurite_type ) nrns = neuron_population ( nrn ) return np . array ( [ morphmath . vector ( s . root_node . points [ 0 ] , n . soma . center ) for n in nrns for s in n . neurites if neurite_filter ( s ) ] )
Calculates the vectors between all the trunks of the neuron and the soma center .
235,642
def trunk_angles ( nrn , neurite_type = NeuriteType . all ) : vectors = trunk_vectors ( nrn , neurite_type = neurite_type ) if not vectors . size : return [ ] def _sort_angle ( p1 , p2 ) : ang1 = np . arctan2 ( * p1 [ : : - 1 ] ) ang2 = np . arctan2 ( * p2 [ : : - 1 ] ) return ( ang1 - ang2 ) order = np . argsort ( np ...
Calculates the angles between all the trunks of the neuron . The angles are defined on the x - y plane and the trees are sorted from the y axis and anticlock - wise .
235,643
def sholl_crossings ( neurites , center , radii ) : def _count_crossings ( neurite , radius ) : r2 = radius ** 2 count = 0 for start , end in iter_segments ( neurite ) : start_dist2 , end_dist2 = ( morphmath . point_dist2 ( center , start ) , morphmath . point_dist2 ( center , end ) ) count += int ( start_dist2 <= r2 <...
calculate crossings of neurites
235,644
def sholl_frequency ( nrn , neurite_type = NeuriteType . all , step_size = 10 ) : nrns = neuron_population ( nrn ) neurite_filter = is_type ( neurite_type ) min_soma_edge = float ( 'Inf' ) max_radii = 0 neurites_list = [ ] for neuron in nrns : neurites_list . extend ( ( ( neurites , neuron . soma . center ) for neurite...
perform Sholl frequency calculations on a population of neurites
235,645
def dist_points ( bin_edges , d ) : bc = bin_centers ( bin_edges ) if d is not None : d = DISTS [ d [ 'type' ] ] ( d , bc ) return d , bc
Return an array of values according to a distribution
235,646
def calc_limits ( data , dist = None , padding = 0.25 ) : dmin = sys . float_info . max if dist is None else dist . get ( 'min' , sys . float_info . max ) dmax = sys . float_info . min if dist is None else dist . get ( 'max' , sys . float_info . min ) _min = min ( min ( data ) , dmin ) _max = max ( max ( data ) , dmax ...
Calculate a suitable range for a histogram
235,647
def load_neurite_features ( filepath ) : stuff = defaultdict ( lambda : defaultdict ( list ) ) nrns = nm . load_neurons ( filepath ) for nrn in nrns : for t in NEURITES_ : for feat in FEATURES : stuff [ feat ] [ str ( t ) . split ( '.' ) [ 1 ] ] . extend ( nm . get ( feat , nrn , neurite_type = t ) ) return stuff
Unpack relevant data into megadict
235,648
def main ( data_dir , mtype_file ) : stuff = load_neurite_features ( data_dir ) sim_params = json . load ( open ( mtype_file ) ) _plots = [ ] for feat , d in stuff . items ( ) : for typ , data in d . items ( ) : dist = sim_params [ 'components' ] [ typ ] . get ( feat , None ) print ( 'Type = %s, Feature = %s, Distribut...
Run the stuff
235,649
def extract_density ( population , plane = 'xy' , bins = 100 , neurite_type = NeuriteType . basal_dendrite ) : segment_midpoints = get_feat ( 'segment_midpoints' , population , neurite_type = neurite_type ) horiz = segment_midpoints [ : , 'xyz' . index ( plane [ 0 ] ) ] vert = segment_midpoints [ : , 'xyz' . index ( pl...
Extracts the 2d histogram of the center coordinates of segments in the selected plane .
235,650
def plot_density ( population , bins = 100 , new_fig = True , subplot = 111 , levels = None , plane = 'xy' , colorlabel = 'Nodes per unit area' , labelfontsize = 16 , color_map = 'Reds' , no_colorbar = False , threshold = 0.01 , neurite_type = NeuriteType . basal_dendrite , ** kwargs ) : fig , ax = common . get_figure ...
Plots the 2d histogram of the center coordinates of segments in the selected plane .
235,651
def plot_neuron_on_density ( population , bins = 100 , new_fig = True , subplot = 111 , levels = None , plane = 'xy' , colorlabel = 'Nodes per unit area' , labelfontsize = 16 , color_map = 'Reds' , no_colorbar = False , threshold = 0.01 , neurite_type = NeuriteType . basal_dendrite , ** kwargs ) : _ , ax = common . get...
Plots the 2d histogram of the center coordinates of segments in the selected plane and superimposes the view of the first neurite of the collection .
235,652
def is_monotonic ( neurite , tol ) : for node in neurite . iter_sections ( ) : sec = node . points for point_id in range ( len ( sec ) - 1 ) : if sec [ point_id + 1 ] [ COLS . R ] > sec [ point_id ] [ COLS . R ] + tol : return False if ( node . parent is not None and sec [ 0 ] [ COLS . R ] > node . parent . points [ - ...
Check if neurite tree is monotonic
235,653
def is_flat ( neurite , tol , method = 'tolerance' ) : ext = principal_direction_extent ( neurite . points [ : , COLS . XYZ ] ) assert method in ( 'tolerance' , 'ratio' ) , "Method must be one of 'tolerance', 'ratio'" if method == 'ratio' : sorted_ext = np . sort ( ext ) return sorted_ext [ 0 ] / sorted_ext [ 1 ] < flo...
Check if neurite is flat using the given method
235,654
def is_back_tracking ( neurite ) : def pair ( segs ) : return zip ( segs , segs [ 1 : ] ) def coords ( node ) : return node [ COLS . XYZ ] def max_radius ( seg ) : return max ( seg [ 0 ] [ COLS . R ] , seg [ 1 ] [ COLS . R ] ) def is_not_zero_seg ( seg ) : return not np . allclose ( coords ( seg [ 0 ] ) , coords ( seg ...
Check if a neurite process backtracks to a previous node . Back - tracking takes place when a daughter of a branching process goes back and either overlaps with a previous point or lies inside the cylindrical volume of the latter .
235,655
def get_flat_neurites ( neuron , tol = 0.1 , method = 'ratio' ) : return [ n for n in neuron . neurites if is_flat ( n , tol , method ) ]
Check if a neuron has neurites that are flat within a tolerance
235,656
def get_nonmonotonic_neurites ( neuron , tol = 1e-6 ) : return [ n for n in neuron . neurites if not is_monotonic ( n , tol ) ]
Get neurites that are not monotonic
235,657
def segment_centre_of_mass ( seg ) : h = mm . segment_length ( seg ) r0 = seg [ 0 ] [ COLS . R ] r1 = seg [ 1 ] [ COLS . R ] num = r0 * r0 + 2 * r0 * r1 + 3 * r1 * r1 denom = 4 * ( r0 * r0 + r0 * r1 + r1 * r1 ) centre_of_mass_z_loc = num / denom return seg [ 0 ] [ COLS . XYZ ] + ( centre_of_mass_z_loc / h ) * ( seg [ 1...
Calculate and return centre of mass of a segment .
235,658
def neurite_centre_of_mass ( neurite ) : centre_of_mass = np . zeros ( 3 ) total_volume = 0 seg_vol = np . array ( map ( mm . segment_volume , nm . iter_segments ( neurite ) ) ) seg_centre_of_mass = np . array ( map ( segment_centre_of_mass , nm . iter_segments ( neurite ) ) ) seg_centre_of_mass = seg_centre_of_mass * ...
Calculate and return centre of mass of a neurite .
235,659
def distance_sqr ( point , seg ) : centre_of_mass = segment_centre_of_mass ( seg ) return sum ( pow ( np . subtract ( point , centre_of_mass ) , 2 ) )
Calculate and return square Euclidian distance from given point to centre of mass of given segment .
235,660
def radius_of_gyration ( neurite ) : centre_mass = neurite_centre_of_mass ( neurite ) sum_sqr_distance = 0 N = 0 dist_sqr = [ distance_sqr ( centre_mass , s ) for s in nm . iter_segments ( neurite ) ] sum_sqr_distance = np . sum ( dist_sqr ) N = len ( dist_sqr ) return np . sqrt ( sum_sqr_distance / N )
Calculate and return radius of gyration of a given neurite .
235,661
def view ( input_file , plane , backend ) : if backend == 'matplotlib' : from neurom . viewer import draw kwargs = { 'mode' : '3d' if plane == '3d' else '2d' , } if plane != '3d' : kwargs [ 'plane' ] = plane draw ( load_neuron ( input_file ) , ** kwargs ) else : from neurom . view . plotly import draw draw ( load_neuro...
A simple neuron viewer
235,662
def generate_annotation ( result , settings ) : if result . status : return "" header = ( "\n\n" "({label} ; MUK_ANNOTATION\n" " (Color {color}) ; MUK_ANNOTATION\n" " (Name \"{name}\") ; MUK_ANNOTATION" ) . format ( ** settings ) points = [ p for _ , _points in result . info for p in _points ] annotations =...
Generate the annotation for a given checker
235,663
def annotate ( results , settings ) : annotations = ( generate_annotation ( result , setting ) for result , setting in zip ( results , settings ) ) return '\n' . join ( annot for annot in annotations if annot )
Concatenate the annotations of all checkers
235,664
def as_point ( row ) : return Point ( row [ COLS . X ] , row [ COLS . Y ] , row [ COLS . Z ] , row [ COLS . R ] , int ( row [ COLS . TYPE ] ) )
Create a Point from a data block row
235,665
def create_superuser ( self , email , password , ** extra_fields ) : extra_fields . setdefault ( 'is_staff' , True ) extra_fields . setdefault ( 'is_superuser' , True ) if extra_fields . get ( 'is_staff' ) is not True : raise ValueError ( 'Superuser must have is_staff=True.' ) if extra_fields . get ( 'is_superuser' ) i...
Save new User with is_staff and is_superuser set to True
235,666
def load_file_contents ( file_path , as_list = True ) : abs_file_path = join ( HERE , file_path ) with open ( abs_file_path , encoding = 'utf-8' ) as file_pointer : if as_list : return file_pointer . read ( ) . splitlines ( ) return file_pointer . read ( )
Load file as string or list
235,667
def clean_password2 ( self ) : password1 = self . cleaned_data . get ( 'password1' ) password2 = self . cleaned_data . get ( 'password2' ) if password1 and password2 and password1 != password2 : self . add_error ( 'password1' , forms . ValidationError ( self . error_messages [ 'password_mismatch' ] , code = 'password_m...
Check wether password 1 and password 2 are equivalent
235,668
def _post_clean ( self ) : super ( ) . _post_clean ( ) password = self . cleaned_data . get ( 'password1' ) if password : try : password_validation . validate_password ( password , self . instance ) except ValidationError as error : self . add_error ( 'password1' , error )
Run password validaton after clean methods
235,669
def clean ( self ) : super ( ) . clean ( ) self . email = self . __class__ . objects . normalize_email ( self . email )
Override default clean method to normalize email .
235,670
def normalize_feature_inputs ( ctx , param , value ) : for feature_like in value or ( '-' , ) : try : with click . open_file ( feature_like ) as src : for feature in iter_features ( iter ( src ) ) : yield feature except IOError : coords = list ( coords_from_query ( feature_like ) ) yield { 'type' : 'Feature' , 'propert...
Click callback that normalizes feature input values .
235,671
def iter_features ( geojsonfile , func = None ) : func = func or ( lambda x : x ) first_line = next ( geojsonfile ) if first_line . startswith ( u'\x1e' ) : text_buffer = first_line . strip ( u'\x1e' ) for line in geojsonfile : if line . startswith ( u'\x1e' ) : if text_buffer : obj = json . loads ( text_buffer ) if 'c...
Extract GeoJSON features from a text file object .
235,672
def iter_query ( query ) : try : itr = click . open_file ( query ) . readlines ( ) except IOError : itr = [ query ] return itr
Accept a filename stream or string . Returns an iterator over lines of the query .
235,673
def normalize_feature_objects ( feature_objs ) : for obj in feature_objs : if hasattr ( obj , "__geo_interface__" ) and 'type' in obj . __geo_interface__ . keys ( ) and obj . __geo_interface__ [ 'type' ] == 'Feature' : yield obj . __geo_interface__ elif isinstance ( obj , dict ) and 'type' in obj and obj [ 'type' ] == ...
Takes an iterable of GeoJSON - like Feature mappings or an iterable of objects with a geo interface and normalizes it to the former .
235,674
async def api ( self , endpoint , params = None , test = False ) : data = { } url = "{}/{}" . format ( self . _api , endpoint ) try : async with async_timeout . timeout ( 8 , loop = self . _loop ) : response = await self . _session . get ( url , auth = self . _auth , headers = HEADERS , params = params ) if response . ...
Comunicate with the API .
235,675
async def runcli ( ) : async with aiohttp . ClientSession ( ) as session : host = input ( "IP: " ) username = input ( "Username: " ) password = input ( "Password: " ) print ( "\n\n\n" ) data = API ( LOOP , session , username , password , host ) await data . test_connection ( ) print ( "Authenticated:" , data . authenti...
Debug of pytraccar .
235,676
def restore ( s , t ) : t = ( c for c in t ) return '' . join ( next ( t ) if not is_blacksquare ( c ) else c for c in s )
s is the source string it can contain . t is the target it s smaller than s by the number of . s in s
235,677
def default ( event , data ) : messages = defaultdict ( lambda : 'Avast:' ) messages [ 'start' ] = 'Thar she blows!' messages [ 'tag' ] = 'Thar she blows!' messages [ 'stop' ] = 'Away into the depths:' messages [ 'destroy' ] = 'Away into the depths:' messages [ 'delete' ] = 'Away into the depths:' status = get_status (...
The default handler prints basic event info .
235,678
def table ( tab ) : global open_tables if tab in open_tables : yield open_tables [ tab ] else : open_tables [ tab ] = iptc . Table ( tab ) open_tables [ tab ] . refresh ( ) open_tables [ tab ] . autocommit = False yield open_tables [ tab ] open_tables [ tab ] . commit ( ) del open_tables [ tab ]
Access IPTables transactionally in a uniform way .
235,679
def format_symbol ( self , symbol , link_resolver ) : if not symbol : return '' if isinstance ( symbol , FieldSymbol ) : return '' out = self . _format_symbol ( symbol ) template = self . get_template ( 'symbol_wrapper.html' ) return template . render ( { 'symbol' : symbol , 'formatted_doc' : out } )
Format a symbols . Symbol
235,680
def add_comment ( self , comment ) : if not comment : return self . __comments [ comment . name ] = comment self . comment_added_signal ( self , comment )
Add a comment to the database .
235,681
def touch ( fname ) : orig_mtime = get_mtime ( fname ) while get_mtime ( fname ) == orig_mtime : pathlib . Path ( fname ) . touch ( )
Mimics the touch command
235,682
def debug ( self , message , domain = None ) : if domain is None : domain = self . extension_name debug ( message , domain )
Shortcut function for utils . loggable . debug
235,683
def info ( self , message , domain = None ) : if domain is None : domain = self . extension_name info ( message , domain )
Shortcut function for utils . loggable . info
235,684
def parse_config ( self , config ) : prefix = self . argument_prefix self . sources = config . get_sources ( prefix ) self . smart_sources = [ self . _get_smart_filename ( s ) for s in self . sources ] self . index = config . get_index ( prefix ) self . source_roots = OrderedSet ( config . get_paths ( '%s_source_roots'...
Override this making sure to chain up first if your extension adds its own custom command line arguments or you want to do any further processing on the automatically added arguments .
235,685
def add_attrs ( self , symbol , ** kwargs ) : for key , val in kwargs . items ( ) : symbol . add_extension_attribute ( self . extension_name , key , val )
Helper for setting symbol extension attributes
235,686
def get_attr ( self , symbol , attrname ) : return symbol . extension_attributes . get ( self . extension_name , { } ) . get ( attrname , None )
Helper for getting symbol extension attributes
235,687
def add_index_argument ( cls , group ) : prefix = cls . argument_prefix group . add_argument ( '--%s-index' % prefix , action = "store" , dest = "%s_index" % prefix , help = ( "Name of the %s root markdown file, can be None" % ( cls . extension_name ) ) )
Subclasses may call this to add an index argument .
235,688
def add_sources_argument ( cls , group , allow_filters = True , prefix = None , add_root_paths = False ) : prefix = prefix or cls . argument_prefix group . add_argument ( "--%s-sources" % prefix , action = "store" , nargs = "+" , dest = "%s_sources" % prefix . replace ( '-' , '_' ) , help = "%s source files to parse" %...
Subclasses may call this to add sources and source_filters arguments .
235,689
def add_path_argument ( cls , group , argname , dest = None , help_ = None ) : prefixed = '%s-%s' % ( cls . argument_prefix , argname ) if dest is None : dest = prefixed . replace ( '-' , '_' ) final_dest = dest [ len ( cls . argument_prefix ) + 1 : ] else : final_dest = dest dest = '%s_%s' % ( cls . argument_prefix , ...
Subclasses may call this to expose a path argument .
235,690
def add_paths_argument ( cls , group , argname , dest = None , help_ = None ) : prefixed = '%s-%s' % ( cls . argument_prefix , argname ) if dest is None : dest = prefixed . replace ( '-' , '_' ) final_dest = dest [ len ( cls . argument_prefix ) + 1 : ] else : final_dest = dest dest = '%s_%s' % ( cls . argument_prefix ,...
Subclasses may call this to expose a paths argument .
235,691
def create_symbol ( self , * args , ** kwargs ) : if not kwargs . get ( 'project_name' ) : kwargs [ 'project_name' ] = self . project . project_name sym = self . app . database . create_symbol ( * args , ** kwargs ) if sym : if type ( sym ) != Symbol : self . _created_symbols [ sym . filename ] . add ( sym . unique_nam...
Extensions that discover and create instances of symbols . Symbol should do this through this method as it will keep an index of these which can be used when generating a naive index .
235,692
def format_page ( self , page , link_resolver , output ) : debug ( 'Formatting page %s' % page . link . ref , 'formatting' ) if output : actual_output = os . path . join ( output , 'html' ) if not os . path . exists ( actual_output ) : os . makedirs ( actual_output ) else : actual_output = None page . format ( self . f...
Called by project . Project . format_page to leave full control to extensions over the formatting of the pages they are responsible of .
235,693
def add_subproject ( self , fname , conf_path ) : config = Config ( conf_file = conf_path ) proj = Project ( self . app , dependency_map = self . dependency_map ) proj . parse_name_from_config ( config ) proj . parse_config ( config ) proj . setup ( ) self . subprojects [ fname ] = proj
Creates and adds a new subproject .
235,694
def _no_duplicates_constructor ( loader , node , deep = False ) : mapping = { } for key_node , value_node in node . value : key = loader . construct_object ( key_node , deep = deep ) value = loader . construct_object ( value_node , deep = deep ) if key in mapping : raise ConstructorError ( "while constructing a mapping...
Check for duplicate keys .
235,695
def resolve_symbols ( self , tree , database , link_resolver ) : self . typed_symbols = self . __get_empty_typed_symbols ( ) all_syms = OrderedSet ( ) for sym_name in self . symbol_names : sym = database . get_symbol ( sym_name ) self . __query_extra_symbols ( sym , all_syms , tree , link_resolver , database ) if tree ...
When this method is called the page s symbol names are queried from database and added to lists of actual symbols sorted by symbol class .
235,696
def walk ( self , parent = None ) : if parent is None : yield self . root parent = self . root for cpage_name in parent . subpages : cpage = self . __all_pages [ cpage_name ] yield cpage for page in self . walk ( parent = cpage ) : yield page
Generator that yields pages in infix order
235,697
def get_extension_classes ( ) : res = [ SyntaxHighlightingExtension , SearchExtension , TagExtension , DevhelpExtension , LicenseExtension , GitUploadExtension , EditOnGitHubExtension ] if sys . version_info [ 1 ] >= 5 : res += [ DBusExtension ] try : from hotdoc . extensions . c . c_extension import CExtension res += ...
Hotdoc s setuptools entry point
235,698
def register_functions ( lib , ignore_errors ) : def register ( item ) : return register_function ( lib , item , ignore_errors ) for f in functionList : register ( f )
Register function prototypes with a libclang library instance .
235,699
def from_offset ( tu , file , offset ) : return conf . lib . clang_getLocationForOffset ( tu , file , offset )
Retrieve a SourceLocation from a given character offset .