id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
25,100
wonambi-python/wonambi
wonambi/widgets/traces.py
Traces.next_event
def next_event(self, delete=False): """Go to next event.""" 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)
python
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)
[ "def", "next_event", "(", "self", ",", "delete", "=", "False", ")", ":", "if", "delete", ":", "msg", "=", "\"Delete this event? This cannot be undone.\"", "msgbox", "=", "QMessageBox", "(", "QMessageBox", ".", "Question", ",", "'Delete event'", ",", "msg", ")", ...
Go to next event.
[ "Go", "to", "next", "event", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L1048-L1101
25,101
wonambi-python/wonambi
wonambi/widgets/traces.py
Traces.resizeEvent
def resizeEvent(self, event): """Resize scene so that it fits the whole widget. Parameters ---------- event : instance of QtCore.QEvent not important Notes ----- This function overwrites Qt function, therefore the non-standard name. Argument also depends on Qt. The function is used to change the scale of view, so that the scene fits the whole scene. There are two problems that I could not fix: 1) how to give the width of the label in absolute width, 2) how to strech scene just enough that it doesn't trigger a scrollbar. However, it's pretty good as it is now. """ if self.scene is not None: ratio = self.width() / (self.scene.width() * 1.1) self.resetTransform() self.scale(ratio, 1)
python
def resizeEvent(self, event): if self.scene is not None: ratio = self.width() / (self.scene.width() * 1.1) self.resetTransform() self.scale(ratio, 1)
[ "def", "resizeEvent", "(", "self", ",", "event", ")", ":", "if", "self", ".", "scene", "is", "not", "None", ":", "ratio", "=", "self", ".", "width", "(", ")", "/", "(", "self", ".", "scene", ".", "width", "(", ")", "*", "1.1", ")", "self", ".",...
Resize scene so that it fits the whole widget. Parameters ---------- event : instance of QtCore.QEvent not important Notes ----- This function overwrites Qt function, therefore the non-standard name. Argument also depends on Qt. The function is used to change the scale of view, so that the scene fits the whole scene. There are two problems that I could not fix: 1) how to give the width of the label in absolute width, 2) how to strech scene just enough that it doesn't trigger a scrollbar. However, it's pretty good as it is now.
[ "Resize", "scene", "so", "that", "it", "fits", "the", "whole", "widget", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L1130-L1152
25,102
wonambi-python/wonambi
wonambi/ioeeg/edf.py
Edf.return_dat
def return_dat(self, chan, begsam, endsam): """Read data from an EDF file. Reads channel by channel, and adjusts the values by calibration. Parameters ---------- chan : list of int index (indices) of the channels to read begsam : int index of the first sample endsam : int index of the last sample Returns ------- numpy.ndarray A 2d matrix, where the first dimension is the channels and the second dimension are the samples. """ 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
python
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
[ "def", "return_dat", "(", "self", ",", "chan", ",", "begsam", ",", "endsam", ")", ":", "assert", "begsam", "<", "endsam", "dat", "=", "empty", "(", "(", "len", "(", "chan", ")", ",", "endsam", "-", "begsam", ")", ")", "dat", ".", "fill", "(", "Na...
Read data from an EDF file. Reads channel by channel, and adjusts the values by calibration. Parameters ---------- chan : list of int index (indices) of the channels to read begsam : int index of the first sample endsam : int index of the last sample Returns ------- numpy.ndarray A 2d matrix, where the first dimension is the channels and the second dimension are the samples.
[ "Read", "data", "from", "an", "EDF", "file", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/edf.py#L177-L212
25,103
wonambi-python/wonambi
wonambi/ioeeg/edf.py
Edf._read_record
def _read_record(self, f, blk, chans): """Read raw data from a single EDF channel. Parameters ---------- i_chan : int index of the channel to read begsam : int index of the first sample endsam : int index of the last sample Returns ------- numpy.ndarray A vector with the data as written on file, in 16-bit precision """ 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
python
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
[ "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", ":", "...
Read raw data from a single EDF channel. Parameters ---------- i_chan : int index of the channel to read begsam : int index of the first sample endsam : int index of the last sample Returns ------- numpy.ndarray A vector with the data as written on file, in 16-bit precision
[ "Read", "raw", "data", "from", "a", "single", "EDF", "channel", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/edf.py#L214-L244
25,104
wonambi-python/wonambi
wonambi/ioeeg/brainvision.py
write_brainvision
def write_brainvision(data, filename, markers=None): """Export data in BrainVision format Parameters ---------- data : instance of ChanTime data with only one trial filename : path to file file to export to (use '.vhdr' as extension) """ 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)
python
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)
[ "def", "write_brainvision", "(", "data", ",", "filename", ",", "markers", "=", "None", ")", ":", "filename", "=", "Path", "(", "filename", ")", ".", "resolve", "(", ")", ".", "with_suffix", "(", "'.vhdr'", ")", "if", "markers", "is", "None", ":", "mark...
Export data in BrainVision format Parameters ---------- data : instance of ChanTime data with only one trial filename : path to file file to export to (use '.vhdr' as extension)
[ "Export", "data", "in", "BrainVision", "format" ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/brainvision.py#L226-L246
25,105
wonambi-python/wonambi
wonambi/source/linear.py
calc_xyz2surf
def calc_xyz2surf(surf, xyz, threshold=20, exponent=None, std=None): """Calculate transformation matrix from xyz values to vertices. Parameters ---------- surf : instance of wonambi.attr.Surf the surface of only one hemisphere. xyz : numpy.ndarray nChan x 3 matrix, with the locations in x, y, z. std : float distance in mm of the Gaussian kernel exponent : int inverse law (1-> direct inverse, 2-> inverse square, 3-> inverse cube) threshold : float distance in mm for a vertex to pick up electrode activity (if distance is above the threshold, one electrode does not affect a vertex). Returns ------- numpy.ndarray nVertices X xyz.shape[0] matrix Notes ----- This function is a helper when plotting onto brain surface, by creating a transformation matrix from the values in space (f.e. at each electrode) to the position of the vertices (used to show the brain surface). There are many ways to move from values to vertices. The crucial parameter is the function at which activity decreases in respect to the distance. You can have an inverse relationship by specifying 'exponent'. If 'exponent' is 2, then the activity will decrease as inverse square of the distance. The function can be a Gaussian. With std, you specify the width of the gaussian kernel in mm. For each vertex, it uses a threshold based on the distance ('threshold' value, in mm). Finally, it normalizes the contribution of all the channels to 1, so that the sum of the coefficients for each vertex is 1. You can also create your own matrix (and skip calc_xyz2surf altogether) and pass it as attribute to the main figure. Because it's a loop over all the vertices, this function is pretty slow, but if you calculate it once, you can reuse it. We take advantage of multiprocessing, which speeds it up considerably. """ 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
python
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
[ "def", "calc_xyz2surf", "(", "surf", ",", "xyz", ",", "threshold", "=", "20", ",", "exponent", "=", "None", ",", "std", "=", "None", ")", ":", "if", "exponent", "is", "None", "and", "std", "is", "None", ":", "exponent", "=", "1", "if", "exponent", ...
Calculate transformation matrix from xyz values to vertices. Parameters ---------- surf : instance of wonambi.attr.Surf the surface of only one hemisphere. xyz : numpy.ndarray nChan x 3 matrix, with the locations in x, y, z. std : float distance in mm of the Gaussian kernel exponent : int inverse law (1-> direct inverse, 2-> inverse square, 3-> inverse cube) threshold : float distance in mm for a vertex to pick up electrode activity (if distance is above the threshold, one electrode does not affect a vertex). Returns ------- numpy.ndarray nVertices X xyz.shape[0] matrix Notes ----- This function is a helper when plotting onto brain surface, by creating a transformation matrix from the values in space (f.e. at each electrode) to the position of the vertices (used to show the brain surface). There are many ways to move from values to vertices. The crucial parameter is the function at which activity decreases in respect to the distance. You can have an inverse relationship by specifying 'exponent'. If 'exponent' is 2, then the activity will decrease as inverse square of the distance. The function can be a Gaussian. With std, you specify the width of the gaussian kernel in mm. For each vertex, it uses a threshold based on the distance ('threshold' value, in mm). Finally, it normalizes the contribution of all the channels to 1, so that the sum of the coefficients for each vertex is 1. You can also create your own matrix (and skip calc_xyz2surf altogether) and pass it as attribute to the main figure. Because it's a loop over all the vertices, this function is pretty slow, but if you calculate it once, you can reuse it. We take advantage of multiprocessing, which speeds it up considerably.
[ "Calculate", "transformation", "matrix", "from", "xyz", "values", "to", "vertices", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/source/linear.py#L57-L136
25,106
wonambi-python/wonambi
wonambi/source/linear.py
calc_one_vert_inverse
def calc_one_vert_inverse(one_vert, xyz=None, exponent=None): """Calculate how many electrodes influence one vertex, using the inverse function. Parameters ---------- one_vert : ndarray vector of xyz position of a vertex xyz : ndarray nChan X 3 with the position of all the channels exponent : int inverse law (1-> direct inverse, 2-> inverse square, 3-> inverse cube) Returns ------- ndarray one vector with values for one vertex """ trans = empty(xyz.shape[0]) for i, one_xyz in enumerate(xyz): trans[i] = 1 / (norm(one_vert - one_xyz) ** exponent) return trans
python
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
[ "def", "calc_one_vert_inverse", "(", "one_vert", ",", "xyz", "=", "None", ",", "exponent", "=", "None", ")", ":", "trans", "=", "empty", "(", "xyz", ".", "shape", "[", "0", "]", ")", "for", "i", ",", "one_xyz", "in", "enumerate", "(", "xyz", ")", "...
Calculate how many electrodes influence one vertex, using the inverse function. Parameters ---------- one_vert : ndarray vector of xyz position of a vertex xyz : ndarray nChan X 3 with the position of all the channels exponent : int inverse law (1-> direct inverse, 2-> inverse square, 3-> inverse cube) Returns ------- ndarray one vector with values for one vertex
[ "Calculate", "how", "many", "electrodes", "influence", "one", "vertex", "using", "the", "inverse", "function", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/source/linear.py#L139-L160
25,107
wonambi-python/wonambi
wonambi/source/linear.py
calc_one_vert_gauss
def calc_one_vert_gauss(one_vert, xyz=None, std=None): """Calculate how many electrodes influence one vertex, using a Gaussian function. Parameters ---------- one_vert : ndarray vector of xyz position of a vertex xyz : ndarray nChan X 3 with the position of all the channels std : float distance in mm of the Gaussian kernel Returns ------- ndarray one vector with values for one vertex """ trans = empty(xyz.shape[0]) for i, one_xyz in enumerate(xyz): trans[i] = gauss(norm(one_vert - one_xyz), std) return trans
python
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
[ "def", "calc_one_vert_gauss", "(", "one_vert", ",", "xyz", "=", "None", ",", "std", "=", "None", ")", ":", "trans", "=", "empty", "(", "xyz", ".", "shape", "[", "0", "]", ")", "for", "i", ",", "one_xyz", "in", "enumerate", "(", "xyz", ")", ":", "...
Calculate how many electrodes influence one vertex, using a Gaussian function. Parameters ---------- one_vert : ndarray vector of xyz position of a vertex xyz : ndarray nChan X 3 with the position of all the channels std : float distance in mm of the Gaussian kernel Returns ------- ndarray one vector with values for one vertex
[ "Calculate", "how", "many", "electrodes", "influence", "one", "vertex", "using", "a", "Gaussian", "function", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/source/linear.py#L163-L184
25,108
wonambi-python/wonambi
wonambi/ioeeg/micromed.py
_read_history
def _read_history(f, zone): """This matches the Matlab reader from Matlab Exchange but doesn't seem correct. """ 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
python
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
[ "def", "_read_history", "(", "f", ",", "zone", ")", ":", "pos", ",", "length", "=", "zone", "f", ".", "seek", "(", "pos", ",", "SEEK_SET", ")", "histories", "=", "[", "]", "while", "f", ".", "tell", "(", ")", "<", "(", "pos", "+", "length", ")"...
This matches the Matlab reader from Matlab Exchange but doesn't seem correct.
[ "This", "matches", "the", "Matlab", "reader", "from", "Matlab", "Exchange", "but", "doesn", "t", "seem", "correct", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/micromed.py#L458-L486
25,109
wonambi-python/wonambi
wonambi/widgets/video.py
Video.create_video
def create_video(self): """Create video widget.""" 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)
python
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)
[ "def", "create_video", "(", "self", ")", ":", "self", ".", "instance", "=", "vlc", ".", "Instance", "(", ")", "video_widget", "=", "QFrame", "(", ")", "self", ".", "mediaplayer", "=", "self", ".", "instance", ".", "media_player_new", "(", ")", "if", "s...
Create video widget.
[ "Create", "video", "widget", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/video.py#L74-L104
25,110
wonambi-python/wonambi
wonambi/widgets/video.py
Video.stop_video
def stop_video(self, tick): """Stop video if tick is more than the end, only for last file. Parameters ---------- tick : int time in ms from the beginning of the file useless? """ if self.cnt_video == self.n_video: if tick >= self.end_diff: self.idx_button.setText('Start') self.video.stop()
python
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()
[ "def", "stop_video", "(", "self", ",", "tick", ")", ":", "if", "self", ".", "cnt_video", "==", "self", ".", "n_video", ":", "if", "tick", ">=", "self", ".", "end_diff", ":", "self", ".", "idx_button", ".", "setText", "(", "'Start'", ")", "self", ".",...
Stop video if tick is more than the end, only for last file. Parameters ---------- tick : int time in ms from the beginning of the file useless?
[ "Stop", "video", "if", "tick", "is", "more", "than", "the", "end", "only", "for", "last", "file", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/video.py#L106-L119
25,111
wonambi-python/wonambi
wonambi/widgets/video.py
Video.next_video
def next_video(self, _): """Also runs when file is loaded, so index starts at 2.""" self.cnt_video += 1 lg.info('Update video to ' + str(self.cnt_video))
python
def next_video(self, _): self.cnt_video += 1 lg.info('Update video to ' + str(self.cnt_video))
[ "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.
[ "Also", "runs", "when", "file", "is", "loaded", "so", "index", "starts", "at", "2", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/video.py#L128-L131
25,112
wonambi-python/wonambi
wonambi/widgets/video.py
Video.start_stop_video
def start_stop_video(self): """Start and stop the video, and change the button. """ 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()
python
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()
[ "def", "start_stop_video", "(", "self", ")", ":", "if", "self", ".", "parent", ".", "info", ".", "dataset", "is", "None", ":", "self", ".", "parent", ".", "statusBar", "(", ")", ".", "showMessage", "(", "'No Dataset Loaded'", ")", "return", "# & is added a...
Start and stop the video, and change the button.
[ "Start", "and", "stop", "the", "video", "and", "change", "the", "button", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/video.py#L133-L158
25,113
wonambi-python/wonambi
wonambi/widgets/video.py
Video.update_video
def update_video(self): """Read list of files, convert to video time, and add video to queue. """ 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))
python
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))
[ "def", "update_video", "(", "self", ")", ":", "window_start", "=", "self", ".", "parent", ".", "value", "(", "'window_start'", ")", "window_length", "=", "self", ".", "parent", ".", "value", "(", "'window_length'", ")", "d", "=", "self", ".", "parent", "...
Read list of files, convert to video time, and add video to queue.
[ "Read", "list", "of", "files", "convert", "to", "video", "time", "and", "add", "video", "to", "queue", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/video.py#L160-L184
25,114
wonambi-python/wonambi
wonambi/trans/montage.py
montage
def montage(data, ref_chan=None, ref_to_avg=False, bipolar=None, method='average'): """Apply linear transformation to the channels. Parameters ---------- data : instance of DataRaw the data to filter ref_chan : list of str list of channels used as reference ref_to_avg : bool if re-reference to average or not bipolar : float distance in mm to consider two channels as neighbors and then compute the bipolar montage between them. method : str 'average' or 'regression'. 'average' takes the average across the channels selected as reference (it can be all) and subtract it from each channel. 'regression' keeps the residuals after regressing out the mean across channels. Returns ------- filtered_data : instance of DataRaw filtered data Notes ----- If you don't change anything, it returns the same instance of data. """ 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
python
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
[ "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", ...
Apply linear transformation to the channels. Parameters ---------- data : instance of DataRaw the data to filter ref_chan : list of str list of channels used as reference ref_to_avg : bool if re-reference to average or not bipolar : float distance in mm to consider two channels as neighbors and then compute the bipolar montage between them. method : str 'average' or 'regression'. 'average' takes the average across the channels selected as reference (it can be all) and subtract it from each channel. 'regression' keeps the residuals after regressing out the mean across channels. Returns ------- filtered_data : instance of DataRaw filtered data Notes ----- If you don't change anything, it returns the same instance of data.
[ "Apply", "linear", "transformation", "to", "the", "channels", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/montage.py#L18-L99
25,115
wonambi-python/wonambi
wonambi/trans/montage.py
_assert_equal_channels
def _assert_equal_channels(axis): """check that all the trials have the same channels, in the same order. Parameters ---------- axis : ndarray of ndarray one of the data axis Raises ------ """ 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.')
python
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.')
[ "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 s...
check that all the trials have the same channels, in the same order. Parameters ---------- axis : ndarray of ndarray one of the data axis Raises ------
[ "check", "that", "all", "the", "trials", "have", "the", "same", "channels", "in", "the", "same", "order", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/montage.py#L102-L118
25,116
wonambi-python/wonambi
wonambi/trans/montage.py
compute_average_regress
def compute_average_regress(x, idx_chan): """Take the mean across channels and regress out the mean from each channel Parameters ---------- x : ndarray 2d array with channels on one dimension idx_chan: which axis contains channels Returns ------- ndarray same as x, but with the mean being regressed out """ 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)
python
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)
[ "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", ...
Take the mean across channels and regress out the mean from each channel Parameters ---------- x : ndarray 2d array with channels on one dimension idx_chan: which axis contains channels Returns ------- ndarray same as x, but with the mean being regressed out
[ "Take", "the", "mean", "across", "channels", "and", "regress", "out", "the", "mean", "from", "each", "channel" ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/montage.py#L155-L182
25,117
wonambi-python/wonambi
wonambi/widgets/utils.py
keep_recent_datasets
def keep_recent_datasets(max_dataset_history, info=None): """Keep track of the most recent recordings. Parameters ---------- max_dataset_history : int maximum number of datasets to remember info : str, optional TODO path to file Returns ------- list of str paths to most recent datasets (only if you don't specify new_dataset) """ 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
python
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
[ "def", "keep_recent_datasets", "(", "max_dataset_history", ",", "info", "=", "None", ")", ":", "history", "=", "settings", ".", "value", "(", "'recent_recordings'", ",", "[", "]", ")", "if", "isinstance", "(", "history", ",", "str", ")", ":", "history", "=...
Keep track of the most recent recordings. Parameters ---------- max_dataset_history : int maximum number of datasets to remember info : str, optional TODO path to file Returns ------- list of str paths to most recent datasets (only if you don't specify new_dataset)
[ "Keep", "track", "of", "the", "most", "recent", "recordings", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/utils.py#L687-L723
25,118
wonambi-python/wonambi
wonambi/widgets/utils.py
choose_file_or_dir
def choose_file_or_dir(): """Create a simple message box to see if the user wants to open dir or file Returns ------- str 'dir' or 'file' or 'abort' """ 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'
python
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'
[ "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'", ",...
Create a simple message box to see if the user wants to open dir or file Returns ------- str 'dir' or 'file' or 'abort'
[ "Create", "a", "simple", "message", "box", "to", "see", "if", "the", "user", "wants", "to", "open", "dir", "or", "file" ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/utils.py#L726-L748
25,119
wonambi-python/wonambi
wonambi/widgets/utils.py
convert_name_to_color
def convert_name_to_color(s): """Convert any string to an RGB color. Parameters ---------- s : str string to convert selection : bool, optional if an event is being selected, it's lighter Returns ------- instance of QColor one of the possible color Notes ----- It takes any string and converts it to RGB color. The same string always returns the same color. The numbers are a bit arbitrary but not completely. h is the baseline color (keep it high to have brighter colors). Make sure that the max module + h is less than 256 (RGB limit). The number you multiply ord for is necessary to differentiate the letters (otherwise 'r' and 's' are too close to each other). """ 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
python
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
[ "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", "(",...
Convert any string to an RGB color. Parameters ---------- s : str string to convert selection : bool, optional if an event is being selected, it's lighter Returns ------- instance of QColor one of the possible color Notes ----- It takes any string and converts it to RGB color. The same string always returns the same color. The numbers are a bit arbitrary but not completely. h is the baseline color (keep it high to have brighter colors). Make sure that the max module + h is less than 256 (RGB limit). The number you multiply ord for is necessary to differentiate the letters (otherwise 'r' and 's' are too close to each other).
[ "Convert", "any", "string", "to", "an", "RGB", "color", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/utils.py#L760-L790
25,120
wonambi-python/wonambi
wonambi/widgets/utils.py
freq_from_str
def freq_from_str(freq_str): """Obtain frequency ranges from input string, either as list or dynamic notation. Parameters ---------- freq_str : str String with frequency ranges, either as a list: e.g. [[1-3], [3-5], [5-8]]; or with a dynamic definition: (start, stop, width, step). Returns ------- list of tuple of float or None Every tuple of float represents a frequency band. If input is invalid, returns None. """ 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
python
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
[ "def", "freq_from_str", "(", "freq_str", ")", ":", "freq", "=", "[", "]", "as_list", "=", "freq_str", "[", "1", ":", "-", "1", "]", ".", "replace", "(", "' '", ",", "''", ")", ".", "split", "(", "','", ")", "try", ":", "if", "freq_str", "[", "0...
Obtain frequency ranges from input string, either as list or dynamic notation. Parameters ---------- freq_str : str String with frequency ranges, either as a list: e.g. [[1-3], [3-5], [5-8]]; or with a dynamic definition: (start, stop, width, step). Returns ------- list of tuple of float or None Every tuple of float represents a frequency band. If input is invalid, returns None.
[ "Obtain", "frequency", "ranges", "from", "input", "string", "either", "as", "list", "or", "dynamic", "notation", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/utils.py#L793-L838
25,121
wonambi-python/wonambi
wonambi/widgets/utils.py
export_graphics_to_svg
def export_graphics_to_svg(widget, filename): """Export graphics to svg Parameters ---------- widget : instance of QGraphicsView traces or overview filename : str path to save svg """ generator = QSvgGenerator() generator.setFileName(filename) generator.setSize(widget.size()) generator.setViewBox(widget.rect()) painter = QPainter() painter.begin(generator) widget.render(painter) painter.end()
python
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()
[ "def", "export_graphics_to_svg", "(", "widget", ",", "filename", ")", ":", "generator", "=", "QSvgGenerator", "(", ")", "generator", ".", "setFileName", "(", "filename", ")", "generator", ".", "setSize", "(", "widget", ".", "size", "(", ")", ")", "generator"...
Export graphics to svg Parameters ---------- widget : instance of QGraphicsView traces or overview filename : str path to save svg
[ "Export", "graphics", "to", "svg" ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/utils.py#L869-L887
25,122
wonambi-python/wonambi
wonambi/widgets/utils.py
FormList.get_value
def get_value(self, default=None): """Get int from widget. Parameters ---------- default : list list with widgets Returns ------- list list that might contain int or str or float etc """ 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
python
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
[ "def", "get_value", "(", "self", ",", "default", "=", "None", ")", ":", "if", "default", "is", "None", ":", "default", "=", "[", "]", "try", ":", "text", "=", "literal_eval", "(", "self", ".", "text", "(", ")", ")", "if", "not", "isinstance", "(", ...
Get int from widget. Parameters ---------- default : list list with widgets Returns ------- list list that might contain int or str or float etc
[ "Get", "int", "from", "widget", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/utils.py#L390-L419
25,123
wonambi-python/wonambi
wonambi/widgets/utils.py
FormDir.connect
def connect(self, funct): """Call funct when the text was changed. Parameters ---------- funct : function function that broadcasts a change. Notes ----- There is something wrong here. When you run this function, it calls for opening a directory three or four times. This is obviously wrong but I don't understand why this happens three times. Traceback did not help. """ def get_directory(): rec = QFileDialog.getExistingDirectory(self, 'Path to Recording' ' Directory') if rec == '': return self.setText(rec) funct() self.clicked.connect(get_directory)
python
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)
[ "def", "connect", "(", "self", ",", "funct", ")", ":", "def", "get_directory", "(", ")", ":", "rec", "=", "QFileDialog", ".", "getExistingDirectory", "(", "self", ",", "'Path to Recording'", "' Directory'", ")", "if", "rec", "==", "''", ":", "return", "sel...
Call funct when the text was changed. Parameters ---------- funct : function function that broadcasts a change. Notes ----- There is something wrong here. When you run this function, it calls for opening a directory three or four times. This is obviously wrong but I don't understand why this happens three times. Traceback did not help.
[ "Call", "funct", "when", "the", "text", "was", "changed", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/utils.py#L528-L554
25,124
wonambi-python/wonambi
wonambi/widgets/utils.py
FormMenu.get_value
def get_value(self, default=None): """Get selection from widget. Parameters ---------- default : str str for use by widget Returns ------- str selected item from the combobox """ 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
python
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
[ "def", "get_value", "(", "self", ",", "default", "=", "None", ")", ":", "if", "default", "is", "None", ":", "default", "=", "''", "try", ":", "text", "=", "self", ".", "currentText", "(", ")", "except", "ValueError", ":", "lg", ".", "debug", "(", "...
Get selection from widget. Parameters ---------- default : str str for use by widget Returns ------- str selected item from the combobox
[ "Get", "selection", "from", "widget", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/utils.py#L572-L598
25,125
wonambi-python/wonambi
wonambi/ioeeg/bids.py
_write_ieeg_json
def _write_ieeg_json(output_file): """Use only required fields """ dataset_info = { "TaskName": "unknown", "Manufacturer": "n/a", "PowerLineFrequency": 50, "iEEGReference": "n/a", } with output_file.open('w') as f: dump(dataset_info, f, indent=' ')
python
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=' ')
[ "def", "_write_ieeg_json", "(", "output_file", ")", ":", "dataset_info", "=", "{", "\"TaskName\"", ":", "\"unknown\"", ",", "\"Manufacturer\"", ":", "\"n/a\"", ",", "\"PowerLineFrequency\"", ":", "50", ",", "\"iEEGReference\"", ":", "\"n/a\"", ",", "}", "with", ...
Use only required fields
[ "Use", "only", "required", "fields" ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/bids.py#L115-L126
25,126
wonambi-python/wonambi
wonambi/scroll_data.py
MainWindow.value
def value(self, parameter, new_value=None): """This function is a shortcut for any parameter. Instead of calling the widget, its config and its values, you can call directly the parameter. Parameters ---------- parameter : str name of the parameter of interest new_value : str or float, optional new value for the parameter Returns ------- str or float if you didn't specify new_value, it returns the current value. Notes ----- It's important to maintain an organized dict in DEFAULTS which has to correspond to the values in the widgets, also the name of the widget. DEFAULTS is used like a look-up table. """ 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
python
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
[ "def", "value", "(", "self", ",", "parameter", ",", "new_value", "=", "None", ")", ":", "for", "widget_name", ",", "values", "in", "DEFAULTS", ".", "items", "(", ")", ":", "if", "parameter", "in", "values", ".", "keys", "(", ")", ":", "widget", "=", ...
This function is a shortcut for any parameter. Instead of calling the widget, its config and its values, you can call directly the parameter. Parameters ---------- parameter : str name of the parameter of interest new_value : str or float, optional new value for the parameter Returns ------- str or float if you didn't specify new_value, it returns the current value. Notes ----- It's important to maintain an organized dict in DEFAULTS which has to correspond to the values in the widgets, also the name of the widget. DEFAULTS is used like a look-up table.
[ "This", "function", "is", "a", "shortcut", "for", "any", "parameter", ".", "Instead", "of", "calling", "the", "widget", "its", "config", "and", "its", "values", "you", "can", "call", "directly", "the", "parameter", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/scroll_data.py#L88-L119
25,127
wonambi-python/wonambi
wonambi/scroll_data.py
MainWindow.update
def update(self): """Once you open a dataset, it activates all the widgets. """ 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()
python
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()
[ "def", "update", "(", "self", ")", ":", "self", ".", "info", ".", "display_dataset", "(", ")", "self", ".", "overview", ".", "update", "(", ")", "self", ".", "labels", ".", "update", "(", "labels", "=", "self", ".", "info", ".", "dataset", ".", "he...
Once you open a dataset, it activates all the widgets.
[ "Once", "you", "open", "a", "dataset", "it", "activates", "all", "the", "widgets", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/scroll_data.py#L121-L134
25,128
wonambi-python/wonambi
wonambi/scroll_data.py
MainWindow.reset
def reset(self): """Remove all the information from previous dataset before loading a new dataset. """ # 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()
python
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()
[ "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",...
Remove all the information from previous dataset before loading a new dataset.
[ "Remove", "all", "the", "information", "from", "previous", "dataset", "before", "loading", "a", "new", "dataset", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/scroll_data.py#L136-L152
25,129
wonambi-python/wonambi
wonambi/scroll_data.py
MainWindow.show_settings
def show_settings(self): """Open the Setting windows, after updating the values in GUI. """ 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()
python
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()
[ "def", "show_settings", "(", "self", ")", ":", "self", ".", "notes", ".", "config", ".", "put_values", "(", ")", "self", ".", "overview", ".", "config", ".", "put_values", "(", ")", "self", ".", "settings", ".", "config", ".", "put_values", "(", ")", ...
Open the Setting windows, after updating the values in GUI.
[ "Open", "the", "Setting", "windows", "after", "updating", "the", "values", "in", "GUI", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/scroll_data.py#L154-L163
25,130
wonambi-python/wonambi
wonambi/scroll_data.py
MainWindow.show_spindle_dialog
def show_spindle_dialog(self): """Create the spindle detection dialog.""" self.spindle_dialog.update_groups() self.spindle_dialog.update_cycles() self.spindle_dialog.show()
python
def show_spindle_dialog(self): self.spindle_dialog.update_groups() self.spindle_dialog.update_cycles() self.spindle_dialog.show()
[ "def", "show_spindle_dialog", "(", "self", ")", ":", "self", ".", "spindle_dialog", ".", "update_groups", "(", ")", "self", ".", "spindle_dialog", ".", "update_cycles", "(", ")", "self", ".", "spindle_dialog", ".", "show", "(", ")" ]
Create the spindle detection dialog.
[ "Create", "the", "spindle", "detection", "dialog", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/scroll_data.py#L180-L184
25,131
wonambi-python/wonambi
wonambi/scroll_data.py
MainWindow.show_slow_wave_dialog
def show_slow_wave_dialog(self): """Create the SW detection dialog.""" self.slow_wave_dialog.update_groups() self.slow_wave_dialog.update_cycles() self.slow_wave_dialog.show()
python
def show_slow_wave_dialog(self): self.slow_wave_dialog.update_groups() self.slow_wave_dialog.update_cycles() self.slow_wave_dialog.show()
[ "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.
[ "Create", "the", "SW", "detection", "dialog", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/scroll_data.py#L186-L190
25,132
wonambi-python/wonambi
wonambi/scroll_data.py
MainWindow.show_event_analysis_dialog
def show_event_analysis_dialog(self): """Create the event analysis dialog.""" self.event_analysis_dialog.update_types() self.event_analysis_dialog.update_groups() self.event_analysis_dialog.update_cycles() self.event_analysis_dialog.show()
python
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()
[ "def", "show_event_analysis_dialog", "(", "self", ")", ":", "self", ".", "event_analysis_dialog", ".", "update_types", "(", ")", "self", ".", "event_analysis_dialog", ".", "update_groups", "(", ")", "self", ".", "event_analysis_dialog", ".", "update_cycles", "(", ...
Create the event analysis dialog.
[ "Create", "the", "event", "analysis", "dialog", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/scroll_data.py#L192-L197
25,133
wonambi-python/wonambi
wonambi/scroll_data.py
MainWindow.show_analysis_dialog
def show_analysis_dialog(self): """Create the analysis dialog.""" self.analysis_dialog.update_evt_types() self.analysis_dialog.update_groups() self.analysis_dialog.update_cycles() self.analysis_dialog.show()
python
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()
[ "def", "show_analysis_dialog", "(", "self", ")", ":", "self", ".", "analysis_dialog", ".", "update_evt_types", "(", ")", "self", ".", "analysis_dialog", ".", "update_groups", "(", ")", "self", ".", "analysis_dialog", ".", "update_cycles", "(", ")", "self", "."...
Create the analysis dialog.
[ "Create", "the", "analysis", "dialog", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/scroll_data.py#L199-L204
25,134
wonambi-python/wonambi
wonambi/scroll_data.py
MainWindow.closeEvent
def closeEvent(self, event): """save the name of the last open dataset.""" 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()
python
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()
[ "def", "closeEvent", "(", "self", ",", "event", ")", ":", "max_dataset_history", "=", "self", ".", "value", "(", "'max_dataset_history'", ")", "keep_recent_datasets", "(", "max_dataset_history", ",", "self", ".", "info", ")", "settings", ".", "setValue", "(", ...
save the name of the last open dataset.
[ "save", "the", "name", "of", "the", "last", "open", "dataset", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/scroll_data.py#L243-L251
25,135
wonambi-python/wonambi
wonambi/ioeeg/bci2000.py
_read_header
def _read_header(filename): """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. """ 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
python
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
[ "def", "_read_header", "(", "filename", ")", ":", "header", "=", "_read_header_text", "(", "filename", ")", "first_row", "=", "header", "[", "0", "]", "EXTRA_ROWS", "=", "3", "# drop DefaultValue1 LowRange1 HighRange1", "hdr", "=", "{", "}", "for", "group", "i...
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.
[ "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", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/bci2000.py#L212-L260
25,136
wonambi-python/wonambi
wonambi/trans/reject.py
remove_artf_evts
def remove_artf_evts(times, annot, chan=None, min_dur=0.1): """Correct times to remove events marked 'Artefact'. Parameters ---------- times : list of tuple of float the start and end times of each segment annot : instance of Annotations the annotation file containing events and epochs chan : str, optional full name of channel on which artefacts were marked. Channel format is 'chan_name (group_name)'. If None, artefacts from any channel will be removed. min_dur : float resulting segments, after concatenation, are rejected if shorter than this duration Returns ------- list of tuple of float the new start and end times of each segment, with artefact periods taken out """ 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
python
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
[ "def", "remove_artf_evts", "(", "times", ",", "annot", ",", "chan", "=", "None", ",", "min_dur", "=", "0.1", ")", ":", "new_times", "=", "times", "beg", "=", "times", "[", "0", "]", "[", "0", "]", "end", "=", "times", "[", "-", "1", "]", "[", "...
Correct times to remove events marked 'Artefact'. Parameters ---------- times : list of tuple of float the start and end times of each segment annot : instance of Annotations the annotation file containing events and epochs chan : str, optional full name of channel on which artefacts were marked. Channel format is 'chan_name (group_name)'. If None, artefacts from any channel will be removed. min_dur : float resulting segments, after concatenation, are rejected if shorter than this duration Returns ------- list of tuple of float the new start and end times of each segment, with artefact periods taken out
[ "Correct", "times", "to", "remove", "events", "marked", "Artefact", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/reject.py#L13-L83
25,137
SuLab/WikidataIntegrator
wikidataintegrator/wdi_core.py
WDBaseDataType.statement_ref_mode
def statement_ref_mode(self, value): """Set the reference mode for a statement, always overrides the global reference state.""" 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
python
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
[ "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...
Set the reference mode for a statement, always overrides the global reference state.
[ "Set", "the", "reference", "mode", "for", "a", "statement", "always", "overrides", "the", "global", "reference", "state", "." ]
8ceb2ed1c08fec070ec9edfcf7db7b8691481b62
https://github.com/SuLab/WikidataIntegrator/blob/8ceb2ed1c08fec070ec9edfcf7db7b8691481b62/wikidataintegrator/wdi_core.py#L1641-L1647
25,138
SuLab/WikidataIntegrator
wikidataintegrator/wdi_core.py
WDBaseDataType.equals
def equals(self, that, include_ref=False, fref=None): """ 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 """ 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)
python
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)
[ "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", "==...
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
[ "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", ".", ...
8ceb2ed1c08fec070ec9edfcf7db7b8691481b62
https://github.com/SuLab/WikidataIntegrator/blob/8ceb2ed1c08fec070ec9edfcf7db7b8691481b62/wikidataintegrator/wdi_core.py#L1798-L1814
25,139
SuLab/WikidataIntegrator
wikidataintegrator/wdi_core.py
WDBaseDataType.refs_equal
def refs_equal(olditem, newitem): """ tests for exactly identical references """ 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
python
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
[ "def", "refs_equal", "(", "olditem", ",", "newitem", ")", ":", "oldrefs", "=", "olditem", ".", "references", "newrefs", "=", "newitem", ".", "references", "ref_equal", "=", "lambda", "oldref", ",", "newref", ":", "True", "if", "(", "len", "(", "oldref", ...
tests for exactly identical references
[ "tests", "for", "exactly", "identical", "references" ]
8ceb2ed1c08fec070ec9edfcf7db7b8691481b62
https://github.com/SuLab/WikidataIntegrator/blob/8ceb2ed1c08fec070ec9edfcf7db7b8691481b62/wikidataintegrator/wdi_core.py#L1817-L1830
25,140
SuLab/WikidataIntegrator
wikidataintegrator/wdi_helpers/__init__.py
try_write
def try_write(wd_item, record_id, record_prop, login, edit_summary='', write=True): """ Write a PBB_core item. Log if item was created, updated, or skipped. Catch and log all errors. :param wd_item: A wikidata item that will be written :type wd_item: PBB_Core.WDItemEngine :param record_id: An external identifier, to be used for logging :type record_id: str :param record_prop: Property of the external identifier :type record_prop: str :param login: PBB_core login instance :type login: PBB_login.WDLogin :param edit_summary: passed directly to wd_item.write :type edit_summary: str :param write: If `False`, do not actually perform write. Action will be logged as if write had occured :type write: bool :return: True if write did not throw an exception, returns the exception otherwise """ 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
python
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
[ "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", ...
Write a PBB_core item. Log if item was created, updated, or skipped. Catch and log all errors. :param wd_item: A wikidata item that will be written :type wd_item: PBB_Core.WDItemEngine :param record_id: An external identifier, to be used for logging :type record_id: str :param record_prop: Property of the external identifier :type record_prop: str :param login: PBB_core login instance :type login: PBB_login.WDLogin :param edit_summary: passed directly to wd_item.write :type edit_summary: str :param write: If `False`, do not actually perform write. Action will be logged as if write had occured :type write: bool :return: True if write did not throw an exception, returns the exception otherwise
[ "Write", "a", "PBB_core", "item", ".", "Log", "if", "item", "was", "created", "updated", "or", "skipped", ".", "Catch", "and", "log", "all", "errors", "." ]
8ceb2ed1c08fec070ec9edfcf7db7b8691481b62
https://github.com/SuLab/WikidataIntegrator/blob/8ceb2ed1c08fec070ec9edfcf7db7b8691481b62/wikidataintegrator/wdi_helpers/__init__.py#L58-L101
25,141
maykinmedia/django-admin-index
django_admin_index/compat/django18.py
_build_app_dict
def _build_app_dict(site, request, label=None): """ Builds the app dictionary. Takes an optional label parameters to filter models of a specific app. """ 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
python
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
[ "def", "_build_app_dict", "(", "site", ",", "request", ",", "label", "=", "None", ")", ":", "app_dict", "=", "{", "}", "if", "label", ":", "models", "=", "{", "m", ":", "m_a", "for", "m", ",", "m_a", "in", "site", ".", "_registry", ".", "items", ...
Builds the app dictionary. Takes an optional label parameters to filter models of a specific app.
[ "Builds", "the", "app", "dictionary", ".", "Takes", "an", "optional", "label", "parameters", "to", "filter", "models", "of", "a", "specific", "app", "." ]
5bfd90e6945775865d722e0f5058824769f68f04
https://github.com/maykinmedia/django-admin-index/blob/5bfd90e6945775865d722e0f5058824769f68f04/django_admin_index/compat/django18.py#L13-L76
25,142
maykinmedia/django-admin-index
django_admin_index/compat/django18.py
get_app_list
def get_app_list(site, request): """ Returns a sorted list of all the installed apps that have been registered in this site. """ 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
python
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
[ "def", "get_app_list", "(", "site", ",", "request", ")", ":", "app_dict", "=", "_build_app_dict", "(", "site", ",", "request", ")", "# Sort the apps alphabetically.", "app_list", "=", "sorted", "(", "app_dict", ".", "values", "(", ")", ",", "key", "=", "lamb...
Returns a sorted list of all the installed apps that have been registered in this site.
[ "Returns", "a", "sorted", "list", "of", "all", "the", "installed", "apps", "that", "have", "been", "registered", "in", "this", "site", "." ]
5bfd90e6945775865d722e0f5058824769f68f04
https://github.com/maykinmedia/django-admin-index/blob/5bfd90e6945775865d722e0f5058824769f68f04/django_admin_index/compat/django18.py#L79-L93
25,143
SuLab/WikidataIntegrator
wikidataintegrator/wdi_fastrun.py
FastRunContainer.format_query_results
def format_query_results(self, r, prop_nr): """ `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 `r` is a list of dicts. The keys are: item: the subject. the item this statement is on v: the object. The value for this statement sid: statement ID pq: qualifier property qval: qualifier value ref: reference ID pr: reference property rval: reference value """ 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']
python
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']
[ "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'", ",", "'...
`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 `r` is a list of dicts. The keys are: item: the subject. the item this statement is on v: the object. The value for this statement sid: statement ID pq: qualifier property qval: qualifier value ref: reference ID pr: reference property rval: reference 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" ]
8ceb2ed1c08fec070ec9edfcf7db7b8691481b62
https://github.com/SuLab/WikidataIntegrator/blob/8ceb2ed1c08fec070ec9edfcf7db7b8691481b62/wikidataintegrator/wdi_fastrun.py#L299-L358
25,144
SuLab/WikidataIntegrator
wikidataintegrator/wdi_fastrun.py
FastRunContainer.clear
def clear(self): """ convinience function to empty this fastrun container """ self.prop_dt_map = dict() self.prop_data = dict() self.rev_lookup = defaultdict(set)
python
def clear(self): self.prop_dt_map = dict() self.prop_data = dict() self.rev_lookup = defaultdict(set)
[ "def", "clear", "(", "self", ")", ":", "self", ".", "prop_dt_map", "=", "dict", "(", ")", "self", ".", "prop_data", "=", "dict", "(", ")", "self", ".", "rev_lookup", "=", "defaultdict", "(", "set", ")" ]
convinience function to empty this fastrun container
[ "convinience", "function", "to", "empty", "this", "fastrun", "container" ]
8ceb2ed1c08fec070ec9edfcf7db7b8691481b62
https://github.com/SuLab/WikidataIntegrator/blob/8ceb2ed1c08fec070ec9edfcf7db7b8691481b62/wikidataintegrator/wdi_fastrun.py#L504-L510
25,145
sighingnow/parsec.py
src/parsec/__init__.py
times
def times(p, mint, maxt=None): '''Repeat a parser between `mint` and `maxt` times. DO AS MUCH MATCH AS IT CAN. Return a list of values.''' 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
python
def times(p, mint, maxt=None): '''Repeat a parser between `mint` and `maxt` times. DO AS MUCH MATCH AS IT CAN. Return a list of values.''' 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
[ "def", "times", "(", "p", ",", "mint", ",", "maxt", "=", "None", ")", ":", "maxt", "=", "maxt", "if", "maxt", "else", "mint", "@", "Parser", "def", "times_parser", "(", "text", ",", "index", ")", ":", "cnt", ",", "values", ",", "res", "=", "0", ...
Repeat a parser between `mint` and `maxt` times. DO AS MUCH MATCH AS IT CAN. Return a list of values.
[ "Repeat", "a", "parser", "between", "mint", "and", "maxt", "times", ".", "DO", "AS", "MUCH", "MATCH", "AS", "IT", "CAN", ".", "Return", "a", "list", "of", "values", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L405-L441
25,146
sighingnow/parsec.py
src/parsec/__init__.py
optional
def optional(p, default_value=None): '''`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. ''' @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
python
def optional(p, default_value=None): '''`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. ''' @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
[ "def", "optional", "(", "p", ",", "default_value", "=", "None", ")", ":", "@", "Parser", "def", "optional_parser", "(", "text", ",", "index", ")", ":", "res", "=", "p", "(", "text", ",", "index", ")", "if", "res", ".", "status", ":", "return", "Val...
`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.
[ "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",...
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L450-L463
25,147
sighingnow/parsec.py
src/parsec/__init__.py
separated
def separated(p, sep, mint, maxt=None, end=None): '''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`.''' 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
python
def separated(p, sep, mint, maxt=None, end=None): '''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`.''' 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
[ "def", "separated", "(", "p", ",", "sep", ",", "mint", ",", "maxt", "=", "None", ",", "end", "=", "None", ")", ":", "maxt", "=", "maxt", "if", "maxt", "else", "mint", "@", "Parser", "def", "sep_parser", "(", "text", ",", "index", ")", ":", "cnt",...
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`.
[ "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", "requ...
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L478-L522
25,148
sighingnow/parsec.py
src/parsec/__init__.py
one_of
def one_of(s): '''Parser a char from specified string.''' @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
python
def one_of(s): '''Parser a char from specified string.''' @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
[ "def", "one_of", "(", "s", ")", ":", "@", "Parser", "def", "one_of_parser", "(", "text", ",", "index", "=", "0", ")", ":", "if", "index", "<", "len", "(", "text", ")", "and", "text", "[", "index", "]", "in", "s", ":", "return", "Value", ".", "s...
Parser a char from specified string.
[ "Parser", "a", "char", "from", "specified", "string", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L567-L575
25,149
sighingnow/parsec.py
src/parsec/__init__.py
none_of
def none_of(s): '''Parser a char NOT from specified string.''' @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
python
def none_of(s): '''Parser a char NOT from specified string.''' @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
[ "def", "none_of", "(", "s", ")", ":", "@", "Parser", "def", "none_of_parser", "(", "text", ",", "index", "=", "0", ")", ":", "if", "index", "<", "len", "(", "text", ")", "and", "text", "[", "index", "]", "not", "in", "s", ":", "return", "Value", ...
Parser a char NOT from specified string.
[ "Parser", "a", "char", "NOT", "from", "specified", "string", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L578-L586
25,150
sighingnow/parsec.py
src/parsec/__init__.py
space
def space(): '''Parser a whitespace character.''' @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
python
def space(): '''Parser a whitespace character.''' @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
[ "def", "space", "(", ")", ":", "@", "Parser", "def", "space_parser", "(", "text", ",", "index", "=", "0", ")", ":", "if", "index", "<", "len", "(", "text", ")", "and", "text", "[", "index", "]", ".", "isspace", "(", ")", ":", "return", "Value", ...
Parser a whitespace character.
[ "Parser", "a", "whitespace", "character", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L589-L597
25,151
sighingnow/parsec.py
src/parsec/__init__.py
letter
def letter(): '''Parse a letter in alphabet.''' @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
python
def letter(): '''Parse a letter in alphabet.''' @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
[ "def", "letter", "(", ")", ":", "@", "Parser", "def", "letter_parser", "(", "text", ",", "index", "=", "0", ")", ":", "if", "index", "<", "len", "(", "text", ")", "and", "text", "[", "index", "]", ".", "isalpha", "(", ")", ":", "return", "Value",...
Parse a letter in alphabet.
[ "Parse", "a", "letter", "in", "alphabet", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L605-L613
25,152
sighingnow/parsec.py
src/parsec/__init__.py
digit
def digit(): '''Parse a digit character.''' @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
python
def digit(): '''Parse a digit character.''' @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
[ "def", "digit", "(", ")", ":", "@", "Parser", "def", "digit_parser", "(", "text", ",", "index", "=", "0", ")", ":", "if", "index", "<", "len", "(", "text", ")", "and", "text", "[", "index", "]", ".", "isdigit", "(", ")", ":", "return", "Value", ...
Parse a digit character.
[ "Parse", "a", "digit", "character", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L616-L624
25,153
sighingnow/parsec.py
src/parsec/__init__.py
eof
def eof(): '''Parser EOF flag of a string.''' @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
python
def eof(): '''Parser EOF flag of a string.''' @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
[ "def", "eof", "(", ")", ":", "@", "Parser", "def", "eof_parser", "(", "text", ",", "index", "=", "0", ")", ":", "if", "index", ">=", "len", "(", "text", ")", ":", "return", "Value", ".", "success", "(", "index", ",", "None", ")", "else", ":", "...
Parser EOF flag of a string.
[ "Parser", "EOF", "flag", "of", "a", "string", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L627-L635
25,154
sighingnow/parsec.py
src/parsec/__init__.py
string
def string(s): '''Parser a string.''' @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
python
def string(s): '''Parser a string.''' @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
[ "def", "string", "(", "s", ")", ":", "@", "Parser", "def", "string_parser", "(", "text", ",", "index", "=", "0", ")", ":", "slen", ",", "tlen", "=", "len", "(", "s", ")", ",", "len", "(", "text", ")", "if", "text", "[", "index", ":", "index", ...
Parser a string.
[ "Parser", "a", "string", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L638-L650
25,155
sighingnow/parsec.py
src/parsec/__init__.py
ParseError.loc_info
def loc_info(text, index): '''Location of `index` in source code `text`.''' 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)
python
def loc_info(text, index): '''Location of `index` in source code `text`.''' 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)
[ "def", "loc_info", "(", "text", ",", "index", ")", ":", "if", "index", ">", "len", "(", "text", ")", ":", "raise", "ValueError", "(", "'Invalid index.'", ")", "line", ",", "last_ln", "=", "text", ".", "count", "(", "'\\n'", ",", "0", ",", "index", ...
Location of `index` in source code `text`.
[ "Location", "of", "index", "in", "source", "code", "text", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L29-L35
25,156
sighingnow/parsec.py
src/parsec/__init__.py
ParseError.loc
def loc(self): '''Locate the error position in the source code text.''' try: return '{}:{}'.format(*ParseError.loc_info(self.text, self.index)) except ValueError: return '<out of bounds index {!r}>'.format(self.index)
python
def loc(self): '''Locate the error position in the source code text.''' try: return '{}:{}'.format(*ParseError.loc_info(self.text, self.index)) except ValueError: return '<out of bounds index {!r}>'.format(self.index)
[ "def", "loc", "(", "self", ")", ":", "try", ":", "return", "'{}:{}'", ".", "format", "(", "*", "ParseError", ".", "loc_info", "(", "self", ".", "text", ",", "self", ".", "index", ")", ")", "except", "ValueError", ":", "return", "'<out of bounds index {!r...
Locate the error position in the source code text.
[ "Locate", "the", "error", "position", "in", "the", "source", "code", "text", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L37-L42
25,157
sighingnow/parsec.py
src/parsec/__init__.py
Value.aggregate
def aggregate(self, other=None): '''collect the furthest failure from self and other.''' 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)
python
def aggregate(self, other=None): '''collect the furthest failure from self and other.''' 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)
[ "def", "aggregate", "(", "self", ",", "other", "=", "None", ")", ":", "if", "not", "self", ".", "status", ":", "return", "self", "if", "not", "other", ":", "return", "self", "if", "not", "other", ".", "status", ":", "return", "other", "return", "Valu...
collect the furthest failure from self and other.
[ "collect", "the", "furthest", "failure", "from", "self", "and", "other", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L64-L72
25,158
sighingnow/parsec.py
src/parsec/__init__.py
Value.combinate
def combinate(values): '''aggregate multiple values into tuple''' 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)
python
def combinate(values): '''aggregate multiple values into tuple''' 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)
[ "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", "(...
aggregate multiple values into tuple
[ "aggregate", "multiple", "values", "into", "tuple" ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L75-L85
25,159
sighingnow/parsec.py
src/parsec/__init__.py
Parser.parse_partial
def parse_partial(self, text): '''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. ''' 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)
python
def parse_partial(self, text): '''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. ''' 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)
[ "def", "parse_partial", "(", "self", ",", "text", ")", ":", "if", "not", "isinstance", "(", "text", ",", "str", ")", ":", "raise", "TypeError", "(", "'Can only parsing string but got {!r}'", ".", "format", "(", "text", ")", ")", "res", "=", "self", "(", ...
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.
[ "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", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L117-L128
25,160
sighingnow/parsec.py
src/parsec/__init__.py
Parser.bind
def bind(self, fn): '''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. ''' @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
python
def bind(self, fn): '''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. ''' @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
[ "def", "bind", "(", "self", ",", "fn", ")", ":", "@", "Parser", "def", "bind_parser", "(", "text", ",", "index", ")", ":", "res", "=", "self", "(", "text", ",", "index", ")", "return", "res", "if", "not", "res", ".", "status", "else", "fn", "(", ...
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.
[ "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", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L140-L149
25,161
sighingnow/parsec.py
src/parsec/__init__.py
Parser.parsecmap
def parsecmap(self, fn): '''Returns a parser that transforms the produced value of parser with `fn`.''' return self.bind(lambda res: Parser(lambda _, index: Value.success(index, fn(res))))
python
def parsecmap(self, fn): '''Returns a parser that transforms the produced value of parser with `fn`.''' return self.bind(lambda res: Parser(lambda _, index: Value.success(index, fn(res))))
[ "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`.
[ "Returns", "a", "parser", "that", "transforms", "the", "produced", "value", "of", "parser", "with", "fn", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L218-L220
25,162
sighingnow/parsec.py
src/parsec/__init__.py
Parser.parsecapp
def parsecapp(self, other): '''Returns a parser that applies the produced value of this parser to the produced value of `other`.''' # pylint: disable=unnecessary-lambda return self.bind(lambda res: other.parsecmap(lambda x: res(x)))
python
def parsecapp(self, other): '''Returns a parser that applies the produced value of this parser to the produced value of `other`.''' # pylint: disable=unnecessary-lambda return self.bind(lambda res: other.parsecmap(lambda x: res(x)))
[ "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`.
[ "Returns", "a", "parser", "that", "applies", "the", "produced", "value", "of", "this", "parser", "to", "the", "produced", "value", "of", "other", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L222-L225
25,163
sighingnow/parsec.py
src/parsec/__init__.py
Parser.result
def result(self, res): '''Return a value according to the parameter `res` when parse successfully.''' return self >> Parser(lambda _, index: Value.success(index, res))
python
def result(self, res): '''Return a value according to the parameter `res` when parse successfully.''' return self >> Parser(lambda _, index: Value.success(index, res))
[ "def", "result", "(", "self", ",", "res", ")", ":", "return", "self", ">>", "Parser", "(", "lambda", "_", ",", "index", ":", "Value", ".", "success", "(", "index", ",", "res", ")", ")" ]
Return a value according to the parameter `res` when parse successfully.
[ "Return", "a", "value", "according", "to", "the", "parameter", "res", "when", "parse", "successfully", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L227-L229
25,164
sighingnow/parsec.py
src/parsec/__init__.py
Parser.mark
def mark(self): '''Mark the line and column information of the result of this parser.''' 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
python
def mark(self): '''Mark the line and column information of the result of this parser.''' 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
[ "def", "mark", "(", "self", ")", ":", "def", "pos", "(", "text", ",", "index", ")", ":", "return", "ParseError", ".", "loc_info", "(", "text", ",", "index", ")", "@", "Parser", "def", "mark_parser", "(", "text", ",", "index", ")", ":", "res", "=", ...
Mark the line and column information of the result of this parser.
[ "Mark", "the", "line", "and", "column", "information", "of", "the", "result", "of", "this", "parser", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L231-L243
25,165
sighingnow/parsec.py
src/parsec/__init__.py
Parser.desc
def desc(self, description): '''Describe a parser, when it failed, print out the description text.''' return self | Parser(lambda _, index: Value.failure(index, description))
python
def desc(self, description): '''Describe a parser, when it failed, print out the description text.''' return self | Parser(lambda _, index: Value.failure(index, description))
[ "def", "desc", "(", "self", ",", "description", ")", ":", "return", "self", "|", "Parser", "(", "lambda", "_", ",", "index", ":", "Value", ".", "failure", "(", "index", ",", "description", ")", ")" ]
Describe a parser, when it failed, print out the description text.
[ "Describe", "a", "parser", "when", "it", "failed", "print", "out", "the", "description", "text", "." ]
ed50e1e259142757470b925f8d20dfe5ad223af0
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L245-L247
25,166
pecan/pecan
pecan/routing.py
route
def route(*args): """ This function is used to define an explicit route for a path segment. You generally only want to use this in situations where your desired path segment is not a valid Python variable/function name. For example, if you wanted to be able to route to: /path/with-dashes/ ...the following is invalid Python syntax:: class Controller(object): with-dashes = SubController() ...so you would instead define the route explicitly:: class Controller(object): pass pecan.route(Controller, 'with-dashes', SubController()) """ 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)
python
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)
[ "def", "route", "(", "*", "args", ")", ":", "def", "_validate_route", "(", "route", ")", ":", "if", "not", "isinstance", "(", "route", ",", "six", ".", "string_types", ")", ":", "raise", "TypeError", "(", "'%s must be a string'", "%", "route", ")", "if",...
This function is used to define an explicit route for a path segment. You generally only want to use this in situations where your desired path segment is not a valid Python variable/function name. For example, if you wanted to be able to route to: /path/with-dashes/ ...the following is invalid Python syntax:: class Controller(object): with-dashes = SubController() ...so you would instead define the route explicitly:: class Controller(object): pass pecan.route(Controller, 'with-dashes', SubController())
[ "This", "function", "is", "used", "to", "define", "an", "explicit", "route", "for", "a", "path", "segment", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/routing.py#L19-L101
25,167
pecan/pecan
pecan/routing.py
lookup_controller
def lookup_controller(obj, remainder, request=None): ''' Traverses the requested url path and returns the appropriate controller object, including default routes. Handles common errors gracefully. ''' if request is None: warnings.warn( ( "The function signature for %s.lookup_controller is changing " "in the next version of pecan.\nPlease update to: " "`lookup_controller(self, obj, remainder, request)`." % ( __name__, ) ), DeprecationWarning ) notfound_handlers = [] while True: try: obj, remainder = find_object(obj, remainder, notfound_handlers, request) handle_security(obj) return obj, remainder except (exc.HTTPNotFound, exc.HTTPMethodNotAllowed, PecanNotFound) as e: if isinstance(e, PecanNotFound): e = exc.HTTPNotFound() while notfound_handlers: name, obj, remainder = notfound_handlers.pop() if name == '_default': # Notfound handler is, in fact, a controller, so stop # traversal return obj, remainder else: # Notfound handler is an internal redirect, so continue # traversal result = handle_lookup_traversal(obj, remainder) if result: # If no arguments are passed to the _lookup, yet the # argspec requires at least one, raise a 404 if ( remainder == [''] and len(obj._pecan['argspec'].args) > 1 ): raise e obj_, remainder_ = result return lookup_controller(obj_, remainder_, request) else: raise e
python
def lookup_controller(obj, remainder, request=None): ''' Traverses the requested url path and returns the appropriate controller object, including default routes. Handles common errors gracefully. ''' if request is None: warnings.warn( ( "The function signature for %s.lookup_controller is changing " "in the next version of pecan.\nPlease update to: " "`lookup_controller(self, obj, remainder, request)`." % ( __name__, ) ), DeprecationWarning ) notfound_handlers = [] while True: try: obj, remainder = find_object(obj, remainder, notfound_handlers, request) handle_security(obj) return obj, remainder except (exc.HTTPNotFound, exc.HTTPMethodNotAllowed, PecanNotFound) as e: if isinstance(e, PecanNotFound): e = exc.HTTPNotFound() while notfound_handlers: name, obj, remainder = notfound_handlers.pop() if name == '_default': # Notfound handler is, in fact, a controller, so stop # traversal return obj, remainder else: # Notfound handler is an internal redirect, so continue # traversal result = handle_lookup_traversal(obj, remainder) if result: # If no arguments are passed to the _lookup, yet the # argspec requires at least one, raise a 404 if ( remainder == [''] and len(obj._pecan['argspec'].args) > 1 ): raise e obj_, remainder_ = result return lookup_controller(obj_, remainder_, request) else: raise e
[ "def", "lookup_controller", "(", "obj", ",", "remainder", ",", "request", "=", "None", ")", ":", "if", "request", "is", "None", ":", "warnings", ".", "warn", "(", "(", "\"The function signature for %s.lookup_controller is changing \"", "\"in the next version of pecan.\\...
Traverses the requested url path and returns the appropriate controller object, including default routes. Handles common errors gracefully.
[ "Traverses", "the", "requested", "url", "path", "and", "returns", "the", "appropriate", "controller", "object", "including", "default", "routes", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/routing.py#L119-L170
25,168
pecan/pecan
pecan/routing.py
find_object
def find_object(obj, remainder, notfound_handlers, request): ''' 'Walks' the url path in search of an action for which a controller is implemented and returns that controller object along with what's left of the remainder. ''' prev_obj = None while True: if obj is None: raise PecanNotFound if iscontroller(obj): if getattr(obj, 'custom_route', None) is None: return obj, remainder _detect_custom_path_segments(obj) if remainder: custom_route = __custom_routes__.get((obj.__class__, remainder[0])) if custom_route: return getattr(obj, custom_route), remainder[1:] # are we traversing to another controller cross_boundary(prev_obj, obj) try: next_obj, rest = remainder[0], remainder[1:] if next_obj == '': index = getattr(obj, 'index', None) if iscontroller(index): return index, rest except IndexError: # the URL has hit an index method without a trailing slash index = getattr(obj, 'index', None) if iscontroller(index): raise NonCanonicalPath(index, []) default = getattr(obj, '_default', None) if iscontroller(default): notfound_handlers.append(('_default', default, remainder)) lookup = getattr(obj, '_lookup', None) if iscontroller(lookup): notfound_handlers.append(('_lookup', lookup, remainder)) route = getattr(obj, '_route', None) if iscontroller(route): if len(getargspec(route).args) == 2: warnings.warn( ( "The function signature for %s.%s._route is changing " "in the next version of pecan.\nPlease update to: " "`def _route(self, args, request)`." % ( obj.__class__.__module__, obj.__class__.__name__ ) ), DeprecationWarning ) next_obj, next_remainder = route(remainder) else: next_obj, next_remainder = route(remainder, request) cross_boundary(route, next_obj) return next_obj, next_remainder if not remainder: raise PecanNotFound prev_remainder = remainder prev_obj = obj remainder = rest try: obj = getattr(obj, next_obj, None) except UnicodeEncodeError: obj = None # Last-ditch effort: if there's not a matching subcontroller, no # `_default`, no `_lookup`, and no `_route`, look to see if there's # an `index` that has a generic method defined for the current request # method. if not obj and not notfound_handlers and hasattr(prev_obj, 'index'): if request.method in _cfg(prev_obj.index).get('generic_handlers', {}): return prev_obj.index, prev_remainder
python
def find_object(obj, remainder, notfound_handlers, request): ''' 'Walks' the url path in search of an action for which a controller is implemented and returns that controller object along with what's left of the remainder. ''' prev_obj = None while True: if obj is None: raise PecanNotFound if iscontroller(obj): if getattr(obj, 'custom_route', None) is None: return obj, remainder _detect_custom_path_segments(obj) if remainder: custom_route = __custom_routes__.get((obj.__class__, remainder[0])) if custom_route: return getattr(obj, custom_route), remainder[1:] # are we traversing to another controller cross_boundary(prev_obj, obj) try: next_obj, rest = remainder[0], remainder[1:] if next_obj == '': index = getattr(obj, 'index', None) if iscontroller(index): return index, rest except IndexError: # the URL has hit an index method without a trailing slash index = getattr(obj, 'index', None) if iscontroller(index): raise NonCanonicalPath(index, []) default = getattr(obj, '_default', None) if iscontroller(default): notfound_handlers.append(('_default', default, remainder)) lookup = getattr(obj, '_lookup', None) if iscontroller(lookup): notfound_handlers.append(('_lookup', lookup, remainder)) route = getattr(obj, '_route', None) if iscontroller(route): if len(getargspec(route).args) == 2: warnings.warn( ( "The function signature for %s.%s._route is changing " "in the next version of pecan.\nPlease update to: " "`def _route(self, args, request)`." % ( obj.__class__.__module__, obj.__class__.__name__ ) ), DeprecationWarning ) next_obj, next_remainder = route(remainder) else: next_obj, next_remainder = route(remainder, request) cross_boundary(route, next_obj) return next_obj, next_remainder if not remainder: raise PecanNotFound prev_remainder = remainder prev_obj = obj remainder = rest try: obj = getattr(obj, next_obj, None) except UnicodeEncodeError: obj = None # Last-ditch effort: if there's not a matching subcontroller, no # `_default`, no `_lookup`, and no `_route`, look to see if there's # an `index` that has a generic method defined for the current request # method. if not obj and not notfound_handlers and hasattr(prev_obj, 'index'): if request.method in _cfg(prev_obj.index).get('generic_handlers', {}): return prev_obj.index, prev_remainder
[ "def", "find_object", "(", "obj", ",", "remainder", ",", "notfound_handlers", ",", "request", ")", ":", "prev_obj", "=", "None", "while", "True", ":", "if", "obj", "is", "None", ":", "raise", "PecanNotFound", "if", "iscontroller", "(", "obj", ")", ":", "...
'Walks' the url path in search of an action for which a controller is implemented and returns that controller object along with what's left of the remainder.
[ "Walks", "the", "url", "path", "in", "search", "of", "an", "action", "for", "which", "a", "controller", "is", "implemented", "and", "returns", "that", "controller", "object", "along", "with", "what", "s", "left", "of", "the", "remainder", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/routing.py#L188-L269
25,169
pecan/pecan
pecan/secure.py
unlocked
def unlocked(func_or_obj): """ This method unlocks method or class attribute on a SecureController. Can be used to decorate or wrap an attribute """ if ismethod(func_or_obj) or isfunction(func_or_obj): return _unlocked_method(func_or_obj) else: return _UnlockedAttribute(func_or_obj)
python
def unlocked(func_or_obj): if ismethod(func_or_obj) or isfunction(func_or_obj): return _unlocked_method(func_or_obj) else: return _UnlockedAttribute(func_or_obj)
[ "def", "unlocked", "(", "func_or_obj", ")", ":", "if", "ismethod", "(", "func_or_obj", ")", "or", "isfunction", "(", "func_or_obj", ")", ":", "return", "_unlocked_method", "(", "func_or_obj", ")", "else", ":", "return", "_UnlockedAttribute", "(", "func_or_obj", ...
This method unlocks method or class attribute on a SecureController. Can be used to decorate or wrap an attribute
[ "This", "method", "unlocks", "method", "or", "class", "attribute", "on", "a", "SecureController", ".", "Can", "be", "used", "to", "decorate", "or", "wrap", "an", "attribute" ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/secure.py#L101-L109
25,170
pecan/pecan
pecan/secure.py
secure
def secure(func_or_obj, check_permissions_for_obj=None): """ This method secures a method or class depending on invocation. To decorate a method use one argument: @secure(<check_permissions_method>) To secure a class, invoke with two arguments: secure(<obj instance>, <check_permissions_method>) """ if _allowed_check_permissions_types(func_or_obj): return _secure_method(func_or_obj) else: if not _allowed_check_permissions_types(check_permissions_for_obj): msg = "When securing an object, secure() requires the " + \ "second argument to be method" raise TypeError(msg) return _SecuredAttribute(func_or_obj, check_permissions_for_obj)
python
def secure(func_or_obj, check_permissions_for_obj=None): if _allowed_check_permissions_types(func_or_obj): return _secure_method(func_or_obj) else: if not _allowed_check_permissions_types(check_permissions_for_obj): msg = "When securing an object, secure() requires the " + \ "second argument to be method" raise TypeError(msg) return _SecuredAttribute(func_or_obj, check_permissions_for_obj)
[ "def", "secure", "(", "func_or_obj", ",", "check_permissions_for_obj", "=", "None", ")", ":", "if", "_allowed_check_permissions_types", "(", "func_or_obj", ")", ":", "return", "_secure_method", "(", "func_or_obj", ")", "else", ":", "if", "not", "_allowed_check_permi...
This method secures a method or class depending on invocation. To decorate a method use one argument: @secure(<check_permissions_method>) To secure a class, invoke with two arguments: secure(<obj instance>, <check_permissions_method>)
[ "This", "method", "secures", "a", "method", "or", "class", "depending", "on", "invocation", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/secure.py#L112-L129
25,171
pecan/pecan
pecan/secure.py
_make_wrapper
def _make_wrapper(f): """return a wrapped function with a copy of the _pecan context""" @wraps(f) def wrapper(*args, **kwargs): return f(*args, **kwargs) wrapper._pecan = f._pecan.copy() return wrapper
python
def _make_wrapper(f): @wraps(f) def wrapper(*args, **kwargs): return f(*args, **kwargs) wrapper._pecan = f._pecan.copy() return wrapper
[ "def", "_make_wrapper", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "wrapper", ".", "_pecan", "=", "f", ...
return a wrapped function with a copy of the _pecan context
[ "return", "a", "wrapped", "function", "with", "a", "copy", "of", "the", "_pecan", "context" ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/secure.py#L195-L201
25,172
pecan/pecan
pecan/secure.py
handle_security
def handle_security(controller, im_self=None): """ Checks the security of a controller. """ if controller._pecan.get('secured', False): check_permissions = controller._pecan['check_permissions'] if isinstance(check_permissions, six.string_types): check_permissions = getattr( im_self or six.get_method_self(controller), check_permissions ) if not check_permissions(): raise exc.HTTPUnauthorized
python
def handle_security(controller, im_self=None): if controller._pecan.get('secured', False): check_permissions = controller._pecan['check_permissions'] if isinstance(check_permissions, six.string_types): check_permissions = getattr( im_self or six.get_method_self(controller), check_permissions ) if not check_permissions(): raise exc.HTTPUnauthorized
[ "def", "handle_security", "(", "controller", ",", "im_self", "=", "None", ")", ":", "if", "controller", ".", "_pecan", ".", "get", "(", "'secured'", ",", "False", ")", ":", "check_permissions", "=", "controller", ".", "_pecan", "[", "'check_permissions'", "]...
Checks the security of a controller.
[ "Checks", "the", "security", "of", "a", "controller", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/secure.py#L205-L217
25,173
pecan/pecan
pecan/secure.py
cross_boundary
def cross_boundary(prev_obj, obj): """ Check permissions as we move between object instances. """ if prev_obj is None: return if isinstance(obj, _SecuredAttribute): # a secure attribute can live in unsecure class so we have to set # while we walk the route obj.parent = prev_obj if hasattr(prev_obj, '_pecan'): if obj not in prev_obj._pecan.get('unlocked', []): handle_security(prev_obj)
python
def cross_boundary(prev_obj, obj): if prev_obj is None: return if isinstance(obj, _SecuredAttribute): # a secure attribute can live in unsecure class so we have to set # while we walk the route obj.parent = prev_obj if hasattr(prev_obj, '_pecan'): if obj not in prev_obj._pecan.get('unlocked', []): handle_security(prev_obj)
[ "def", "cross_boundary", "(", "prev_obj", ",", "obj", ")", ":", "if", "prev_obj", "is", "None", ":", "return", "if", "isinstance", "(", "obj", ",", "_SecuredAttribute", ")", ":", "# a secure attribute can live in unsecure class so we have to set", "# while we walk the r...
Check permissions as we move between object instances.
[ "Check", "permissions", "as", "we", "move", "between", "object", "instances", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/secure.py#L220-L232
25,174
pecan/pecan
pecan/scaffolds/__init__.py
makedirs
def makedirs(directory): """ Resursively create a named directory. """ parent = os.path.dirname(os.path.abspath(directory)) if not os.path.exists(parent): makedirs(parent) os.mkdir(directory)
python
def makedirs(directory): parent = os.path.dirname(os.path.abspath(directory)) if not os.path.exists(parent): makedirs(parent) os.mkdir(directory)
[ "def", "makedirs", "(", "directory", ")", ":", "parent", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "directory", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "parent", ")", ":", "makedirs",...
Resursively create a named directory.
[ "Resursively", "create", "a", "named", "directory", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/scaffolds/__init__.py#L105-L110
25,175
pecan/pecan
pecan/scaffolds/__init__.py
substitute_filename
def substitute_filename(fn, variables): """ Substitute +variables+ in file directory names. """ for var, value in variables.items(): fn = fn.replace('+%s+' % var, str(value)) return fn
python
def substitute_filename(fn, variables): for var, value in variables.items(): fn = fn.replace('+%s+' % var, str(value)) return fn
[ "def", "substitute_filename", "(", "fn", ",", "variables", ")", ":", "for", "var", ",", "value", "in", "variables", ".", "items", "(", ")", ":", "fn", "=", "fn", ".", "replace", "(", "'+%s+'", "%", "var", ",", "str", "(", "value", ")", ")", "return...
Substitute +variables+ in file directory names.
[ "Substitute", "+", "variables", "+", "in", "file", "directory", "names", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/scaffolds/__init__.py#L113-L117
25,176
pecan/pecan
pecan/__init__.py
make_app
def make_app(root, **kw): ''' Utility for creating the Pecan application object. This function should generally be called from the ``setup_app`` function in your project's ``app.py`` file. :param root: A string representing a root controller object (e.g., "myapp.controller.root.RootController") :param static_root: The relative path to a directory containing static files. Serving static files is only enabled when debug mode is set. :param debug: A flag to enable debug mode. This enables the debug middleware and serving static files. :param wrap_app: A function or middleware class to wrap the Pecan app. This must either be a wsgi middleware class or a function that returns a wsgi application. This wrapper is applied first before wrapping the application in other middlewares such as Pecan's debug middleware. This should be used if you want to use middleware to perform authentication or intercept all requests before they are routed to the root controller. :param logging: A dictionary used to configure logging. This uses ``logging.config.dictConfig``. All other keyword arguments are passed in to the Pecan app constructor. :returns: a ``Pecan`` object. ''' # Pass logging configuration (if it exists) on to the Python logging module logging = kw.get('logging', {}) debug = kw.get('debug', False) if logging: if debug: try: # # By default, Python 2.7+ silences DeprecationWarnings. # However, if conf.app.debug is True, we should probably ensure # that users see these types of warnings. # from logging import captureWarnings captureWarnings(True) warnings.simplefilter("default", DeprecationWarning) except ImportError: # No captureWarnings on Python 2.6, DeprecationWarnings are on pass if isinstance(logging, Config): logging = logging.to_dict() if 'version' not in logging: logging['version'] = 1 load_logging_config(logging) # Instantiate the WSGI app by passing **kw onward app = Pecan(root, **kw) # Optionally wrap the app in another WSGI app wrap_app = kw.get('wrap_app', None) if wrap_app: app = wrap_app(app) # Configuration for serving custom error messages errors = kw.get('errors', getattr(conf.app, 'errors', {})) if errors: app = middleware.errordocument.ErrorDocumentMiddleware(app, errors) # Included for internal redirect support app = middleware.recursive.RecursiveMiddleware(app) # When in debug mode, load exception debugging middleware static_root = kw.get('static_root', None) if debug: debug_kwargs = getattr(conf, 'debug', {}) debug_kwargs.setdefault('context_injectors', []).append( lambda environ: { 'request': environ.get('pecan.locals', {}).get('request') } ) app = DebugMiddleware( app, **debug_kwargs ) # Support for serving static files (for development convenience) if static_root: app = middleware.static.StaticFileMiddleware(app, static_root) elif static_root: warnings.warn( "`static_root` is only used when `debug` is True, ignoring", RuntimeWarning ) if hasattr(conf, 'requestviewer'): warnings.warn(''.join([ "`pecan.conf.requestviewer` is deprecated. To apply the ", "`RequestViewerHook` to your application, add it to ", "`pecan.conf.app.hooks` or manually in your project's `app.py` ", "file."]), DeprecationWarning ) return app
python
def make_app(root, **kw): ''' Utility for creating the Pecan application object. This function should generally be called from the ``setup_app`` function in your project's ``app.py`` file. :param root: A string representing a root controller object (e.g., "myapp.controller.root.RootController") :param static_root: The relative path to a directory containing static files. Serving static files is only enabled when debug mode is set. :param debug: A flag to enable debug mode. This enables the debug middleware and serving static files. :param wrap_app: A function or middleware class to wrap the Pecan app. This must either be a wsgi middleware class or a function that returns a wsgi application. This wrapper is applied first before wrapping the application in other middlewares such as Pecan's debug middleware. This should be used if you want to use middleware to perform authentication or intercept all requests before they are routed to the root controller. :param logging: A dictionary used to configure logging. This uses ``logging.config.dictConfig``. All other keyword arguments are passed in to the Pecan app constructor. :returns: a ``Pecan`` object. ''' # Pass logging configuration (if it exists) on to the Python logging module logging = kw.get('logging', {}) debug = kw.get('debug', False) if logging: if debug: try: # # By default, Python 2.7+ silences DeprecationWarnings. # However, if conf.app.debug is True, we should probably ensure # that users see these types of warnings. # from logging import captureWarnings captureWarnings(True) warnings.simplefilter("default", DeprecationWarning) except ImportError: # No captureWarnings on Python 2.6, DeprecationWarnings are on pass if isinstance(logging, Config): logging = logging.to_dict() if 'version' not in logging: logging['version'] = 1 load_logging_config(logging) # Instantiate the WSGI app by passing **kw onward app = Pecan(root, **kw) # Optionally wrap the app in another WSGI app wrap_app = kw.get('wrap_app', None) if wrap_app: app = wrap_app(app) # Configuration for serving custom error messages errors = kw.get('errors', getattr(conf.app, 'errors', {})) if errors: app = middleware.errordocument.ErrorDocumentMiddleware(app, errors) # Included for internal redirect support app = middleware.recursive.RecursiveMiddleware(app) # When in debug mode, load exception debugging middleware static_root = kw.get('static_root', None) if debug: debug_kwargs = getattr(conf, 'debug', {}) debug_kwargs.setdefault('context_injectors', []).append( lambda environ: { 'request': environ.get('pecan.locals', {}).get('request') } ) app = DebugMiddleware( app, **debug_kwargs ) # Support for serving static files (for development convenience) if static_root: app = middleware.static.StaticFileMiddleware(app, static_root) elif static_root: warnings.warn( "`static_root` is only used when `debug` is True, ignoring", RuntimeWarning ) if hasattr(conf, 'requestviewer'): warnings.warn(''.join([ "`pecan.conf.requestviewer` is deprecated. To apply the ", "`RequestViewerHook` to your application, add it to ", "`pecan.conf.app.hooks` or manually in your project's `app.py` ", "file."]), DeprecationWarning ) return app
[ "def", "make_app", "(", "root", ",", "*", "*", "kw", ")", ":", "# Pass logging configuration (if it exists) on to the Python logging module", "logging", "=", "kw", ".", "get", "(", "'logging'", ",", "{", "}", ")", "debug", "=", "kw", ".", "get", "(", "'debug'"...
Utility for creating the Pecan application object. This function should generally be called from the ``setup_app`` function in your project's ``app.py`` file. :param root: A string representing a root controller object (e.g., "myapp.controller.root.RootController") :param static_root: The relative path to a directory containing static files. Serving static files is only enabled when debug mode is set. :param debug: A flag to enable debug mode. This enables the debug middleware and serving static files. :param wrap_app: A function or middleware class to wrap the Pecan app. This must either be a wsgi middleware class or a function that returns a wsgi application. This wrapper is applied first before wrapping the application in other middlewares such as Pecan's debug middleware. This should be used if you want to use middleware to perform authentication or intercept all requests before they are routed to the root controller. :param logging: A dictionary used to configure logging. This uses ``logging.config.dictConfig``. All other keyword arguments are passed in to the Pecan app constructor. :returns: a ``Pecan`` object.
[ "Utility", "for", "creating", "the", "Pecan", "application", "object", ".", "This", "function", "should", "generally", "be", "called", "from", "the", "setup_app", "function", "in", "your", "project", "s", "app", ".", "py", "file", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/__init__.py#L33-L134
25,177
pecan/pecan
pecan/configuration.py
conf_from_file
def conf_from_file(filepath): ''' Creates a configuration dictionary from a file. :param filepath: The path to the file. ''' abspath = os.path.abspath(os.path.expanduser(filepath)) conf_dict = {} if not os.path.isfile(abspath): raise RuntimeError('`%s` is not a file.' % abspath) # First, make sure the code will actually compile (and has no SyntaxErrors) with open(abspath, 'rb') as f: compiled = compile(f.read(), abspath, 'exec') # Next, attempt to actually import the file as a module. # This provides more verbose import-related error reporting than exec() absname, _ = os.path.splitext(abspath) basepath, module_name = absname.rsplit(os.sep, 1) if six.PY3: SourceFileLoader(module_name, abspath).load_module(module_name) else: imp.load_module( module_name, *imp.find_module(module_name, [basepath]) ) # If we were able to import as a module, actually exec the compiled code exec(compiled, globals(), conf_dict) conf_dict['__file__'] = abspath return conf_from_dict(conf_dict)
python
def conf_from_file(filepath): ''' Creates a configuration dictionary from a file. :param filepath: The path to the file. ''' abspath = os.path.abspath(os.path.expanduser(filepath)) conf_dict = {} if not os.path.isfile(abspath): raise RuntimeError('`%s` is not a file.' % abspath) # First, make sure the code will actually compile (and has no SyntaxErrors) with open(abspath, 'rb') as f: compiled = compile(f.read(), abspath, 'exec') # Next, attempt to actually import the file as a module. # This provides more verbose import-related error reporting than exec() absname, _ = os.path.splitext(abspath) basepath, module_name = absname.rsplit(os.sep, 1) if six.PY3: SourceFileLoader(module_name, abspath).load_module(module_name) else: imp.load_module( module_name, *imp.find_module(module_name, [basepath]) ) # If we were able to import as a module, actually exec the compiled code exec(compiled, globals(), conf_dict) conf_dict['__file__'] = abspath return conf_from_dict(conf_dict)
[ "def", "conf_from_file", "(", "filepath", ")", ":", "abspath", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "filepath", ")", ")", "conf_dict", "=", "{", "}", "if", "not", "os", ".", "path", ".", "isfile", ...
Creates a configuration dictionary from a file. :param filepath: The path to the file.
[ "Creates", "a", "configuration", "dictionary", "from", "a", "file", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/configuration.py#L154-L186
25,178
pecan/pecan
pecan/configuration.py
get_conf_path_from_env
def get_conf_path_from_env(): ''' If the ``PECAN_CONFIG`` environment variable exists and it points to a valid path it will return that, otherwise it will raise a ``RuntimeError``. ''' config_path = os.environ.get('PECAN_CONFIG') if not config_path: error = "PECAN_CONFIG is not set and " \ "no config file was passed as an argument." elif not os.path.isfile(config_path): error = "PECAN_CONFIG was set to an invalid path: %s" % config_path else: return config_path raise RuntimeError(error)
python
def get_conf_path_from_env(): ''' If the ``PECAN_CONFIG`` environment variable exists and it points to a valid path it will return that, otherwise it will raise a ``RuntimeError``. ''' config_path = os.environ.get('PECAN_CONFIG') if not config_path: error = "PECAN_CONFIG is not set and " \ "no config file was passed as an argument." elif not os.path.isfile(config_path): error = "PECAN_CONFIG was set to an invalid path: %s" % config_path else: return config_path raise RuntimeError(error)
[ "def", "get_conf_path_from_env", "(", ")", ":", "config_path", "=", "os", ".", "environ", ".", "get", "(", "'PECAN_CONFIG'", ")", "if", "not", "config_path", ":", "error", "=", "\"PECAN_CONFIG is not set and \"", "\"no config file was passed as an argument.\"", "elif", ...
If the ``PECAN_CONFIG`` environment variable exists and it points to a valid path it will return that, otherwise it will raise a ``RuntimeError``.
[ "If", "the", "PECAN_CONFIG", "environment", "variable", "exists", "and", "it", "points", "to", "a", "valid", "path", "it", "will", "return", "that", "otherwise", "it", "will", "raise", "a", "RuntimeError", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/configuration.py#L189-L204
25,179
pecan/pecan
pecan/configuration.py
conf_from_dict
def conf_from_dict(conf_dict): ''' Creates a configuration dictionary from a dictionary. :param conf_dict: The configuration dictionary. ''' conf = Config(filename=conf_dict.get('__file__', '')) for k, v in six.iteritems(conf_dict): if k.startswith('__'): continue elif inspect.ismodule(v): continue conf[k] = v return conf
python
def conf_from_dict(conf_dict): ''' Creates a configuration dictionary from a dictionary. :param conf_dict: The configuration dictionary. ''' conf = Config(filename=conf_dict.get('__file__', '')) for k, v in six.iteritems(conf_dict): if k.startswith('__'): continue elif inspect.ismodule(v): continue conf[k] = v return conf
[ "def", "conf_from_dict", "(", "conf_dict", ")", ":", "conf", "=", "Config", "(", "filename", "=", "conf_dict", ".", "get", "(", "'__file__'", ",", "''", ")", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "conf_dict", ")", ":", "if", ...
Creates a configuration dictionary from a dictionary. :param conf_dict: The configuration dictionary.
[ "Creates", "a", "configuration", "dictionary", "from", "a", "dictionary", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/configuration.py#L207-L222
25,180
pecan/pecan
pecan/configuration.py
set_config
def set_config(config, overwrite=False): ''' Updates the global configuration. :param config: Can be a dictionary containing configuration, or a string which represents a (relative) configuration filename. ''' if config is None: config = get_conf_path_from_env() # must be after the fallback other a bad fallback will incorrectly clear if overwrite is True: _runtime_conf.empty() if isinstance(config, six.string_types): config = conf_from_file(config) _runtime_conf.update(config) if config.__file__: _runtime_conf.__file__ = config.__file__ elif isinstance(config, dict): _runtime_conf.update(conf_from_dict(config)) else: raise TypeError('%s is neither a dictionary or a string.' % config)
python
def set_config(config, overwrite=False): ''' Updates the global configuration. :param config: Can be a dictionary containing configuration, or a string which represents a (relative) configuration filename. ''' if config is None: config = get_conf_path_from_env() # must be after the fallback other a bad fallback will incorrectly clear if overwrite is True: _runtime_conf.empty() if isinstance(config, six.string_types): config = conf_from_file(config) _runtime_conf.update(config) if config.__file__: _runtime_conf.__file__ = config.__file__ elif isinstance(config, dict): _runtime_conf.update(conf_from_dict(config)) else: raise TypeError('%s is neither a dictionary or a string.' % config)
[ "def", "set_config", "(", "config", ",", "overwrite", "=", "False", ")", ":", "if", "config", "is", "None", ":", "config", "=", "get_conf_path_from_env", "(", ")", "# must be after the fallback other a bad fallback will incorrectly clear", "if", "overwrite", "is", "Tr...
Updates the global configuration. :param config: Can be a dictionary containing configuration, or a string which represents a (relative) configuration filename.
[ "Updates", "the", "global", "configuration", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/configuration.py#L233-L256
25,181
pecan/pecan
pecan/configuration.py
Config.update
def update(self, conf_dict): ''' Updates this configuration with a dictionary. :param conf_dict: A python dictionary to update this configuration with. ''' if isinstance(conf_dict, dict): iterator = six.iteritems(conf_dict) else: iterator = iter(conf_dict) for k, v in iterator: if not IDENTIFIER.match(k): raise ValueError('\'%s\' is not a valid indentifier' % k) cur_val = self.__values__.get(k) if isinstance(cur_val, Config): cur_val.update(conf_dict[k]) else: self[k] = conf_dict[k]
python
def update(self, conf_dict): ''' Updates this configuration with a dictionary. :param conf_dict: A python dictionary to update this configuration with. ''' if isinstance(conf_dict, dict): iterator = six.iteritems(conf_dict) else: iterator = iter(conf_dict) for k, v in iterator: if not IDENTIFIER.match(k): raise ValueError('\'%s\' is not a valid indentifier' % k) cur_val = self.__values__.get(k) if isinstance(cur_val, Config): cur_val.update(conf_dict[k]) else: self[k] = conf_dict[k]
[ "def", "update", "(", "self", ",", "conf_dict", ")", ":", "if", "isinstance", "(", "conf_dict", ",", "dict", ")", ":", "iterator", "=", "six", ".", "iteritems", "(", "conf_dict", ")", "else", ":", "iterator", "=", "iter", "(", "conf_dict", ")", "for", ...
Updates this configuration with a dictionary. :param conf_dict: A python dictionary to update this configuration with.
[ "Updates", "this", "configuration", "with", "a", "dictionary", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/configuration.py#L57-L79
25,182
pecan/pecan
pecan/configuration.py
Config.to_dict
def to_dict(self, prefix=None): ''' Converts recursively the Config object into a valid dictionary. :param prefix: A string to optionally prefix all key elements in the returned dictonary. ''' conf_obj = dict(self) return self.__dictify__(conf_obj, prefix)
python
def to_dict(self, prefix=None): ''' Converts recursively the Config object into a valid dictionary. :param prefix: A string to optionally prefix all key elements in the returned dictonary. ''' conf_obj = dict(self) return self.__dictify__(conf_obj, prefix)
[ "def", "to_dict", "(", "self", ",", "prefix", "=", "None", ")", ":", "conf_obj", "=", "dict", "(", "self", ")", "return", "self", ".", "__dictify__", "(", "conf_obj", ",", "prefix", ")" ]
Converts recursively the Config object into a valid dictionary. :param prefix: A string to optionally prefix all key elements in the returned dictonary.
[ "Converts", "recursively", "the", "Config", "object", "into", "a", "valid", "dictionary", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/configuration.py#L100-L109
25,183
pecan/pecan
pecan/core.py
override_template
def override_template(template, content_type=None): ''' Call within a controller to override the template that is used in your response. :param template: a valid path to a template file, just as you would specify in an ``@expose``. :param content_type: a valid MIME type to use for the response.func_closure ''' request.pecan['override_template'] = template if content_type: request.pecan['override_content_type'] = content_type
python
def override_template(template, content_type=None): ''' Call within a controller to override the template that is used in your response. :param template: a valid path to a template file, just as you would specify in an ``@expose``. :param content_type: a valid MIME type to use for the response.func_closure ''' request.pecan['override_template'] = template if content_type: request.pecan['override_content_type'] = content_type
[ "def", "override_template", "(", "template", ",", "content_type", "=", "None", ")", ":", "request", ".", "pecan", "[", "'override_template'", "]", "=", "template", "if", "content_type", ":", "request", ".", "pecan", "[", "'override_content_type'", "]", "=", "c...
Call within a controller to override the template that is used in your response. :param template: a valid path to a template file, just as you would specify in an ``@expose``. :param content_type: a valid MIME type to use for the response.func_closure
[ "Call", "within", "a", "controller", "to", "override", "the", "template", "that", "is", "used", "in", "your", "response", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/core.py#L98-L110
25,184
pecan/pecan
pecan/core.py
abort
def abort(status_code, detail='', headers=None, comment=None, **kw): ''' Raise an HTTP status code, as specified. Useful for returning status codes like 401 Unauthorized or 403 Forbidden. :param status_code: The HTTP status code as an integer. :param detail: The message to send along, as a string. :param headers: A dictionary of headers to send along with the response. :param comment: A comment to include in the response. ''' # If there is a traceback, we need to catch it for a re-raise try: _, _, traceback = sys.exc_info() webob_exception = exc.status_map[status_code]( detail=detail, headers=headers, comment=comment, **kw ) if six.PY3: raise webob_exception.with_traceback(traceback) else: # Using exec to avoid python 3 parsers from crashing exec('raise webob_exception, None, traceback') finally: # Per the suggestion of the Python docs, delete the traceback object del traceback
python
def abort(status_code, detail='', headers=None, comment=None, **kw): ''' Raise an HTTP status code, as specified. Useful for returning status codes like 401 Unauthorized or 403 Forbidden. :param status_code: The HTTP status code as an integer. :param detail: The message to send along, as a string. :param headers: A dictionary of headers to send along with the response. :param comment: A comment to include in the response. ''' # If there is a traceback, we need to catch it for a re-raise try: _, _, traceback = sys.exc_info() webob_exception = exc.status_map[status_code]( detail=detail, headers=headers, comment=comment, **kw ) if six.PY3: raise webob_exception.with_traceback(traceback) else: # Using exec to avoid python 3 parsers from crashing exec('raise webob_exception, None, traceback') finally: # Per the suggestion of the Python docs, delete the traceback object del traceback
[ "def", "abort", "(", "status_code", ",", "detail", "=", "''", ",", "headers", "=", "None", ",", "comment", "=", "None", ",", "*", "*", "kw", ")", ":", "# If there is a traceback, we need to catch it for a re-raise", "try", ":", "_", ",", "_", ",", "traceback...
Raise an HTTP status code, as specified. Useful for returning status codes like 401 Unauthorized or 403 Forbidden. :param status_code: The HTTP status code as an integer. :param detail: The message to send along, as a string. :param headers: A dictionary of headers to send along with the response. :param comment: A comment to include in the response.
[ "Raise", "an", "HTTP", "status", "code", "as", "specified", ".", "Useful", "for", "returning", "status", "codes", "like", "401", "Unauthorized", "or", "403", "Forbidden", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/core.py#L113-L141
25,185
pecan/pecan
pecan/core.py
redirect
def redirect(location=None, internal=False, code=None, headers={}, add_slash=False, request=None): ''' Perform a redirect, either internal or external. An internal redirect performs the redirect server-side, while the external redirect utilizes an HTTP 302 status code. :param location: The HTTP location to redirect to. :param internal: A boolean indicating whether the redirect should be internal. :param code: The HTTP status code to use for the redirect. Defaults to 302. :param headers: Any HTTP headers to send with the response, as a dictionary. :param request: The :class:`pecan.Request` instance to use. ''' request = request or state.request if add_slash: if location is None: split_url = list(urlparse.urlsplit(request.url)) new_proto = request.environ.get( 'HTTP_X_FORWARDED_PROTO', split_url[0] ) split_url[0] = new_proto else: split_url = urlparse.urlsplit(location) split_url[2] = split_url[2].rstrip('/') + '/' location = urlparse.urlunsplit(split_url) if not headers: headers = {} if internal: if code is not None: raise ValueError('Cannot specify a code for internal redirects') request.environ['pecan.recursive.context'] = request.context raise ForwardRequestException(location) if code is None: code = 302 raise exc.status_map[code](location=location, headers=headers)
python
def redirect(location=None, internal=False, code=None, headers={}, add_slash=False, request=None): ''' Perform a redirect, either internal or external. An internal redirect performs the redirect server-side, while the external redirect utilizes an HTTP 302 status code. :param location: The HTTP location to redirect to. :param internal: A boolean indicating whether the redirect should be internal. :param code: The HTTP status code to use for the redirect. Defaults to 302. :param headers: Any HTTP headers to send with the response, as a dictionary. :param request: The :class:`pecan.Request` instance to use. ''' request = request or state.request if add_slash: if location is None: split_url = list(urlparse.urlsplit(request.url)) new_proto = request.environ.get( 'HTTP_X_FORWARDED_PROTO', split_url[0] ) split_url[0] = new_proto else: split_url = urlparse.urlsplit(location) split_url[2] = split_url[2].rstrip('/') + '/' location = urlparse.urlunsplit(split_url) if not headers: headers = {} if internal: if code is not None: raise ValueError('Cannot specify a code for internal redirects') request.environ['pecan.recursive.context'] = request.context raise ForwardRequestException(location) if code is None: code = 302 raise exc.status_map[code](location=location, headers=headers)
[ "def", "redirect", "(", "location", "=", "None", ",", "internal", "=", "False", ",", "code", "=", "None", ",", "headers", "=", "{", "}", ",", "add_slash", "=", "False", ",", "request", "=", "None", ")", ":", "request", "=", "request", "or", "state", ...
Perform a redirect, either internal or external. An internal redirect performs the redirect server-side, while the external redirect utilizes an HTTP 302 status code. :param location: The HTTP location to redirect to. :param internal: A boolean indicating whether the redirect should be internal. :param code: The HTTP status code to use for the redirect. Defaults to 302. :param headers: Any HTTP headers to send with the response, as a dictionary. :param request: The :class:`pecan.Request` instance to use.
[ "Perform", "a", "redirect", "either", "internal", "or", "external", ".", "An", "internal", "redirect", "performs", "the", "redirect", "server", "-", "side", "while", "the", "external", "redirect", "utilizes", "an", "HTTP", "302", "status", "code", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/core.py#L144-L183
25,186
pecan/pecan
pecan/core.py
load_app
def load_app(config, **kwargs): ''' Used to load a ``Pecan`` application and its environment based on passed configuration. :param config: Can be a dictionary containing configuration, a string which represents a (relative) configuration filename returns a pecan.Pecan object ''' from .configuration import _runtime_conf, set_config set_config(config, overwrite=True) for package_name in getattr(_runtime_conf.app, 'modules', []): module = __import__(package_name, fromlist=['app']) if hasattr(module, 'app') and hasattr(module.app, 'setup_app'): app = module.app.setup_app(_runtime_conf, **kwargs) app.config = _runtime_conf return app raise RuntimeError( 'No app.setup_app found in any of the configured app.modules' )
python
def load_app(config, **kwargs): ''' Used to load a ``Pecan`` application and its environment based on passed configuration. :param config: Can be a dictionary containing configuration, a string which represents a (relative) configuration filename returns a pecan.Pecan object ''' from .configuration import _runtime_conf, set_config set_config(config, overwrite=True) for package_name in getattr(_runtime_conf.app, 'modules', []): module = __import__(package_name, fromlist=['app']) if hasattr(module, 'app') and hasattr(module.app, 'setup_app'): app = module.app.setup_app(_runtime_conf, **kwargs) app.config = _runtime_conf return app raise RuntimeError( 'No app.setup_app found in any of the configured app.modules' )
[ "def", "load_app", "(", "config", ",", "*", "*", "kwargs", ")", ":", "from", ".", "configuration", "import", "_runtime_conf", ",", "set_config", "set_config", "(", "config", ",", "overwrite", "=", "True", ")", "for", "package_name", "in", "getattr", "(", "...
Used to load a ``Pecan`` application and its environment based on passed configuration. :param config: Can be a dictionary containing configuration, a string which represents a (relative) configuration filename returns a pecan.Pecan object
[ "Used", "to", "load", "a", "Pecan", "application", "and", "its", "environment", "based", "on", "passed", "configuration", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/core.py#L202-L223
25,187
pecan/pecan
pecan/core.py
PecanBase.route
def route(self, req, node, path): ''' Looks up a controller from a node based upon the specified path. :param node: The node, such as a root controller object. :param path: The path to look up on this node. ''' path = path.split('/')[1:] try: node, remainder = lookup_controller(node, path, req) return node, remainder except NonCanonicalPath as e: if self.force_canonical and \ not _cfg(e.controller).get('accept_noncanonical', False): if req.method == 'POST': raise RuntimeError( "You have POSTed to a URL '%s' which " "requires a slash. Most browsers will not maintain " "POST data when redirected. Please update your code " "to POST to '%s/' or set force_canonical to False" % (req.pecan['routing_path'], req.pecan['routing_path']) ) redirect(code=302, add_slash=True, request=req) return e.controller, e.remainder
python
def route(self, req, node, path): ''' Looks up a controller from a node based upon the specified path. :param node: The node, such as a root controller object. :param path: The path to look up on this node. ''' path = path.split('/')[1:] try: node, remainder = lookup_controller(node, path, req) return node, remainder except NonCanonicalPath as e: if self.force_canonical and \ not _cfg(e.controller).get('accept_noncanonical', False): if req.method == 'POST': raise RuntimeError( "You have POSTed to a URL '%s' which " "requires a slash. Most browsers will not maintain " "POST data when redirected. Please update your code " "to POST to '%s/' or set force_canonical to False" % (req.pecan['routing_path'], req.pecan['routing_path']) ) redirect(code=302, add_slash=True, request=req) return e.controller, e.remainder
[ "def", "route", "(", "self", ",", "req", ",", "node", ",", "path", ")", ":", "path", "=", "path", ".", "split", "(", "'/'", ")", "[", "1", ":", "]", "try", ":", "node", ",", "remainder", "=", "lookup_controller", "(", "node", ",", "path", ",", ...
Looks up a controller from a node based upon the specified path. :param node: The node, such as a root controller object. :param path: The path to look up on this node.
[ "Looks", "up", "a", "controller", "from", "a", "node", "based", "upon", "the", "specified", "path", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/core.py#L284-L308
25,188
pecan/pecan
pecan/core.py
PecanBase.determine_hooks
def determine_hooks(self, controller=None): ''' Determines the hooks to be run, in which order. :param controller: If specified, includes hooks for a specific controller. ''' controller_hooks = [] if controller: controller_hooks = _cfg(controller).get('hooks', []) if controller_hooks: return list( sorted( chain(controller_hooks, self.hooks), key=operator.attrgetter('priority') ) ) return self.hooks
python
def determine_hooks(self, controller=None): ''' Determines the hooks to be run, in which order. :param controller: If specified, includes hooks for a specific controller. ''' controller_hooks = [] if controller: controller_hooks = _cfg(controller).get('hooks', []) if controller_hooks: return list( sorted( chain(controller_hooks, self.hooks), key=operator.attrgetter('priority') ) ) return self.hooks
[ "def", "determine_hooks", "(", "self", ",", "controller", "=", "None", ")", ":", "controller_hooks", "=", "[", "]", "if", "controller", ":", "controller_hooks", "=", "_cfg", "(", "controller", ")", ".", "get", "(", "'hooks'", ",", "[", "]", ")", "if", ...
Determines the hooks to be run, in which order. :param controller: If specified, includes hooks for a specific controller.
[ "Determines", "the", "hooks", "to", "be", "run", "in", "which", "order", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/core.py#L310-L328
25,189
pecan/pecan
pecan/core.py
PecanBase.handle_hooks
def handle_hooks(self, hooks, hook_type, *args): ''' Processes hooks of the specified type. :param hook_type: The type of hook, including ``before``, ``after``, ``on_error``, and ``on_route``. :param \*args: Arguments to pass to the hooks. ''' if hook_type not in ['before', 'on_route']: hooks = reversed(hooks) for hook in hooks: result = getattr(hook, hook_type)(*args) # on_error hooks can choose to return a Response, which will # be used instead of the standard error pages. if hook_type == 'on_error' and isinstance(result, WebObResponse): return result
python
def handle_hooks(self, hooks, hook_type, *args): ''' Processes hooks of the specified type. :param hook_type: The type of hook, including ``before``, ``after``, ``on_error``, and ``on_route``. :param \*args: Arguments to pass to the hooks. ''' if hook_type not in ['before', 'on_route']: hooks = reversed(hooks) for hook in hooks: result = getattr(hook, hook_type)(*args) # on_error hooks can choose to return a Response, which will # be used instead of the standard error pages. if hook_type == 'on_error' and isinstance(result, WebObResponse): return result
[ "def", "handle_hooks", "(", "self", ",", "hooks", ",", "hook_type", ",", "*", "args", ")", ":", "if", "hook_type", "not", "in", "[", "'before'", ",", "'on_route'", "]", ":", "hooks", "=", "reversed", "(", "hooks", ")", "for", "hook", "in", "hooks", "...
Processes hooks of the specified type. :param hook_type: The type of hook, including ``before``, ``after``, ``on_error``, and ``on_route``. :param \*args: Arguments to pass to the hooks.
[ "Processes", "hooks", "of", "the", "specified", "type", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/core.py#L330-L346
25,190
pecan/pecan
pecan/core.py
PecanBase.get_args
def get_args(self, state, all_params, remainder, argspec, im_self): ''' Determines the arguments for a controller based upon parameters passed the argument specification for the controller. ''' args = [] varargs = [] kwargs = dict() valid_args = argspec.args[:] if ismethod(state.controller) or im_self: valid_args.pop(0) # pop off `self` pecan_state = state.request.pecan remainder = [x for x in remainder if x] if im_self is not None: args.append(im_self) # grab the routing args from nested REST controllers if 'routing_args' in pecan_state: remainder = pecan_state['routing_args'] + list(remainder) del pecan_state['routing_args'] # handle positional arguments if valid_args and remainder: args.extend(remainder[:len(valid_args)]) remainder = remainder[len(valid_args):] valid_args = valid_args[len(args):] # handle wildcard arguments if [i for i in remainder if i]: if not argspec[1]: abort(404) varargs.extend(remainder) # get the default positional arguments if argspec[3]: defaults = dict(izip(argspec[0][-len(argspec[3]):], argspec[3])) else: defaults = dict() # handle positional GET/POST params for name in valid_args: if name in all_params: args.append(all_params.pop(name)) elif name in defaults: args.append(defaults[name]) else: break # handle wildcard GET/POST params if argspec[2]: for name, value in six.iteritems(all_params): if name not in argspec[0]: kwargs[name] = value return args, varargs, kwargs
python
def get_args(self, state, all_params, remainder, argspec, im_self): ''' Determines the arguments for a controller based upon parameters passed the argument specification for the controller. ''' args = [] varargs = [] kwargs = dict() valid_args = argspec.args[:] if ismethod(state.controller) or im_self: valid_args.pop(0) # pop off `self` pecan_state = state.request.pecan remainder = [x for x in remainder if x] if im_self is not None: args.append(im_self) # grab the routing args from nested REST controllers if 'routing_args' in pecan_state: remainder = pecan_state['routing_args'] + list(remainder) del pecan_state['routing_args'] # handle positional arguments if valid_args and remainder: args.extend(remainder[:len(valid_args)]) remainder = remainder[len(valid_args):] valid_args = valid_args[len(args):] # handle wildcard arguments if [i for i in remainder if i]: if not argspec[1]: abort(404) varargs.extend(remainder) # get the default positional arguments if argspec[3]: defaults = dict(izip(argspec[0][-len(argspec[3]):], argspec[3])) else: defaults = dict() # handle positional GET/POST params for name in valid_args: if name in all_params: args.append(all_params.pop(name)) elif name in defaults: args.append(defaults[name]) else: break # handle wildcard GET/POST params if argspec[2]: for name, value in six.iteritems(all_params): if name not in argspec[0]: kwargs[name] = value return args, varargs, kwargs
[ "def", "get_args", "(", "self", ",", "state", ",", "all_params", ",", "remainder", ",", "argspec", ",", "im_self", ")", ":", "args", "=", "[", "]", "varargs", "=", "[", "]", "kwargs", "=", "dict", "(", ")", "valid_args", "=", "argspec", ".", "args", ...
Determines the arguments for a controller based upon parameters passed the argument specification for the controller.
[ "Determines", "the", "arguments", "for", "a", "controller", "based", "upon", "parameters", "passed", "the", "argument", "specification", "for", "the", "controller", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/core.py#L348-L404
25,191
pecan/pecan
pecan/commands/shell.py
ShellCommand.run
def run(self, args): """ Load the pecan app, prepare the locals, sets the banner, and invokes the python shell. """ super(ShellCommand, self).run(args) # load the application app = self.load_app() # prepare the locals locs = dict(__name__='pecan-admin') locs['wsgiapp'] = app locs['app'] = TestApp(app) model = self.load_model(app.config) if model: locs['model'] = model # insert the pecan locals from pecan import abort, conf, redirect, request, response locs['abort'] = abort locs['conf'] = conf locs['redirect'] = redirect locs['request'] = request locs['response'] = response # prepare the banner banner = ' The following objects are available:\n' banner += ' %-10s - This project\'s WSGI App instance\n' % 'wsgiapp' banner += ' %-10s - The current configuration\n' % 'conf' banner += ' %-10s - webtest.TestApp wrapped around wsgiapp\n' % 'app' if model: model_name = getattr( model, '__module__', getattr(model, '__name__', 'model') ) banner += ' %-10s - Models from %s\n' % ('model', model_name) self.invoke_shell(locs, banner)
python
def run(self, args): super(ShellCommand, self).run(args) # load the application app = self.load_app() # prepare the locals locs = dict(__name__='pecan-admin') locs['wsgiapp'] = app locs['app'] = TestApp(app) model = self.load_model(app.config) if model: locs['model'] = model # insert the pecan locals from pecan import abort, conf, redirect, request, response locs['abort'] = abort locs['conf'] = conf locs['redirect'] = redirect locs['request'] = request locs['response'] = response # prepare the banner banner = ' The following objects are available:\n' banner += ' %-10s - This project\'s WSGI App instance\n' % 'wsgiapp' banner += ' %-10s - The current configuration\n' % 'conf' banner += ' %-10s - webtest.TestApp wrapped around wsgiapp\n' % 'app' if model: model_name = getattr( model, '__module__', getattr(model, '__name__', 'model') ) banner += ' %-10s - Models from %s\n' % ('model', model_name) self.invoke_shell(locs, banner)
[ "def", "run", "(", "self", ",", "args", ")", ":", "super", "(", "ShellCommand", ",", "self", ")", ".", "run", "(", "args", ")", "# load the application", "app", "=", "self", ".", "load_app", "(", ")", "# prepare the locals", "locs", "=", "dict", "(", "...
Load the pecan app, prepare the locals, sets the banner, and invokes the python shell.
[ "Load", "the", "pecan", "app", "prepare", "the", "locals", "sets", "the", "banner", "and", "invokes", "the", "python", "shell", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/commands/shell.py#L108-L148
25,192
pecan/pecan
pecan/commands/shell.py
ShellCommand.load_model
def load_model(self, config): """ Load the model extension module """ for package_name in getattr(config.app, 'modules', []): module = __import__(package_name, fromlist=['model']) if hasattr(module, 'model'): return module.model return None
python
def load_model(self, config): for package_name in getattr(config.app, 'modules', []): module = __import__(package_name, fromlist=['model']) if hasattr(module, 'model'): return module.model return None
[ "def", "load_model", "(", "self", ",", "config", ")", ":", "for", "package_name", "in", "getattr", "(", "config", ".", "app", ",", "'modules'", ",", "[", "]", ")", ":", "module", "=", "__import__", "(", "package_name", ",", "fromlist", "=", "[", "'mode...
Load the model extension module
[ "Load", "the", "model", "extension", "module" ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/commands/shell.py#L169-L177
25,193
pecan/pecan
pecan/rest.py
RestController._handle_bad_rest_arguments
def _handle_bad_rest_arguments(self, controller, remainder, request): """ Ensure that the argspec for a discovered controller actually matched the positional arguments in the request path. If not, raise a webob.exc.HTTPBadRequest. """ argspec = self._get_args_for_controller(controller) fixed_args = len(argspec) - len( request.pecan.get('routing_args', []) ) if len(remainder) < fixed_args: # For controllers that are missing intermediate IDs # (e.g., /authors/books vs /authors/1/books), return a 404 for an # invalid path. abort(404)
python
def _handle_bad_rest_arguments(self, controller, remainder, request): argspec = self._get_args_for_controller(controller) fixed_args = len(argspec) - len( request.pecan.get('routing_args', []) ) if len(remainder) < fixed_args: # For controllers that are missing intermediate IDs # (e.g., /authors/books vs /authors/1/books), return a 404 for an # invalid path. abort(404)
[ "def", "_handle_bad_rest_arguments", "(", "self", ",", "controller", ",", "remainder", ",", "request", ")", ":", "argspec", "=", "self", ".", "_get_args_for_controller", "(", "controller", ")", "fixed_args", "=", "len", "(", "argspec", ")", "-", "len", "(", ...
Ensure that the argspec for a discovered controller actually matched the positional arguments in the request path. If not, raise a webob.exc.HTTPBadRequest.
[ "Ensure", "that", "the", "argspec", "for", "a", "discovered", "controller", "actually", "matched", "the", "positional", "arguments", "in", "the", "request", "path", ".", "If", "not", "raise", "a", "webob", ".", "exc", ".", "HTTPBadRequest", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/rest.py#L75-L89
25,194
pecan/pecan
pecan/rest.py
RestController._route
def _route(self, args, request=None): ''' Routes a request to the appropriate controller and returns its result. Performs a bit of validation - refuses to route delete and put actions via a GET request). ''' if request is None: from pecan import request # convention uses "_method" to handle browser-unsupported methods method = request.params.get('_method', request.method).lower() # make sure DELETE/PUT requests don't use GET if request.method == 'GET' and method in ('delete', 'put'): abort(405) # check for nested controllers result = self._find_sub_controllers(args, request) if result: return result # handle the request handler = getattr( self, '_handle_%s' % method, self._handle_unknown_method ) try: if len(getargspec(handler).args) == 3: result = handler(method, args) else: result = handler(method, args, request) # # If the signature of the handler does not match the number # of remaining positional arguments, attempt to handle # a _lookup method (if it exists) # argspec = self._get_args_for_controller(result[0]) num_args = len(argspec) if num_args < len(args): _lookup_result = self._handle_lookup(args, request) if _lookup_result: return _lookup_result except (exc.HTTPClientError, exc.HTTPNotFound, exc.HTTPMethodNotAllowed) as e: # # If the matching handler results in a 400, 404, or 405, attempt to # handle a _lookup method (if it exists) # _lookup_result = self._handle_lookup(args, request) if _lookup_result: return _lookup_result # Build a correct Allow: header if isinstance(e, exc.HTTPMethodNotAllowed): def method_iter(): for func in ('get', 'get_one', 'get_all', 'new', 'edit', 'get_delete'): if self._find_controller(func): yield 'GET' break for method in ('HEAD', 'POST', 'PUT', 'DELETE', 'TRACE', 'PATCH'): func = method.lower() if self._find_controller(func): yield method e.allow = sorted(method_iter()) raise # return the result return result
python
def _route(self, args, request=None): ''' Routes a request to the appropriate controller and returns its result. Performs a bit of validation - refuses to route delete and put actions via a GET request). ''' if request is None: from pecan import request # convention uses "_method" to handle browser-unsupported methods method = request.params.get('_method', request.method).lower() # make sure DELETE/PUT requests don't use GET if request.method == 'GET' and method in ('delete', 'put'): abort(405) # check for nested controllers result = self._find_sub_controllers(args, request) if result: return result # handle the request handler = getattr( self, '_handle_%s' % method, self._handle_unknown_method ) try: if len(getargspec(handler).args) == 3: result = handler(method, args) else: result = handler(method, args, request) # # If the signature of the handler does not match the number # of remaining positional arguments, attempt to handle # a _lookup method (if it exists) # argspec = self._get_args_for_controller(result[0]) num_args = len(argspec) if num_args < len(args): _lookup_result = self._handle_lookup(args, request) if _lookup_result: return _lookup_result except (exc.HTTPClientError, exc.HTTPNotFound, exc.HTTPMethodNotAllowed) as e: # # If the matching handler results in a 400, 404, or 405, attempt to # handle a _lookup method (if it exists) # _lookup_result = self._handle_lookup(args, request) if _lookup_result: return _lookup_result # Build a correct Allow: header if isinstance(e, exc.HTTPMethodNotAllowed): def method_iter(): for func in ('get', 'get_one', 'get_all', 'new', 'edit', 'get_delete'): if self._find_controller(func): yield 'GET' break for method in ('HEAD', 'POST', 'PUT', 'DELETE', 'TRACE', 'PATCH'): func = method.lower() if self._find_controller(func): yield method e.allow = sorted(method_iter()) raise # return the result return result
[ "def", "_route", "(", "self", ",", "args", ",", "request", "=", "None", ")", ":", "if", "request", "is", "None", ":", "from", "pecan", "import", "request", "# convention uses \"_method\" to handle browser-unsupported methods", "method", "=", "request", ".", "param...
Routes a request to the appropriate controller and returns its result. Performs a bit of validation - refuses to route delete and put actions via a GET request).
[ "Routes", "a", "request", "to", "the", "appropriate", "controller", "and", "returns", "its", "result", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/rest.py#L103-L178
25,195
pecan/pecan
pecan/rest.py
RestController._find_controller
def _find_controller(self, *args): ''' Returns the appropriate controller for routing a custom action. ''' for name in args: obj = self._lookup_child(name) if obj and iscontroller(obj): return obj return None
python
def _find_controller(self, *args): ''' Returns the appropriate controller for routing a custom action. ''' for name in args: obj = self._lookup_child(name) if obj and iscontroller(obj): return obj return None
[ "def", "_find_controller", "(", "self", ",", "*", "args", ")", ":", "for", "name", "in", "args", ":", "obj", "=", "self", ".", "_lookup_child", "(", "name", ")", "if", "obj", "and", "iscontroller", "(", "obj", ")", ":", "return", "obj", "return", "No...
Returns the appropriate controller for routing a custom action.
[ "Returns", "the", "appropriate", "controller", "for", "routing", "a", "custom", "action", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/rest.py#L195-L203
25,196
pecan/pecan
pecan/rest.py
RestController._find_sub_controllers
def _find_sub_controllers(self, remainder, request): ''' Identifies the correct controller to route to by analyzing the request URI. ''' # need either a get_one or get to parse args method = None for name in ('get_one', 'get'): if hasattr(self, name): method = name break if not method: return # get the args to figure out how much to chop off args = self._get_args_for_controller(getattr(self, method)) fixed_args = len(args) - len( request.pecan.get('routing_args', []) ) var_args = getargspec(getattr(self, method)).varargs # attempt to locate a sub-controller if var_args: for i, item in enumerate(remainder): controller = self._lookup_child(item) if controller and not ismethod(controller): self._set_routing_args(request, remainder[:i]) return lookup_controller(controller, remainder[i + 1:], request) elif fixed_args < len(remainder) and hasattr( self, remainder[fixed_args] ): controller = self._lookup_child(remainder[fixed_args]) if not ismethod(controller): self._set_routing_args(request, remainder[:fixed_args]) return lookup_controller( controller, remainder[fixed_args + 1:], request )
python
def _find_sub_controllers(self, remainder, request): ''' Identifies the correct controller to route to by analyzing the request URI. ''' # need either a get_one or get to parse args method = None for name in ('get_one', 'get'): if hasattr(self, name): method = name break if not method: return # get the args to figure out how much to chop off args = self._get_args_for_controller(getattr(self, method)) fixed_args = len(args) - len( request.pecan.get('routing_args', []) ) var_args = getargspec(getattr(self, method)).varargs # attempt to locate a sub-controller if var_args: for i, item in enumerate(remainder): controller = self._lookup_child(item) if controller and not ismethod(controller): self._set_routing_args(request, remainder[:i]) return lookup_controller(controller, remainder[i + 1:], request) elif fixed_args < len(remainder) and hasattr( self, remainder[fixed_args] ): controller = self._lookup_child(remainder[fixed_args]) if not ismethod(controller): self._set_routing_args(request, remainder[:fixed_args]) return lookup_controller( controller, remainder[fixed_args + 1:], request )
[ "def", "_find_sub_controllers", "(", "self", ",", "remainder", ",", "request", ")", ":", "# need either a get_one or get to parse args", "method", "=", "None", "for", "name", "in", "(", "'get_one'", ",", "'get'", ")", ":", "if", "hasattr", "(", "self", ",", "n...
Identifies the correct controller to route to by analyzing the request URI.
[ "Identifies", "the", "correct", "controller", "to", "route", "to", "by", "analyzing", "the", "request", "URI", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/rest.py#L205-L244
25,197
pecan/pecan
pecan/rest.py
RestController._handle_get
def _handle_get(self, method, remainder, request=None): ''' Routes ``GET`` actions to the appropriate controller. ''' if request is None: self._raise_method_deprecation_warning(self._handle_get) # route to a get_all or get if no additional parts are available if not remainder or remainder == ['']: remainder = list(six.moves.filter(bool, remainder)) controller = self._find_controller('get_all', 'get') if controller: self._handle_bad_rest_arguments(controller, remainder, request) return controller, [] abort(405) method_name = remainder[-1] # check for new/edit/delete GET requests if method_name in ('new', 'edit', 'delete'): if method_name == 'delete': method_name = 'get_delete' controller = self._find_controller(method_name) if controller: return controller, remainder[:-1] match = self._handle_custom_action(method, remainder, request) if match: return match controller = self._lookup_child(remainder[0]) if controller and not ismethod(controller): return lookup_controller(controller, remainder[1:], request) # finally, check for the regular get_one/get requests controller = self._find_controller('get_one', 'get') if controller: self._handle_bad_rest_arguments(controller, remainder, request) return controller, remainder abort(405)
python
def _handle_get(self, method, remainder, request=None): ''' Routes ``GET`` actions to the appropriate controller. ''' if request is None: self._raise_method_deprecation_warning(self._handle_get) # route to a get_all or get if no additional parts are available if not remainder or remainder == ['']: remainder = list(six.moves.filter(bool, remainder)) controller = self._find_controller('get_all', 'get') if controller: self._handle_bad_rest_arguments(controller, remainder, request) return controller, [] abort(405) method_name = remainder[-1] # check for new/edit/delete GET requests if method_name in ('new', 'edit', 'delete'): if method_name == 'delete': method_name = 'get_delete' controller = self._find_controller(method_name) if controller: return controller, remainder[:-1] match = self._handle_custom_action(method, remainder, request) if match: return match controller = self._lookup_child(remainder[0]) if controller and not ismethod(controller): return lookup_controller(controller, remainder[1:], request) # finally, check for the regular get_one/get requests controller = self._find_controller('get_one', 'get') if controller: self._handle_bad_rest_arguments(controller, remainder, request) return controller, remainder abort(405)
[ "def", "_handle_get", "(", "self", ",", "method", ",", "remainder", ",", "request", "=", "None", ")", ":", "if", "request", "is", "None", ":", "self", ".", "_raise_method_deprecation_warning", "(", "self", ".", "_handle_get", ")", "# route to a get_all or get if...
Routes ``GET`` actions to the appropriate controller.
[ "Routes", "GET", "actions", "to", "the", "appropriate", "controller", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/rest.py#L270-L309
25,198
pecan/pecan
pecan/rest.py
RestController._handle_delete
def _handle_delete(self, method, remainder, request=None): ''' Routes ``DELETE`` actions to the appropriate controller. ''' if request is None: self._raise_method_deprecation_warning(self._handle_delete) if remainder: match = self._handle_custom_action(method, remainder, request) if match: return match controller = self._lookup_child(remainder[0]) if controller and not ismethod(controller): return lookup_controller(controller, remainder[1:], request) # check for post_delete/delete requests first controller = self._find_controller('post_delete', 'delete') if controller: return controller, remainder # if no controller exists, try routing to a sub-controller; note that # since this is a DELETE verb, any local exposes are 405'd if remainder: if self._find_controller(remainder[0]): abort(405) sub_controller = self._lookup_child(remainder[0]) if sub_controller: return lookup_controller(sub_controller, remainder[1:], request) abort(405)
python
def _handle_delete(self, method, remainder, request=None): ''' Routes ``DELETE`` actions to the appropriate controller. ''' if request is None: self._raise_method_deprecation_warning(self._handle_delete) if remainder: match = self._handle_custom_action(method, remainder, request) if match: return match controller = self._lookup_child(remainder[0]) if controller and not ismethod(controller): return lookup_controller(controller, remainder[1:], request) # check for post_delete/delete requests first controller = self._find_controller('post_delete', 'delete') if controller: return controller, remainder # if no controller exists, try routing to a sub-controller; note that # since this is a DELETE verb, any local exposes are 405'd if remainder: if self._find_controller(remainder[0]): abort(405) sub_controller = self._lookup_child(remainder[0]) if sub_controller: return lookup_controller(sub_controller, remainder[1:], request) abort(405)
[ "def", "_handle_delete", "(", "self", ",", "method", ",", "remainder", ",", "request", "=", "None", ")", ":", "if", "request", "is", "None", ":", "self", ".", "_raise_method_deprecation_warning", "(", "self", ".", "_handle_delete", ")", "if", "remainder", ":...
Routes ``DELETE`` actions to the appropriate controller.
[ "Routes", "DELETE", "actions", "to", "the", "appropriate", "controller", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/rest.py#L311-L342
25,199
pecan/pecan
pecan/rest.py
RestController._handle_post
def _handle_post(self, method, remainder, request=None): ''' Routes ``POST`` requests. ''' if request is None: self._raise_method_deprecation_warning(self._handle_post) # check for custom POST/PUT requests if remainder: match = self._handle_custom_action(method, remainder, request) if match: return match controller = self._lookup_child(remainder[0]) if controller and not ismethod(controller): return lookup_controller(controller, remainder[1:], request) # check for regular POST/PUT requests controller = self._find_controller(method) if controller: return controller, remainder abort(405)
python
def _handle_post(self, method, remainder, request=None): ''' Routes ``POST`` requests. ''' if request is None: self._raise_method_deprecation_warning(self._handle_post) # check for custom POST/PUT requests if remainder: match = self._handle_custom_action(method, remainder, request) if match: return match controller = self._lookup_child(remainder[0]) if controller and not ismethod(controller): return lookup_controller(controller, remainder[1:], request) # check for regular POST/PUT requests controller = self._find_controller(method) if controller: return controller, remainder abort(405)
[ "def", "_handle_post", "(", "self", ",", "method", ",", "remainder", ",", "request", "=", "None", ")", ":", "if", "request", "is", "None", ":", "self", ".", "_raise_method_deprecation_warning", "(", "self", ".", "_handle_post", ")", "# check for custom POST/PUT ...
Routes ``POST`` requests.
[ "Routes", "POST", "requests", "." ]
833d0653fa0e6bbfb52545b091c30182105f4a82
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/rest.py#L344-L366