idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
23,500
def create_widgets ( self ) : self . bbox = QDialogButtonBox ( QDialogButtonBox . Ok | QDialogButtonBox . Cancel ) self . idx_ok = self . bbox . button ( QDialogButtonBox . Ok ) self . idx_cancel = self . bbox . button ( QDialogButtonBox . Cancel ) self . idx_group = FormMenu ( [ gr [ 'name' ] for gr in self . groups ] ) chan_box = QListWidget ( ) self . idx_chan = chan_box stage_box = QListWidget ( ) stage_box . addItems ( STAGE_NAME ) stage_box . setSelectionMode ( QAbstractItemView . ExtendedSelection ) self . idx_stage = stage_box cycle_box = QListWidget ( ) cycle_box . setSelectionMode ( QAbstractItemView . ExtendedSelection ) self . idx_cycle = cycle_box
Build basic components of dialog .
208
6
23,501
def update_groups ( self ) : self . groups = self . parent . channels . groups self . idx_group . clear ( ) for gr in self . groups : self . idx_group . addItem ( gr [ 'name' ] ) self . update_channels ( )
Update the channel groups list when dialog is opened .
61
10
23,502
def update_channels ( self ) : group_dict = { k [ 'name' ] : i for i , k in enumerate ( self . groups ) } group_index = group_dict [ self . idx_group . currentText ( ) ] self . one_grp = self . groups [ group_index ] self . idx_chan . clear ( ) self . idx_chan . setSelectionMode ( QAbstractItemView . ExtendedSelection ) for chan in self . one_grp [ 'chan_to_plot' ] : name = chan + '—(' + ' '.j o in(s e lf.o n e_grp[' r ef_chan']) + ' ' item = QListWidgetItem ( name ) self . idx_chan . addItem ( item )
Update the channels list when a new group is selected .
179
11
23,503
def update_cycles ( self ) : self . idx_cycle . clear ( ) try : self . cycles = self . parent . notes . annot . get_cycles ( ) except ValueError as err : self . idx_cycle . setEnabled ( False ) msg = 'There is a problem with the cycle markers: ' + str ( err ) self . parent . statusBar ( ) . showMessage ( msg ) else : if self . cycles is None : self . idx_cycle . setEnabled ( False ) else : self . idx_cycle . setEnabled ( True ) for i in range ( len ( self . cycles ) ) : self . idx_cycle . addItem ( str ( i + 1 ) )
Enable cycles checkbox only if there are cycles marked with no errors .
152
14
23,504
def _create_data_to_plot ( data , chan_groups ) : # chan_to_plot only gives the number of channels to plot, for prealloc chan_to_plot = [ one_chan for one_grp in chan_groups for one_chan in one_grp [ 'chan_to_plot' ] ] output = ChanTime ( ) output . s_freq = data . s_freq output . start_time = data . start_time output . axis [ 'time' ] = data . axis [ 'time' ] output . axis [ 'chan' ] = empty ( 1 , dtype = 'O' ) output . data = empty ( 1 , dtype = 'O' ) output . data [ 0 ] = empty ( ( len ( chan_to_plot ) , data . number_of ( 'time' ) [ 0 ] ) , dtype = 'f' ) all_chan_grp_name = [ ] i_ch = 0 for one_grp in chan_groups : sel_data = _select_channels ( data , one_grp [ 'chan_to_plot' ] + one_grp [ 'ref_chan' ] ) data1 = montage ( sel_data , ref_chan = one_grp [ 'ref_chan' ] ) data1 . data [ 0 ] = nan_to_num ( data1 . data [ 0 ] ) if one_grp [ 'hp' ] is not None : data1 = filter_ ( data1 , low_cut = one_grp [ 'hp' ] ) if one_grp [ 'lp' ] is not None : data1 = filter_ ( data1 , high_cut = one_grp [ 'lp' ] ) for chan in one_grp [ 'chan_to_plot' ] : chan_grp_name = chan + ' (' + one_grp [ 'name' ] + ')' all_chan_grp_name . append ( chan_grp_name ) dat = data1 ( chan = chan , trial = 0 ) dat = dat - nanmean ( dat ) output . data [ 0 ] [ i_ch , : ] = dat * one_grp [ 'scale' ] i_ch += 1 output . axis [ 'chan' ] [ 0 ] = asarray ( all_chan_grp_name , dtype = 'U' ) return output
Create data after montage and filtering .
540
8
23,505
def _convert_timestr_to_seconds ( time_str , rec_start ) : if not CHECK_TIME_STR . match ( time_str ) : raise ValueError ( 'Input can only contain digits and colons' ) if ':' in time_str : time_split = [ int ( x ) for x in time_str . split ( ':' ) ] # if it's in 'HH:MM' format, add ':SS' if len ( time_split ) == 2 : time_split . append ( 0 ) clock_time = time ( * time_split ) chosen_start = datetime . combine ( rec_start . date ( ) , clock_time ) # if the clock time is after start of the recordings, assume it's the next day if clock_time < rec_start . time ( ) : chosen_start += timedelta ( days = 1 ) window_start = int ( ( chosen_start - rec_start ) . total_seconds ( ) ) else : window_start = int ( time_str ) return window_start
Convert input from user about time string to an absolute time for the recordings .
230
16
23,506
def read_data ( self ) : window_start = self . parent . value ( 'window_start' ) window_end = window_start + self . parent . value ( 'window_length' ) dataset = self . parent . info . dataset groups = self . parent . channels . groups chan_to_read = [ ] for one_grp in groups : chan_to_read . extend ( one_grp [ 'chan_to_plot' ] + one_grp [ 'ref_chan' ] ) if not chan_to_read : return data = dataset . read_data ( chan = chan_to_read , begtime = window_start , endtime = window_end ) max_s_freq = self . parent . value ( 'max_s_freq' ) if data . s_freq > max_s_freq : q = int ( data . s_freq / max_s_freq ) lg . debug ( 'Decimate (no low-pass filter) at ' + str ( q ) ) data . data [ 0 ] = data . data [ 0 ] [ : , slice ( None , None , q ) ] data . axis [ 'time' ] [ 0 ] = data . axis [ 'time' ] [ 0 ] [ slice ( None , None , q ) ] data . s_freq = int ( data . s_freq / q ) self . data = _create_data_to_plot ( data , self . parent . channels . groups )
Read the data to plot .
333
6
23,507
def display ( self ) : if self . data is None : return if self . scene is not None : self . y_scrollbar_value = self . verticalScrollBar ( ) . value ( ) self . scene . clear ( ) self . create_chan_labels ( ) self . create_time_labels ( ) window_start = self . parent . value ( 'window_start' ) window_length = self . parent . value ( 'window_length' ) time_height = max ( [ x . boundingRect ( ) . height ( ) for x in self . idx_time ] ) label_width = window_length * self . parent . value ( 'label_ratio' ) scene_height = ( len ( self . idx_label ) * self . parent . value ( 'y_distance' ) + time_height ) self . scene = QGraphicsScene ( window_start - label_width , 0 , window_length + label_width , scene_height ) self . setScene ( self . scene ) self . idx_markers = [ ] self . idx_annot = [ ] self . idx_annot_labels = [ ] self . add_chan_labels ( ) self . add_time_labels ( ) self . add_traces ( ) self . display_grid ( ) self . display_markers ( ) self . display_annotations ( ) self . resizeEvent ( None ) self . verticalScrollBar ( ) . setValue ( self . y_scrollbar_value ) self . parent . info . display_view ( ) self . parent . overview . display_current ( )
Display the recordings .
353
4
23,508
def create_chan_labels ( self ) : self . idx_label = [ ] for one_grp in self . parent . channels . groups : for one_label in one_grp [ 'chan_to_plot' ] : item = QGraphicsSimpleTextItem ( one_label ) item . setBrush ( QBrush ( QColor ( one_grp [ 'color' ] ) ) ) item . setFlag ( QGraphicsItem . ItemIgnoresTransformations ) self . idx_label . append ( item )
Create the channel labels but don t plot them yet .
116
11
23,509
def create_time_labels ( self ) : min_time = int ( floor ( min ( self . data . axis [ 'time' ] [ 0 ] ) ) ) max_time = int ( ceil ( max ( self . data . axis [ 'time' ] [ 0 ] ) ) ) n_time_labels = self . parent . value ( 'n_time_labels' ) self . idx_time = [ ] self . time_pos = [ ] for one_time in linspace ( min_time , max_time , n_time_labels ) : x_label = ( self . data . start_time + timedelta ( seconds = one_time ) ) . strftime ( '%H:%M:%S' ) item = QGraphicsSimpleTextItem ( x_label ) item . setFlag ( QGraphicsItem . ItemIgnoresTransformations ) self . idx_time . append ( item ) self . time_pos . append ( QPointF ( one_time , len ( self . idx_label ) * self . parent . value ( 'y_distance' ) ) )
Create the time labels but don t plot them yet .
244
11
23,510
def add_chan_labels ( self ) : window_start = self . parent . value ( 'window_start' ) window_length = self . parent . value ( 'window_length' ) label_width = window_length * self . parent . value ( 'label_ratio' ) for row , one_label_item in enumerate ( self . idx_label ) : self . scene . addItem ( one_label_item ) one_label_item . setPos ( window_start - label_width , self . parent . value ( 'y_distance' ) * row + self . parent . value ( 'y_distance' ) / 2 )
Add channel labels on the left .
144
7
23,511
def add_time_labels ( self ) : for text , pos in zip ( self . idx_time , self . time_pos ) : self . scene . addItem ( text ) text . setPos ( pos )
Add time labels at the bottom .
48
7
23,512
def add_traces ( self ) : y_distance = self . parent . value ( 'y_distance' ) self . chan = [ ] self . chan_pos = [ ] self . chan_scale = [ ] row = 0 for one_grp in self . parent . channels . groups : for one_chan in one_grp [ 'chan_to_plot' ] : # channel name chan_name = one_chan + ' (' + one_grp [ 'name' ] + ')' # trace dat = ( self . data ( trial = 0 , chan = chan_name ) * self . parent . value ( 'y_scale' ) ) dat *= - 1 # flip data, upside down path = self . scene . addPath ( Path ( self . data . axis [ 'time' ] [ 0 ] , dat ) ) path . setPen ( QPen ( QColor ( one_grp [ 'color' ] ) , LINE_WIDTH ) ) # adjust position chan_pos = y_distance * row + y_distance / 2 path . setPos ( 0 , chan_pos ) row += 1 self . chan . append ( chan_name ) self . chan_scale . append ( one_grp [ 'scale' ] ) self . chan_pos . append ( chan_pos )
Add traces based on self . data .
295
8
23,513
def display_grid ( self ) : window_start = self . parent . value ( 'window_start' ) window_length = self . parent . value ( 'window_length' ) window_end = window_start + window_length if self . parent . value ( 'grid_x' ) : x_tick = self . parent . value ( 'grid_xtick' ) x_ticks = arange ( window_start , window_end + x_tick , x_tick ) for x in x_ticks : x_pos = [ x , x ] y_pos = [ 0 , self . parent . value ( 'y_distance' ) * len ( self . idx_label ) ] path = self . scene . addPath ( Path ( x_pos , y_pos ) ) path . setPen ( QPen ( QColor ( LINE_COLOR ) , LINE_WIDTH , Qt . DotLine ) ) if self . parent . value ( 'grid_y' ) : y_tick = ( self . parent . value ( 'grid_ytick' ) * self . parent . value ( 'y_scale' ) ) for one_label_item in self . idx_label : x_pos = [ window_start , window_end ] y = one_label_item . y ( ) y_pos_0 = [ y , y ] path_0 = self . scene . addPath ( Path ( x_pos , y_pos_0 ) ) path_0 . setPen ( QPen ( QColor ( LINE_COLOR ) , LINE_WIDTH , Qt . DotLine ) ) y_up = one_label_item . y ( ) + y_tick y_pos_up = [ y_up , y_up ] path_up = self . scene . addPath ( Path ( x_pos , y_pos_up ) ) path_up . setPen ( QPen ( QColor ( LINE_COLOR ) , LINE_WIDTH , Qt . DotLine ) ) y_down = one_label_item . y ( ) - y_tick y_pos_down = [ y_down , y_down ] path_down = self . scene . addPath ( Path ( x_pos , y_pos_down ) ) path_down . setPen ( QPen ( QColor ( LINE_COLOR ) , LINE_WIDTH , Qt . DotLine ) )
Display grid on x - axis and y - axis .
522
11
23,514
def display_markers ( self ) : for item in self . idx_markers : self . scene . removeItem ( item ) self . idx_markers = [ ] window_start = self . parent . value ( 'window_start' ) window_length = self . parent . value ( 'window_length' ) window_end = window_start + window_length y_distance = self . parent . value ( 'y_distance' ) markers = [ ] if self . parent . info . markers is not None : if self . parent . value ( 'marker_show' ) : markers = self . parent . info . markers for mrk in markers : if window_start <= mrk [ 'end' ] and window_end >= mrk [ 'start' ] : mrk_start = max ( ( mrk [ 'start' ] , window_start ) ) mrk_end = min ( ( mrk [ 'end' ] , window_end ) ) color = QColor ( self . parent . value ( 'marker_color' ) ) item = QGraphicsRectItem ( mrk_start , 0 , mrk_end - mrk_start , len ( self . idx_label ) * y_distance ) item . setPen ( color ) item . setBrush ( color ) item . setZValue ( - 9 ) self . scene . addItem ( item ) item = TextItem_with_BG ( color . darker ( 200 ) ) item . setText ( mrk [ 'name' ] ) item . setPos ( mrk [ 'start' ] , len ( self . idx_label ) * self . parent . value ( 'y_distance' ) ) item . setFlag ( QGraphicsItem . ItemIgnoresTransformations ) item . setRotation ( - 90 ) self . scene . addItem ( item ) self . idx_markers . append ( item )
Add markers on top of first plot .
423
8
23,515
def step_prev ( self ) : window_start = around ( self . parent . value ( 'window_start' ) - self . parent . value ( 'window_length' ) / self . parent . value ( 'window_step' ) , 2 ) if window_start < 0 : return self . parent . overview . update_position ( window_start )
Go to the previous step .
77
6
23,516
def step_next ( self ) : window_start = around ( self . parent . value ( 'window_start' ) + self . parent . value ( 'window_length' ) / self . parent . value ( 'window_step' ) , 2 ) self . parent . overview . update_position ( window_start )
Go to the next step .
69
6
23,517
def page_prev ( self ) : window_start = ( self . parent . value ( 'window_start' ) - self . parent . value ( 'window_length' ) ) if window_start < 0 : return self . parent . overview . update_position ( window_start )
Go to the previous page .
61
6
23,518
def page_next ( self ) : window_start = ( self . parent . value ( 'window_start' ) + self . parent . value ( 'window_length' ) ) self . parent . overview . update_position ( window_start )
Go to the next page .
53
6
23,519
def go_to_epoch ( self , checked = False , test_text_str = None ) : if test_text_str is not None : time_str = test_text_str ok = True else : time_str , ok = QInputDialog . getText ( self , 'Go To Epoch' , 'Enter start time of the ' 'epoch,\nin seconds ("1560") ' 'or\nas absolute time ' '("22:30")' ) if not ok : return try : rec_start_time = self . parent . info . dataset . header [ 'start_time' ] window_start = _convert_timestr_to_seconds ( time_str , rec_start_time ) except ValueError as err : error_dialog = QErrorMessage ( ) error_dialog . setWindowTitle ( 'Error moving to epoch' ) error_dialog . showMessage ( str ( err ) ) if test_text_str is None : error_dialog . exec ( ) self . parent . statusBar ( ) . showMessage ( str ( err ) ) return self . parent . overview . update_position ( window_start )
Go to any window
252
4
23,520
def line_up_with_epoch ( self ) : if self . parent . notes . annot is None : # TODO: remove if buttons are disabled error_dialog = QErrorMessage ( ) error_dialog . setWindowTitle ( 'Error moving to epoch' ) error_dialog . showMessage ( 'No score file loaded' ) error_dialog . exec ( ) return new_window_start = self . parent . notes . annot . get_epoch_start ( self . parent . value ( 'window_start' ) ) self . parent . overview . update_position ( new_window_start )
Go to the start of the present epoch .
133
9
23,521
def add_time ( self , extra_time ) : window_start = self . parent . value ( 'window_start' ) + extra_time self . parent . overview . update_position ( window_start )
Go to the predefined time forward .
46
8
23,522
def X_more ( self ) : if self . parent . value ( 'window_length' ) < 0.3 : return self . parent . value ( 'window_length' , self . parent . value ( 'window_length' ) * 2 ) self . parent . overview . update_position ( )
Zoom in on the x - axis .
65
9
23,523
def X_less ( self ) : self . parent . value ( 'window_length' , self . parent . value ( 'window_length' ) / 2 ) self . parent . overview . update_position ( )
Zoom out on the x - axis .
46
9
23,524
def X_length ( self , new_window_length ) : self . parent . value ( 'window_length' , new_window_length ) self . parent . overview . update_position ( )
Use presets for length of the window .
43
8
23,525
def Y_more ( self ) : self . parent . value ( 'y_scale' , self . parent . value ( 'y_scale' ) * 2 ) self . parent . traces . display ( )
Increase the scaling .
44
4
23,526
def Y_less ( self ) : self . parent . value ( 'y_scale' , self . parent . value ( 'y_scale' ) / 2 ) self . parent . traces . display ( )
Decrease the scaling .
44
5
23,527
def Y_ampl ( self , new_y_scale ) : self . parent . value ( 'y_scale' , new_y_scale ) self . parent . traces . display ( )
Make scaling on Y axis using predefined values
42
9
23,528
def Y_wider ( self ) : self . parent . value ( 'y_distance' , self . parent . value ( 'y_distance' ) * 1.4 ) self . parent . traces . display ( )
Increase the distance of the lines .
47
7
23,529
def Y_tighter ( self ) : self . parent . value ( 'y_distance' , self . parent . value ( 'y_distance' ) / 1.4 ) self . parent . traces . display ( )
Decrease the distance of the lines .
47
8
23,530
def Y_dist ( self , new_y_distance ) : self . parent . value ( 'y_distance' , new_y_distance ) self . parent . traces . display ( )
Use preset values for the distance between lines .
41
9
23,531
def mousePressEvent ( self , event ) : if not self . scene : return if self . event_sel or self . current_event : self . parent . notes . idx_eventtype . setCurrentText ( self . current_etype ) self . current_etype = None self . current_event = None self . deselect = True self . event_sel = None self . current_event_row = None self . scene . removeItem ( self . highlight ) self . highlight = None self . parent . statusBar ( ) . showMessage ( '' ) return self . ready = False self . event_sel = None xy_scene = self . mapToScene ( event . pos ( ) ) chan_idx = argmin ( abs ( asarray ( self . chan_pos ) - xy_scene . y ( ) ) ) self . sel_chan = chan_idx self . sel_xy = ( xy_scene . x ( ) , xy_scene . y ( ) ) chk_marker = self . parent . notes . action [ 'new_bookmark' ] . isChecked ( ) chk_event = self . parent . notes . action [ 'new_event' ] . isChecked ( ) if not ( chk_marker or chk_event ) : channame = self . chan [ self . sel_chan ] + ' in selected window' self . parent . spectrum . show_channame ( channame ) # Make annotations clickable else : for annot in self . idx_annot : if annot . contains ( xy_scene ) : self . highlight_event ( annot ) if chk_event : row = self . parent . notes . find_row ( annot . marker . x ( ) , annot . marker . x ( ) + annot . marker . width ( ) ) self . parent . notes . idx_annot_list . setCurrentCell ( row , 0 ) break self . ready = True
Create a marker or start selection
430
6
23,532
def mouseReleaseEvent ( self , event ) : if not self . scene : return if self . event_sel : return if self . deselect : self . deselect = False return if not self . ready : return chk_marker = self . parent . notes . action [ 'new_bookmark' ] . isChecked ( ) chk_event = self . parent . notes . action [ 'new_event' ] . isChecked ( ) y_distance = self . parent . value ( 'y_distance' ) if chk_marker or chk_event : x_in_scene = self . mapToScene ( event . pos ( ) ) . x ( ) y_in_scene = self . mapToScene ( event . pos ( ) ) . y ( ) # it can happen that selection is empty (f.e. double-click) if self . sel_xy [ 0 ] is not None : # max resolution = sampling frequency # in case there is no data s_freq = self . parent . info . dataset . header [ 's_freq' ] at_s_freq = lambda x : round ( x * s_freq ) / s_freq start = at_s_freq ( self . sel_xy [ 0 ] ) end = at_s_freq ( x_in_scene ) if abs ( end - start ) < self . parent . value ( 'min_marker_dur' ) : end = start if start <= end : time = ( start , end ) else : time = ( end , start ) if chk_marker : self . parent . notes . add_bookmark ( time ) elif chk_event and start != end : eventtype = self . parent . notes . idx_eventtype . currentText ( ) # if dragged across > 1.5 chan, event is marked on all chan if abs ( y_in_scene - self . sel_xy [ 1 ] ) > 1.5 * y_distance : chan = '' else : chan_idx = int ( floor ( self . sel_xy [ 1 ] / y_distance ) ) chan = self . chan [ chan_idx ] self . parent . notes . add_event ( eventtype , time , chan ) else : # normal selection if self . idx_info in self . scene . items ( ) : self . scene . removeItem ( self . idx_info ) self . idx_info = None # restore spectrum self . parent . spectrum . update ( ) self . parent . spectrum . display_window ( ) # general garbage collection self . sel_chan = None self . sel_xy = ( None , None ) if self . idx_sel in self . scene . items ( ) : self . scene . removeItem ( self . idx_sel ) self . idx_sel = None
Create a new event or marker or show the previous power spectrum
629
12
23,533
def next_event ( self , delete = False ) : if delete : msg = "Delete this event? This cannot be undone." msgbox = QMessageBox ( QMessageBox . Question , 'Delete event' , msg ) msgbox . setStandardButtons ( QMessageBox . Yes | QMessageBox . No ) msgbox . setDefaultButton ( QMessageBox . Yes ) response = msgbox . exec_ ( ) if response == QMessageBox . No : return event_sel = self . event_sel if event_sel is None : return notes = self . parent . notes if not self . current_event_row : row = notes . find_row ( event_sel . marker . x ( ) , event_sel . marker . x ( ) + event_sel . marker . width ( ) ) else : row = self . current_event_row same_type = self . action [ 'next_of_same_type' ] . isChecked ( ) if same_type : target = notes . idx_annot_list . item ( row , 2 ) . text ( ) if delete : notes . delete_row ( ) msg = 'Deleted event from {} to {}.' . format ( event_sel . marker . x ( ) , event_sel . marker . x ( ) + event_sel . marker . width ( ) ) self . parent . statusBar ( ) . showMessage ( msg ) row -= 1 if row + 1 == notes . idx_annot_list . rowCount ( ) : return if not same_type : next_row = row + 1 else : next_row = None types = notes . idx_annot_list . property ( 'name' ) [ row + 1 : ] for i , ty in enumerate ( types ) : if ty == target : next_row = row + 1 + i break if next_row is None : return self . current_event_row = next_row notes . go_to_marker ( next_row , 0 , 'annot' ) notes . idx_annot_list . setCurrentCell ( next_row , 0 )
Go to next event .
449
5
23,534
def resizeEvent ( self , event ) : if self . scene is not None : ratio = self . width ( ) / ( self . scene . width ( ) * 1.1 ) self . resetTransform ( ) self . scale ( ratio , 1 )
Resize scene so that it fits the whole widget .
52
11
23,535
def return_dat ( self , chan , begsam , endsam ) : assert begsam < endsam dat = empty ( ( len ( chan ) , endsam - begsam ) ) dat . fill ( NaN ) with self . filename . open ( 'rb' ) as f : for i_dat , blk , i_blk in _select_blocks ( self . blocks , begsam , endsam ) : dat_in_rec = self . _read_record ( f , blk , chan ) dat [ : , i_dat [ 0 ] : i_dat [ 1 ] ] = dat_in_rec [ : , i_blk [ 0 ] : i_blk [ 1 ] ] # calibration dat = ( ( dat . astype ( 'float64' ) - self . dig_min [ chan , newaxis ] ) * self . gain [ chan , newaxis ] + self . phys_min [ chan , newaxis ] ) return dat
Read data from an EDF file .
212
8
23,536
def _read_record ( self , f , blk , chans ) : dat_in_rec = empty ( ( len ( chans ) , self . max_smp ) ) i_ch_in_dat = 0 for i_ch in chans : offset , n_smp_per_chan = self . _offset ( blk , i_ch ) f . seek ( offset ) x = fromfile ( f , count = n_smp_per_chan , dtype = EDF_FORMAT ) ratio = int ( self . max_smp / n_smp_per_chan ) dat_in_rec [ i_ch_in_dat , : ] = repeat ( x , ratio ) i_ch_in_dat += 1 return dat_in_rec
Read raw data from a single EDF channel .
171
10
23,537
def write_brainvision ( data , filename , markers = None ) : filename = Path ( filename ) . resolve ( ) . with_suffix ( '.vhdr' ) if markers is None : markers = [ ] with filename . open ( 'w' ) as f : f . write ( _write_vhdr ( data , filename ) ) with filename . with_suffix ( '.vmrk' ) . open ( 'w' ) as f : f . write ( _write_vmrk ( data , filename , markers ) ) _write_eeg ( data , filename )
Export data in BrainVision format
126
6
23,538
def calc_xyz2surf ( surf , xyz , threshold = 20 , exponent = None , std = None ) : if exponent is None and std is None : exponent = 1 if exponent is not None : lg . debug ( 'Vertex values based on inverse-law, with exponent ' + str ( exponent ) ) funct = partial ( calc_one_vert_inverse , xyz = xyz , exponent = exponent ) elif std is not None : lg . debug ( 'Vertex values based on gaussian, with s.d. ' + str ( std ) ) funct = partial ( calc_one_vert_gauss , xyz = xyz , std = std ) with Pool ( ) as p : xyz2surf = p . map ( funct , surf . vert ) xyz2surf = asarray ( xyz2surf ) if exponent is not None : threshold_value = ( 1 / ( threshold ** exponent ) ) external_threshold_value = threshold_value elif std is not None : threshold_value = gauss ( threshold , std ) external_threshold_value = gauss ( std , std ) # this is around 0.607 lg . debug ( 'Values thresholded at ' + str ( threshold_value ) ) xyz2surf [ xyz2surf < threshold_value ] = NaN # here we deal with vertices that are within the threshold value but far # from a single electrodes, so those remain empty sumval = nansum ( xyz2surf , axis = 1 ) sumval [ sumval < external_threshold_value ] = NaN # normalize by the number of electrodes xyz2surf /= atleast_2d ( sumval ) . T xyz2surf [ isnan ( xyz2surf ) ] = 0 return xyz2surf
Calculate transformation matrix from xyz values to vertices .
404
13
23,539
def calc_one_vert_inverse ( one_vert , xyz = None , exponent = None ) : trans = empty ( xyz . shape [ 0 ] ) for i , one_xyz in enumerate ( xyz ) : trans [ i ] = 1 / ( norm ( one_vert - one_xyz ) ** exponent ) return trans
Calculate how many electrodes influence one vertex using the inverse function .
75
14
23,540
def calc_one_vert_gauss ( one_vert , xyz = None , std = None ) : trans = empty ( xyz . shape [ 0 ] ) for i , one_xyz in enumerate ( xyz ) : trans [ i ] = gauss ( norm ( one_vert - one_xyz ) , std ) return trans
Calculate how many electrodes influence one vertex using a Gaussian function .
75
15
23,541
def _read_history ( f , zone ) : pos , length = zone f . seek ( pos , SEEK_SET ) histories = [ ] while f . tell ( ) < ( pos + length ) : history = { 'nSample' : unpack ( MAX_SAMPLE * 'I' , f . read ( MAX_SAMPLE * 4 ) ) , 'lines' : unpack ( 'H' , f . read ( 2 ) ) , 'sectors' : unpack ( 'H' , f . read ( 2 ) ) , 'base_time' : unpack ( 'H' , f . read ( 2 ) ) , 'notch' : unpack ( 'H' , f . read ( 2 ) ) , 'colour' : unpack ( MAX_CAN_VIEW * 'B' , f . read ( MAX_CAN_VIEW ) ) , 'selection' : unpack ( MAX_CAN_VIEW * 'B' , f . read ( MAX_CAN_VIEW ) ) , 'description' : f . read ( 64 ) . strip ( b'\x01\x00' ) , 'inputsNonInv' : unpack ( MAX_CAN_VIEW * 'H' , f . read ( MAX_CAN_VIEW * 2 ) ) , # NonInv : non inverting input 'inputsInv' : unpack ( MAX_CAN_VIEW * 'H' , f . read ( MAX_CAN_VIEW * 2 ) ) , # Inv : inverting input 'HiPass_Filter' : unpack ( MAX_CAN_VIEW * 'I' , f . read ( MAX_CAN_VIEW * 4 ) ) , 'LowPass_Filter' : unpack ( MAX_CAN_VIEW * 'I' , f . read ( MAX_CAN_VIEW * 4 ) ) , 'reference' : unpack ( MAX_CAN_VIEW * 'I' , f . read ( MAX_CAN_VIEW * 4 ) ) , 'free' : f . read ( 1720 ) . strip ( b'\x01\x00' ) , } histories . append ( history ) return histories
This matches the Matlab reader from Matlab Exchange but doesn t seem correct .
453
16
23,542
def create_video ( self ) : self . instance = vlc . Instance ( ) video_widget = QFrame ( ) self . mediaplayer = self . instance . media_player_new ( ) if system ( ) == 'Linux' : self . mediaplayer . set_xwindow ( video_widget . winId ( ) ) elif system ( ) == 'Windows' : self . mediaplayer . set_hwnd ( video_widget . winId ( ) ) elif system ( ) == 'darwin' : # to test self . mediaplayer . set_nsobject ( video_widget . winId ( ) ) else : lg . warning ( 'unsupported system for video widget' ) return self . medialistplayer = vlc . MediaListPlayer ( ) self . medialistplayer . set_media_player ( self . mediaplayer ) event_manager = self . medialistplayer . event_manager ( ) event_manager . event_attach ( vlc . EventType . MediaListPlayerNextItemSet , self . next_video ) self . idx_button = QPushButton ( ) self . idx_button . setText ( 'Start' ) self . idx_button . clicked . connect ( self . start_stop_video ) layout = QVBoxLayout ( ) layout . addWidget ( video_widget ) layout . addWidget ( self . idx_button ) self . setLayout ( layout )
Create video widget .
306
4
23,543
def stop_video ( self , tick ) : if self . cnt_video == self . n_video : if tick >= self . end_diff : self . idx_button . setText ( 'Start' ) self . video . stop ( )
Stop video if tick is more than the end only for last file .
54
14
23,544
def next_video ( self , _ ) : self . cnt_video += 1 lg . info ( 'Update video to ' + str ( self . cnt_video ) )
Also runs when file is loaded so index starts at 2 .
39
12
23,545
def start_stop_video ( self ) : if self . parent . info . dataset is None : self . parent . statusBar ( ) . showMessage ( 'No Dataset Loaded' ) return # & is added automatically by PyQt, it seems if 'Start' in self . idx_button . text ( ) . replace ( '&' , '' ) : try : self . update_video ( ) except IndexError as er : lg . debug ( er ) self . idx_button . setText ( 'Not Available / Start' ) return except OSError as er : lg . debug ( er ) self . idx_button . setText ( 'NO VIDEO for this dataset' ) return self . idx_button . setText ( 'Stop' ) elif 'Stop' in self . idx_button . text ( ) : self . idx_button . setText ( 'Start' ) self . medialistplayer . stop ( ) self . t . stop ( )
Start and stop the video and change the button .
214
10
23,546
def update_video ( self ) : window_start = self . parent . value ( 'window_start' ) window_length = self . parent . value ( 'window_length' ) d = self . parent . info . dataset videos , begsec , endsec = d . read_videos ( window_start , window_start + window_length ) lg . debug ( f'Video: {begsec} - {endsec}' ) self . endsec = endsec videos = [ str ( v ) for v in videos ] # make sure it's a str (not path) medialist = vlc . MediaList ( videos ) self . medialistplayer . set_media_list ( medialist ) self . cnt_video = 0 self . n_video = len ( videos ) self . t = QTimer ( ) self . t . timeout . connect ( self . check_if_finished ) self . t . start ( 100 ) self . medialistplayer . play ( ) self . mediaplayer . set_time ( int ( begsec * 1000 ) )
Read list of files convert to video time and add video to queue .
228
14
23,547
def montage ( data , ref_chan = None , ref_to_avg = False , bipolar = None , method = 'average' ) : if ref_to_avg and ref_chan is not None : raise TypeError ( 'You cannot specify reference to the average and ' 'the channels to use as reference' ) if ref_chan is not None : if ( not isinstance ( ref_chan , ( list , tuple ) ) or not all ( isinstance ( x , str ) for x in ref_chan ) ) : raise TypeError ( 'chan should be a list of strings' ) if ref_chan is None : ref_chan = [ ] # TODO: check bool for ref_chan if bipolar : if not data . attr [ 'chan' ] : raise ValueError ( 'Data should have Chan information in attr' ) _assert_equal_channels ( data . axis [ 'chan' ] ) chan_in_data = data . axis [ 'chan' ] [ 0 ] chan = data . attr [ 'chan' ] chan = chan ( lambda x : x . label in chan_in_data ) chan , trans = create_bipolar_chan ( chan , bipolar ) data . attr [ 'chan' ] = chan if ref_to_avg or ref_chan or bipolar : mdata = data . _copy ( ) idx_chan = mdata . index_of ( 'chan' ) for i in range ( mdata . number_of ( 'trial' ) ) : if ref_to_avg or ref_chan : if ref_to_avg : ref_chan = data . axis [ 'chan' ] [ i ] ref_data = data ( trial = i , chan = ref_chan ) if method == 'average' : mdata . data [ i ] = ( data ( trial = i ) - mean ( ref_data , axis = idx_chan ) ) elif method == 'regression' : mdata . data [ i ] = compute_average_regress ( data ( trial = i ) , idx_chan ) elif bipolar : if not data . index_of ( 'chan' ) == 0 : raise ValueError ( 'For matrix multiplication to work, ' 'the first dimension should be chan' ) mdata . data [ i ] = dot ( trans , data ( trial = i ) ) mdata . axis [ 'chan' ] [ i ] = asarray ( chan . return_label ( ) , dtype = 'U' ) else : mdata = data return mdata
Apply linear transformation to the channels .
560
7
23,548
def _assert_equal_channels ( axis ) : for i0 in axis : for i1 in axis : if not all ( i0 == i1 ) : raise ValueError ( 'The channels for all the trials should have ' 'the same labels, in the same order.' )
check that all the trials have the same channels in the same order .
60
14
23,549
def compute_average_regress ( x , idx_chan ) : if x . ndim != 2 : raise ValueError ( f'The number of dimensions must be 2, not {x.ndim}' ) x = moveaxis ( x , idx_chan , 0 ) # move axis to the front avg = mean ( x , axis = 0 ) x_o = [ ] for i in range ( x . shape [ 0 ] ) : r = lstsq ( avg [ : , None ] , x [ i , : ] [ : , None ] , rcond = 0 ) [ 0 ] x_o . append ( x [ i , : ] - r [ 0 , 0 ] * avg ) return moveaxis ( asarray ( x_o ) , 0 , idx_chan )
Take the mean across channels and regress out the mean from each channel
170
13
23,550
def keep_recent_datasets ( max_dataset_history , info = None ) : history = settings . value ( 'recent_recordings' , [ ] ) if isinstance ( history , str ) : history = [ history ] if info is not None and info . filename is not None : new_dataset = info . filename if new_dataset in history : lg . debug ( new_dataset + ' already present, will be replaced' ) history . remove ( new_dataset ) if len ( history ) > max_dataset_history : lg . debug ( 'Removing last dataset ' + history [ - 1 ] ) history . pop ( ) lg . debug ( 'Adding ' + new_dataset + ' to list of recent datasets' ) history . insert ( 0 , new_dataset ) settings . setValue ( 'recent_recordings' , history ) return None else : return history
Keep track of the most recent recordings .
205
8
23,551
def choose_file_or_dir ( ) : question = QMessageBox ( QMessageBox . Information , 'Open Dataset' , 'Do you want to open a file or a directory?' ) dir_button = question . addButton ( 'Directory' , QMessageBox . YesRole ) file_button = question . addButton ( 'File' , QMessageBox . NoRole ) question . addButton ( QMessageBox . Cancel ) question . exec_ ( ) response = question . clickedButton ( ) if response == dir_button : return 'dir' elif response == file_button : return 'file' else : return 'abort'
Create a simple message box to see if the user wants to open dir or file
138
16
23,552
def convert_name_to_color ( s ) : h = 100 v = [ 5 * ord ( x ) for x in s ] sum_mod = lambda x : sum ( x ) % 100 color = QColor ( sum_mod ( v [ : : 3 ] ) + h , sum_mod ( v [ 1 : : 3 ] ) + h , sum_mod ( v [ 2 : : 3 ] ) + h ) return color
Convert any string to an RGB color .
93
9
23,553
def freq_from_str ( freq_str ) : freq = [ ] as_list = freq_str [ 1 : - 1 ] . replace ( ' ' , '' ) . split ( ',' ) try : if freq_str [ 0 ] == '[' and freq_str [ - 1 ] == ']' : for i in as_list : one_band = i [ 1 : - 1 ] . split ( '-' ) one_band = float ( one_band [ 0 ] ) , float ( one_band [ 1 ] ) freq . append ( one_band ) elif freq_str [ 0 ] == '(' and freq_str [ - 1 ] == ')' : if len ( as_list ) == 4 : start = float ( as_list [ 0 ] ) stop = float ( as_list [ 1 ] ) halfwidth = float ( as_list [ 2 ] ) / 2 step = float ( as_list [ 3 ] ) centres = arange ( start , stop , step ) for i in centres : freq . append ( ( i - halfwidth , i + halfwidth ) ) else : return None else : return None except : return None return freq
Obtain frequency ranges from input string either as list or dynamic notation .
259
14
23,554
def export_graphics_to_svg ( widget , filename ) : generator = QSvgGenerator ( ) generator . setFileName ( filename ) generator . setSize ( widget . size ( ) ) generator . setViewBox ( widget . rect ( ) ) painter = QPainter ( ) painter . begin ( generator ) widget . render ( painter ) painter . end ( )
Export graphics to svg
80
5
23,555
def get_value ( self , default = None ) : if default is None : default = [ ] try : text = literal_eval ( self . text ( ) ) if not isinstance ( text , list ) : pass # raise ValueError except ValueError : lg . debug ( 'Cannot convert "' + str ( text ) + '" to list. ' + 'Using default ' + str ( default ) ) text = default self . set_value ( text ) return text
Get int from widget .
100
5
23,556
def connect ( self , funct ) : def get_directory ( ) : rec = QFileDialog . getExistingDirectory ( self , 'Path to Recording' ' Directory' ) if rec == '' : return self . setText ( rec ) funct ( ) self . clicked . connect ( get_directory )
Call funct when the text was changed .
65
9
23,557
def get_value ( self , default = None ) : if default is None : default = '' try : text = self . currentText ( ) except ValueError : lg . debug ( 'Cannot convert "' + str ( text ) + '" to list. ' + 'Using default ' + str ( default ) ) text = default self . set_value ( text ) return text
Get selection from widget .
80
5
23,558
def _write_ieeg_json ( output_file ) : dataset_info = { "TaskName" : "unknown" , "Manufacturer" : "n/a" , "PowerLineFrequency" : 50 , "iEEGReference" : "n/a" , } with output_file . open ( 'w' ) as f : dump ( dataset_info , f , indent = ' ' )
Use only required fields
89
4
23,559
def value ( self , parameter , new_value = None ) : for widget_name , values in DEFAULTS . items ( ) : if parameter in values . keys ( ) : widget = getattr ( self , widget_name ) if new_value is None : return widget . config . value [ parameter ] else : lg . debug ( 'setting value {0} of {1} to {2}' '' . format ( parameter , widget_name , new_value ) ) widget . config . value [ parameter ] = new_value
This function is a shortcut for any parameter . Instead of calling the widget its config and its values you can call directly the parameter .
114
26
23,560
def update ( self ) : self . info . display_dataset ( ) self . overview . update ( ) self . labels . update ( labels = self . info . dataset . header [ 'chan_name' ] ) self . channels . update ( ) try : self . info . markers = self . info . dataset . read_markers ( ) except FileNotFoundError : lg . info ( 'No notes/markers present in the header of the file' ) else : self . notes . update_dataset_marker ( )
Once you open a dataset it activates all the widgets .
116
11
23,561
def reset ( self ) : # store current dataset max_dataset_history = self . value ( 'max_dataset_history' ) keep_recent_datasets ( max_dataset_history , self . info ) # reset all the widgets self . labels . reset ( ) self . channels . reset ( ) self . info . reset ( ) self . notes . reset ( ) self . overview . reset ( ) self . spectrum . reset ( ) self . traces . reset ( )
Remove all the information from previous dataset before loading a new dataset .
106
13
23,562
def show_settings ( self ) : self . notes . config . put_values ( ) self . overview . config . put_values ( ) self . settings . config . put_values ( ) self . spectrum . config . put_values ( ) self . traces . config . put_values ( ) self . video . config . put_values ( ) self . settings . show ( )
Open the Setting windows after updating the values in GUI .
81
11
23,563
def show_spindle_dialog ( self ) : self . spindle_dialog . update_groups ( ) self . spindle_dialog . update_cycles ( ) self . spindle_dialog . show ( )
Create the spindle detection dialog .
49
7
23,564
def show_slow_wave_dialog ( self ) : self . slow_wave_dialog . update_groups ( ) self . slow_wave_dialog . update_cycles ( ) self . slow_wave_dialog . show ( )
Create the SW detection dialog .
53
6
23,565
def show_event_analysis_dialog ( self ) : self . event_analysis_dialog . update_types ( ) self . event_analysis_dialog . update_groups ( ) self . event_analysis_dialog . update_cycles ( ) self . event_analysis_dialog . show ( )
Create the event analysis dialog .
67
6
23,566
def show_analysis_dialog ( self ) : self . analysis_dialog . update_evt_types ( ) self . analysis_dialog . update_groups ( ) self . analysis_dialog . update_cycles ( ) self . analysis_dialog . show ( )
Create the analysis dialog .
60
5
23,567
def closeEvent ( self , event ) : max_dataset_history = self . value ( 'max_dataset_history' ) keep_recent_datasets ( max_dataset_history , self . info ) settings . setValue ( 'window/geometry' , self . saveGeometry ( ) ) settings . setValue ( 'window/state' , self . saveState ( ) ) event . accept ( )
save the name of the last open dataset .
94
9
23,568
def _read_header ( filename ) : header = _read_header_text ( filename ) first_row = header [ 0 ] EXTRA_ROWS = 3 # drop DefaultValue1 LowRange1 HighRange1 hdr = { } for group in finditer ( '(\w*)= ([\w.]*)' , first_row ) : hdr [ group . group ( 1 ) ] = group . group ( 2 ) if first_row . startswith ( 'BCI2000V' ) : VERSION = hdr [ 'BCI2000V' ] else : VERSION = '1' hdr [ 'DataFormat' ] = 'int16' for row in header [ 1 : ] : if row . startswith ( '[' ) : # remove '[ ... Definition ]' section = row [ 2 : - 14 ] . replace ( ' ' , '' ) if section == 'StateVector' : hdr [ section ] = [ ] else : hdr [ section ] = { } # defaultdict(dict) continue if row == '' : continue elif section == 'StateVector' : statevector = { key : value for key , value in list ( zip ( STATEVECTOR , row . split ( ' ' ) ) ) } hdr [ section ] . append ( statevector ) else : group = match ( '(?P<subsection>[\w:%]*) (?P<format>\w*) (?P<key>\w*)= (?P<value>.*) // ' , row ) onerow = group . groupdict ( ) values = onerow [ 'value' ] . split ( ' ' ) if len ( values ) > EXTRA_ROWS : value = ' ' . join ( onerow [ 'value' ] . split ( ' ' ) [ : - EXTRA_ROWS ] ) else : value = ' ' . join ( values ) hdr [ section ] [ onerow [ 'key' ] ] = value # similar to matlab's output return hdr
It s a pain to parse the header . It might be better to use the cpp code but I would need to include it here .
433
28
23,569
def remove_artf_evts ( times , annot , chan = None , min_dur = 0.1 ) : new_times = times beg = times [ 0 ] [ 0 ] end = times [ - 1 ] [ - 1 ] chan = ( chan , '' ) if chan else None # '' is for channel-global artefacts artefact = annot . get_events ( name = 'Artefact' , time = ( beg , end ) , chan = chan , qual = 'Good' ) if artefact : new_times = [ ] for seg in times : reject = False new_seg = True while new_seg is not False : if type ( new_seg ) is tuple : seg = new_seg end = seg [ 1 ] for artf in artefact : if artf [ 'start' ] <= seg [ 0 ] and seg [ 1 ] <= artf [ 'end' ] : reject = True new_seg = False break a_starts_in_s = seg [ 0 ] <= artf [ 'start' ] <= seg [ 1 ] a_ends_in_s = seg [ 0 ] <= artf [ 'end' ] <= seg [ 1 ] if a_ends_in_s and not a_starts_in_s : seg = artf [ 'end' ] , seg [ 1 ] elif a_starts_in_s : seg = seg [ 0 ] , artf [ 'start' ] if a_ends_in_s : new_seg = artf [ 'end' ] , end else : new_seg = False break new_seg = False if reject is False and seg [ 1 ] - seg [ 0 ] >= min_dur : new_times . append ( seg ) return new_times
Correct times to remove events marked Artefact .
408
10
23,570
def statement_ref_mode ( self , value ) : valid_values = [ 'STRICT_KEEP' , 'STRICT_KEEP_APPEND' , 'STRICT_OVERWRITE' , 'KEEP_GOOD' , 'CUSTOM' ] if value not in valid_values : raise ValueError ( 'Not an allowed reference mode, allowed values {}' . format ( ' ' . join ( valid_values ) ) ) self . _statement_ref_mode = value
Set the reference mode for a statement always overrides the global reference state .
106
15
23,571
def equals ( self , that , include_ref = False , fref = None ) : if not include_ref : # return the result of WDBaseDataType.__eq__, which is testing for equality of value and qualifiers return self == that if include_ref and self != that : return False if include_ref and fref is None : fref = WDBaseDataType . refs_equal return fref ( self , that )
Tests for equality of two statements . If comparing references the order of the arguments matters!!! self is the current statement the next argument is the new statement . Allows passing in a function to use to compare the references fref . Default is equality . fref accepts two arguments oldrefs and newrefs each of which are a list of references where each reference is a list of statements
95
77
23,572
def refs_equal ( olditem , newitem ) : oldrefs = olditem . references newrefs = newitem . references ref_equal = lambda oldref , newref : True if ( len ( oldref ) == len ( newref ) ) and all ( x in oldref for x in newref ) else False if len ( oldrefs ) == len ( newrefs ) and all ( any ( ref_equal ( oldref , newref ) for oldref in oldrefs ) for newref in newrefs ) : return True else : return False
tests for exactly identical references
122
5
23,573
def try_write ( wd_item , record_id , record_prop , login , edit_summary = '' , write = True ) : if wd_item . require_write : if wd_item . create_new_item : msg = "CREATE" else : msg = "UPDATE" else : msg = "SKIP" try : if write : wd_item . write ( login = login , edit_summary = edit_summary ) wdi_core . WDItemEngine . log ( "INFO" , format_msg ( record_id , record_prop , wd_item . wd_item_id , msg ) + ";" + str ( wd_item . lastrevid ) ) except wdi_core . WDApiError as e : print ( e ) wdi_core . WDItemEngine . log ( "ERROR" , format_msg ( record_id , record_prop , wd_item . wd_item_id , json . dumps ( e . wd_error_msg ) , type ( e ) ) ) return e except Exception as e : print ( e ) wdi_core . WDItemEngine . log ( "ERROR" , format_msg ( record_id , record_prop , wd_item . wd_item_id , str ( e ) , type ( e ) ) ) return e return True
Write a PBB_core item . Log if item was created updated or skipped . Catch and log all errors .
296
23
23,574
def _build_app_dict ( site , request , label = None ) : app_dict = { } if label : models = { m : m_a for m , m_a in site . _registry . items ( ) if m . _meta . app_label == label } else : models = site . _registry for model , model_admin in models . items ( ) : app_label = model . _meta . app_label has_module_perms = model_admin . has_module_permission ( request ) if not has_module_perms : continue perms = model_admin . get_model_perms ( request ) # Check whether user has any perm for this module. # If so, add the module to the model_list. if True not in perms . values ( ) : continue info = ( app_label , model . _meta . model_name ) model_dict = { 'name' : capfirst ( model . _meta . verbose_name_plural ) , 'object_name' : model . _meta . object_name , 'perms' : perms , } if perms . get ( 'change' ) : try : model_dict [ 'admin_url' ] = reverse ( 'admin:%s_%s_changelist' % info , current_app = site . name ) except NoReverseMatch : pass if perms . get ( 'add' ) : try : model_dict [ 'add_url' ] = reverse ( 'admin:%s_%s_add' % info , current_app = site . name ) except NoReverseMatch : pass if app_label in app_dict : app_dict [ app_label ] [ 'models' ] . append ( model_dict ) else : app_dict [ app_label ] = { 'name' : apps . get_app_config ( app_label ) . verbose_name , 'app_label' : app_label , 'app_url' : reverse ( 'admin:app_list' , kwargs = { 'app_label' : app_label } , current_app = site . name , ) , 'has_module_perms' : has_module_perms , 'models' : [ model_dict ] , } if label : return app_dict . get ( label ) return app_dict
Builds the app dictionary . Takes an optional label parameters to filter models of a specific app .
516
19
23,575
def get_app_list ( site , request ) : app_dict = _build_app_dict ( site , request ) # Sort the apps alphabetically. app_list = sorted ( app_dict . values ( ) , key = lambda x : x [ 'name' ] . lower ( ) ) # Sort the models alphabetically within each app. for app in app_list : app [ 'models' ] . sort ( key = lambda x : x [ 'name' ] ) return app_list
Returns a sorted list of all the installed apps that have been registered in this site .
106
17
23,576
def format_query_results ( self , r , prop_nr ) : prop_dt = self . get_prop_datatype ( prop_nr ) for i in r : for value in { 'item' , 'sid' , 'pq' , 'pr' , 'ref' } : if value in i : # these are always URIs for the local wikibase i [ value ] = i [ value ] [ 'value' ] . split ( '/' ) [ - 1 ] # make sure datetimes are formatted correctly. # the correct format is '+%Y-%m-%dT%H:%M:%SZ', but is sometimes missing the plus?? # some difference between RDF and xsd:dateTime that I don't understand for value in { 'v' , 'qval' , 'rval' } : if value in i : if i [ value ] . get ( "datatype" ) == 'http://www.w3.org/2001/XMLSchema#dateTime' and not i [ value ] [ 'value' ] [ 0 ] in '+-' : # if it is a dateTime and doesn't start with plus or minus, add a plus i [ value ] [ 'value' ] = '+' + i [ value ] [ 'value' ] # these three ({'v', 'qval', 'rval'}) are values that can be any data type # strip off the URI if they are wikibase-items if 'v' in i : if i [ 'v' ] [ 'type' ] == 'uri' and prop_dt == 'wikibase-item' : i [ 'v' ] = i [ 'v' ] [ 'value' ] . split ( '/' ) [ - 1 ] else : i [ 'v' ] = i [ 'v' ] [ 'value' ] # Note: no-value and some-value don't actually show up in the results here # see for example: select * where { wd:Q7207 p:P40 ?c . ?c ?d ?e } if type ( i [ 'v' ] ) is not dict : self . rev_lookup [ i [ 'v' ] ] . add ( i [ 'item' ] ) # handle qualifier value if 'qval' in i : qual_prop_dt = self . get_prop_datatype ( prop_nr = i [ 'pq' ] ) if i [ 'qval' ] [ 'type' ] == 'uri' and qual_prop_dt == 'wikibase-item' : i [ 'qval' ] = i [ 'qval' ] [ 'value' ] . split ( '/' ) [ - 1 ] else : i [ 'qval' ] = i [ 'qval' ] [ 'value' ] # handle reference value if 'rval' in i : ref_prop_dt = self . get_prop_datatype ( prop_nr = i [ 'pr' ] ) if i [ 'rval' ] [ 'type' ] == 'uri' and ref_prop_dt == 'wikibase-item' : i [ 'rval' ] = i [ 'rval' ] [ 'value' ] . split ( '/' ) [ - 1 ] else : i [ 'rval' ] = i [ 'rval' ] [ 'value' ]
r is the results of the sparql query in _query_data and is modified in place prop_nr is needed to get the property datatype to determine how to format the value
739
38
23,577
def clear ( self ) : self . prop_dt_map = dict ( ) self . prop_data = dict ( ) self . rev_lookup = defaultdict ( set )
convinience function to empty this fastrun container
38
10
23,578
def times ( p , mint , maxt = None ) : maxt = maxt if maxt else mint @ Parser def times_parser ( text , index ) : cnt , values , res = 0 , Value . success ( index , [ ] ) , None while cnt < maxt : res = p ( text , index ) if res . status : values = values . aggregate ( Value . success ( res . index , [ res . value ] ) ) index , cnt = res . index , cnt + 1 else : if cnt >= mint : break else : return res # failed, throw exception. if cnt >= maxt : # finish. break # If we don't have any remaining text to start next loop, we need break. # # We cannot put the `index < len(text)` in where because some parser can # success even when we have no any text. We also need to detect if the # parser consume no text. # # See: #28 if index >= len ( text ) : if cnt >= mint : break # we already have decent result to return else : r = p ( text , index ) if index != r . index : # report error when the parser cannot success with no text return Value . failure ( index , "already meets the end, no enough text" ) return values return times_parser
Repeat a parser between mint and maxt times . DO AS MUCH MATCH AS IT CAN . Return a list of values .
283
25
23,579
def optional ( p , default_value = None ) : @ Parser def optional_parser ( text , index ) : res = p ( text , index ) if res . status : return Value . success ( res . index , res . value ) else : # Return the maybe existing default value without doing anything. return Value . success ( res . index , default_value ) return optional_parser
Make a parser as optional . If success return the result otherwise return default_value silently without raising any exception . If default_value is not provided None is returned instead .
81
34
23,580
def separated ( p , sep , mint , maxt = None , end = None ) : maxt = maxt if maxt else mint @ Parser def sep_parser ( text , index ) : cnt , values , res = 0 , Value . success ( index , [ ] ) , None while cnt < maxt : if end in [ False , None ] and cnt > 0 : res = sep ( text , index ) if res . status : # `sep` found, consume it (advance index) index , values = res . index , Value . success ( res . index , values . value ) elif cnt < mint : return res # error: need more elemnts, but no `sep` found. else : break res = p ( text , index ) if res . status : values = values . aggregate ( Value . success ( res . index , [ res . value ] ) ) index , cnt = res . index , cnt + 1 elif cnt >= mint : break else : return res # error: need more elements, but no `p` found. if end is True : res = sep ( text , index ) if res . status : index , values = res . index , Value . success ( res . index , values . value ) else : return res # error: trailing `sep` not found if cnt >= maxt : break return values return sep_parser
Repeat a parser p separated by s between mint and maxt times . When end is None a trailing separator is optional . When end is True a trailing separator is required . When end is False a trailing separator is not allowed . MATCHES AS MUCH AS POSSIBLE . Return list of values returned by p .
299
66
23,581
def one_of ( s ) : @ Parser def one_of_parser ( text , index = 0 ) : if index < len ( text ) and text [ index ] in s : return Value . success ( index + 1 , text [ index ] ) else : return Value . failure ( index , 'one of {}' . format ( s ) ) return one_of_parser
Parser a char from specified string .
80
7
23,582
def none_of ( s ) : @ Parser def none_of_parser ( text , index = 0 ) : if index < len ( text ) and text [ index ] not in s : return Value . success ( index + 1 , text [ index ] ) else : return Value . failure ( index , 'none of {}' . format ( s ) ) return none_of_parser
Parser a char NOT from specified string .
81
8
23,583
def space ( ) : @ Parser def space_parser ( text , index = 0 ) : if index < len ( text ) and text [ index ] . isspace ( ) : return Value . success ( index + 1 , text [ index ] ) else : return Value . failure ( index , 'one space' ) return space_parser
Parser a whitespace character .
70
6
23,584
def letter ( ) : @ Parser def letter_parser ( text , index = 0 ) : if index < len ( text ) and text [ index ] . isalpha ( ) : return Value . success ( index + 1 , text [ index ] ) else : return Value . failure ( index , 'a letter' ) return letter_parser
Parse a letter in alphabet .
70
7
23,585
def digit ( ) : @ Parser def digit_parser ( text , index = 0 ) : if index < len ( text ) and text [ index ] . isdigit ( ) : return Value . success ( index + 1 , text [ index ] ) else : return Value . failure ( index , 'a digit' ) return digit_parser
Parse a digit character .
70
6
23,586
def eof ( ) : @ Parser def eof_parser ( text , index = 0 ) : if index >= len ( text ) : return Value . success ( index , None ) else : return Value . failure ( index , 'EOF' ) return eof_parser
Parser EOF flag of a string .
58
8
23,587
def string ( s ) : @ Parser def string_parser ( text , index = 0 ) : slen , tlen = len ( s ) , len ( text ) if text [ index : index + slen ] == s : return Value . success ( index + slen , s ) else : matched = 0 while matched < slen and index + matched < tlen and text [ index + matched ] == s [ matched ] : matched = matched + 1 return Value . failure ( index + matched , s ) return string_parser
Parser a string .
111
4
23,588
def loc_info ( text , index ) : if index > len ( text ) : raise ValueError ( 'Invalid index.' ) line , last_ln = text . count ( '\n' , 0 , index ) , text . rfind ( '\n' , 0 , index ) col = index - ( last_ln + 1 ) return ( line , col )
Location of index in source code text .
78
8
23,589
def loc ( self ) : try : return '{}:{}' . format ( * ParseError . loc_info ( self . text , self . index ) ) except ValueError : return '<out of bounds index {!r}>' . format ( self . index )
Locate the error position in the source code text .
60
11
23,590
def aggregate ( self , other = None ) : if not self . status : return self if not other : return self if not other . status : return other return Value ( True , other . index , self . value + other . value , None )
collect the furthest failure from self and other .
51
10
23,591
def combinate ( values ) : prev_v = None for v in values : if prev_v : if not v : return prev_v if not v . status : return v out_values = tuple ( [ v . value for v in values ] ) return Value ( True , values [ - 1 ] . index , out_values , None )
aggregate multiple values into tuple
73
6
23,592
def parse_partial ( self , text ) : if not isinstance ( text , str ) : raise TypeError ( 'Can only parsing string but got {!r}' . format ( text ) ) res = self ( text , 0 ) if res . status : return ( res . value , text [ res . index : ] ) else : raise ParseError ( res . expected , text , res . index )
Parse the longest possible prefix of a given string . Return a tuple of the result value and the rest of the string . If failed raise a ParseError .
86
33
23,593
def bind ( self , fn ) : @ Parser def bind_parser ( text , index ) : res = self ( text , index ) return res if not res . status else fn ( res . value ) ( text , res . index ) return bind_parser
This is the monadic binding operation . Returns a parser which if parser is successful passes the result to fn and continues with the parser returned from fn .
54
30
23,594
def parsecmap ( self , fn ) : return self . bind ( lambda res : Parser ( lambda _ , index : Value . success ( index , fn ( res ) ) ) )
Returns a parser that transforms the produced value of parser with fn .
39
13
23,595
def parsecapp ( self , other ) : # pylint: disable=unnecessary-lambda return self . bind ( lambda res : other . parsecmap ( lambda x : res ( x ) ) )
Returns a parser that applies the produced value of this parser to the produced value of other .
44
18
23,596
def result ( self , res ) : return self >> Parser ( lambda _ , index : Value . success ( index , res ) )
Return a value according to the parameter res when parse successfully .
28
12
23,597
def mark ( self ) : def pos ( text , index ) : return ParseError . loc_info ( text , index ) @ Parser def mark_parser ( text , index ) : res = self ( text , index ) if res . status : return Value . success ( res . index , ( pos ( text , index ) , res . value , pos ( text , res . index ) ) ) else : return res # failed. return mark_parser
Mark the line and column information of the result of this parser .
95
13
23,598
def desc ( self , description ) : return self | Parser ( lambda _ , index : Value . failure ( index , description ) )
Describe a parser when it failed print out the description text .
28
13
23,599
def route ( * args ) : def _validate_route ( route ) : if not isinstance ( route , six . string_types ) : raise TypeError ( '%s must be a string' % route ) if route in ( '.' , '..' ) or not re . match ( '^[0-9a-zA-Z-_$\(\)\.~!,;:*+@=]+$' , route ) : raise ValueError ( '%s must be a valid path segment. Keep in mind ' 'that path segments should not contain path separators ' '(e.g., /) ' % route ) if len ( args ) == 2 : # The handler in this situation is a @pecan.expose'd callable, # and is generally only used by the @expose() decorator itself. # # This sets a special attribute, `custom_route` on the callable, which # pecan's routing logic knows how to make use of (as a special case) route , handler = args if ismethod ( handler ) : handler = handler . __func__ if not iscontroller ( handler ) : raise TypeError ( '%s must be a callable decorated with @pecan.expose' % handler ) obj , attr , value = handler , 'custom_route' , route if handler . __name__ in ( '_lookup' , '_default' , '_route' ) : raise ValueError ( '%s is a special method in pecan and cannot be used in ' 'combination with custom path segments.' % handler . __name__ ) elif len ( args ) == 3 : # This is really just a setattr on the parent controller (with some # additional validation for the path segment itself) _ , route , handler = args obj , attr , value = args if hasattr ( obj , attr ) : raise RuntimeError ( ( "%(module)s.%(class)s already has an " "existing attribute named \"%(route)s\"." % { 'module' : obj . __module__ , 'class' : obj . __name__ , 'route' : attr } ) , ) else : raise TypeError ( 'pecan.route should be called in the format ' 'route(ParentController, "path-segment", SubController())' ) _validate_route ( route ) setattr ( obj , attr , value )
This function is used to define an explicit route for a path segment .
518
14