Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def handle_g_error(error, return_value):
error = error[0]
assert bool(return_value) == (error == ffi.NULL)
if error != ffi.NULL:
if error.message != ffi.NULL:
message = ('Pixbuf error: ' +
ffi.string(error.message).... | [
"Convert a :c:type:`GError**` to a Python :exception:`ImageLoadingError`,\n and raise it.\n\n "
] |
Please provide a description of the function:def decode_to_pixbuf(image_data, width=None, height=None):
loader = ffi.gc(
gdk_pixbuf.gdk_pixbuf_loader_new(), gobject.g_object_unref)
error = ffi.new('GError **')
if width and height:
gdk_pixbuf.gdk_pixbuf_loader_set_size(loader, width, hei... | [
"Decode an image from memory with GDK-PixBuf.\n The file format is detected automatically.\n\n :param image_data: A byte string\n :param width: Integer width in pixels or None\n :param height: Integer height in pixels or None\n :returns:\n A tuple of a new :class:`PixBuf` object\n and t... |
Please provide a description of the function:def decode_to_image_surface(image_data, width=None, height=None):
pixbuf, format_name = decode_to_pixbuf(image_data, width, height)
surface = (
pixbuf_to_cairo_gdk(pixbuf) if gdk is not None
else pixbuf_to_cairo_slices(pixbuf) if not pixbuf.get_h... | [
"Decode an image from memory into a cairo surface.\n The file format is detected automatically.\n\n :param image_data: A byte string\n :param width: Integer width in pixels or None\n :param height: Integer height in pixels or None\n :returns:\n A tuple of a new :class:`~cairocffi.ImageSurface`... |
Please provide a description of the function:def pixbuf_to_cairo_gdk(pixbuf):
dummy_context = Context(ImageSurface(constants.FORMAT_ARGB32, 1, 1))
gdk.gdk_cairo_set_source_pixbuf(
dummy_context._pointer, pixbuf._pointer, 0, 0)
return dummy_context.get_source().get_surface() | [
"Convert from PixBuf to ImageSurface, using GDK.\n\n This method is fastest but GDK is not always available.\n\n "
] |
Please provide a description of the function:def pixbuf_to_cairo_slices(pixbuf):
assert pixbuf.get_colorspace() == gdk_pixbuf.GDK_COLORSPACE_RGB
assert pixbuf.get_n_channels() == 3
assert pixbuf.get_bits_per_sample() == 8
width = pixbuf.get_width()
height = pixbuf.get_height()
rowstride = p... | [
"Convert from PixBuf to ImageSurface, using slice-based byte swapping.\n\n This method is 2~5x slower than GDK but does not support an alpha channel.\n (cairo uses pre-multiplied alpha, but not Pixbuf.)\n\n "
] |
Please provide a description of the function:def pixbuf_to_cairo_png(pixbuf):
buffer_pointer = ffi.new('gchar **')
buffer_size = ffi.new('gsize *')
error = ffi.new('GError **')
handle_g_error(error, pixbuf.save_to_buffer(
buffer_pointer, buffer_size, ffi.new('char[]', b'png'), error,
... | [
"Convert from PixBuf to ImageSurface, by going through the PNG format.\n\n This method is 10~30x slower than GDK but always works.\n\n "
] |
Please provide a description of the function:def init_rotate(cls, radians):
result = cls()
cairo.cairo_matrix_init_rotate(result._pointer, radians)
return result | [
"Return a new :class:`Matrix` for a transformation\n that rotates by :obj:`radians`.\n\n :type radians: float\n :param radians:\n Angle of rotation, in radians.\n The direction of rotation is defined such that\n positive angles rotate in the direction\n ... |
Please provide a description of the function:def as_tuple(self):
ptr = self._pointer
return (ptr.xx, ptr.yx, ptr.xy, ptr.yy, ptr.x0, ptr.y0) | [
"Return all of the matrix’s components.\n\n :returns: A ``(xx, yx, xy, yy, x0, y0)`` tuple of floats.\n\n "
] |
Please provide a description of the function:def multiply(self, other):
res = Matrix()
cairo.cairo_matrix_multiply(
res._pointer, self._pointer, other._pointer)
return res | [
"Multiply with another matrix\n and return the result as a new :class:`Matrix` object.\n Same as ``self * other``.\n\n "
] |
Please provide a description of the function:def translate(self, tx, ty):
cairo.cairo_matrix_translate(self._pointer, tx, ty) | [
"Applies a translation by :obj:`tx`, :obj:`ty`\n to the transformation in this matrix.\n\n The effect of the new transformation is to\n first translate the coordinates by :obj:`tx` and :obj:`ty`,\n then apply the original transformation to the coordinates.\n\n .. note::\n ... |
Please provide a description of the function:def scale(self, sx, sy=None):
if sy is None:
sy = sx
cairo.cairo_matrix_scale(self._pointer, sx, sy) | [
"Applies scaling by :obj:`sx`, :obj:`sy`\n to the transformation in this matrix.\n\n The effect of the new transformation is to\n first scale the coordinates by :obj:`sx` and :obj:`sy`,\n then apply the original transformation to the coordinates.\n\n If :obj:`sy` is omitted, it is... |
Please provide a description of the function:def transform_point(self, x, y):
xy = ffi.new('double[2]', [x, y])
cairo.cairo_matrix_transform_point(self._pointer, xy + 0, xy + 1)
return tuple(xy) | [
"Transforms the point ``(x, y)`` by this matrix.\n\n :param x: X position.\n :param y: Y position.\n :type x: float\n :type y: float\n :returns: A ``(new_x, new_y)`` tuple of floats.\n\n "
] |
Please provide a description of the function:def transform_distance(self, dx, dy):
xy = ffi.new('double[2]', [dx, dy])
cairo.cairo_matrix_transform_distance(self._pointer, xy + 0, xy + 1)
return tuple(xy) | [
"Transforms the distance vector ``(dx, dy)`` by this matrix.\n This is similar to :meth:`transform_point`\n except that the translation components of the transformation\n are ignored.\n The calculation of the returned vector is as follows::\n\n dx2 = dx1 * xx + dy1 * xy\n ... |
Please provide a description of the function:def toggleTransparency(self, force_value=None):
if force_value is None:
self._transparent = not self._transparent
else:
self._transparent = force_value
self.restoreActiveTheme() | [
" Toggles theme trasparency.\n\n force_value will set trasparency if True or False,\n or toggle trasparency if None\n "
] |
Please provide a description of the function:def keypress(self, char):
if char in (curses.KEY_ENTER, ord('\n'),
ord('\r'), ord('l'),
curses.KEY_RIGHT):
self._applied_theme = self._selection
self._applied_theme_name = self._themes[self._selection][... | [
" returns theme_id, save_theme\n return_id\n 0-.. : id in self._theme\n -1 : end or canel\n -2 : go no\n save_them\n True : theme is to be saved in config\n False : theme is not to be saved in config\n ",
" ESCAP... |
Please provide a description of the function:def probePlayer(requested_player=''):
ret_player = None
if logger.isEnabledFor(logging.INFO):
logger.info("Probing available multimedia players...")
implementedPlayers = Player.__subclasses__()
if logger.isEnabledFor(logging.INFO):
logger... | [
" Probes the multimedia players which are available on the host\n system."
] |
Please provide a description of the function:def play(self, name, streamUrl, encoding = ''):
self.close()
self.name = name
self.oldUserInput = {'Input': '', 'Volume': '', 'Title': ''}
self.muted = False
self.show_volume = True
self.title_prefix = ''
self.... | [
" use a multimedia player to play a stream "
] |
Please provide a description of the function:def _sendCommand(self, command):
if(self.process is not None):
try:
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Command: {}".format(command).strip())
self.process.stdin.write(command.e... | [
" send keystroke command to player "
] |
Please provide a description of the function:def close(self):
self._no_mute_on_stop_playback()
# First close the subprocess
self._stop()
# Here is fallback solution and cleanup
if self.connection_timeout_thread is not None:
self.connection_timeout_thread.c... | [
" exit pyradio (and kill player instance) "
] |
Please provide a description of the function:def toggleMute(self):
if not self.muted:
self._mute()
if self.delay_thread is not None:
self.delay_thread.cancel()
self.title_prefix = '[Muted] '
self.muted = True
self.show_volume ... | [
" mute / unmute player "
] |
Please provide a description of the function:def _configHasProfile(self):
for i, config_file in enumerate(self.config_files):
if os.path.exists(config_file):
with open(config_file) as f:
config_string = f.read()
if "[pyradio]" in config_s... | [
" Checks if mpv config has [pyradio] entry / profile.\n\n Profile example:\n\n [pyradio]\n volume-max=300\n volume=50"
] |
Please provide a description of the function:def _buildStartOpts(self, streamUrl, playList=False):
p = subprocess.Popen([self.PLAYER_CMD, "--input-ipc-server"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=False)
out = p.communicate()
if "not found" not in str(out[0]):... | [
" Builds the options to pass to subprocess.",
" Test for newer MPV versions as it supports different IPC flags. "
] |
Please provide a description of the function:def _format_title_string(self, title_string):
return self._title_string_format_text_tag(title_string.replace(self.icy_tokkens[0], self.icy_title_prefix)) | [
" format mpv's title "
] |
Please provide a description of the function:def _buildStartOpts(self, streamUrl, playList=False):
if playList:
opts = [self.PLAYER_CMD, "-quiet", "-playlist", streamUrl]
else:
opts = [self.PLAYER_CMD, "-quiet", streamUrl]
if self.USE_PROFILE == -1:
s... | [
" Builds the options to pass to subprocess."
] |
Please provide a description of the function:def _format_title_string(self, title_string):
if "StreamTitle='" in title_string:
tmp = title_string[title_string.find("StreamTitle='"):].replace("StreamTitle='", self.icy_title_prefix)
ret_string = tmp[:tmp.find("';")]
else:
... | [
" format mplayer's title ",
" work on format:\n ICY Info: START_SONG='{\"artist\":\"Clelia Cafiero\",\"title\":\"M. Mussorgsky-Quadri di un'esposizione\"}';\n Fund on \"ClassicaViva Web Radio: Classical\"\n "
] |
Please provide a description of the function:def _format_volume_string(self, volume_string):
return '[' + volume_string[volume_string.find(self.volume_string):].replace(' %','%').replace('ume', '')+'] ' | [
" format mplayer's volume "
] |
Please provide a description of the function:def _buildStartOpts(self, streamUrl, playList=False):
#opts = [self.PLAYER_CMD, "-Irc", "--quiet", streamUrl]
opts = [self.PLAYER_CMD, "-Irc", "-vv", streamUrl]
return opts | [
" Builds the options to pass to subprocess."
] |
Please provide a description of the function:def _mute(self):
if self.muted:
self._sendCommand("volume {}\n".format(self.actual_volume))
if logger.isEnabledFor(logging.DEBUG):
logger.debug('VLC unmuted: {0} ({1}%)'.format(self.actual_volume, int(100 * self.actua... | [
" mute vlc "
] |
Please provide a description of the function:def _format_volume_string(self, volume_string):
self.actual_volume = int(volume_string.split(self.volume_string)[1].split(',')[0].split()[0])
return '[Vol: {}%] '.format(int(100 * self.actual_volume / self.max_volume)) | [
" format vlc's volume "
] |
Please provide a description of the function:def _format_title_string(self, title_string):
sp = title_string.split(self.icy_tokkens[0])
if sp[0] == title_string:
ret_string = title_string
else:
ret_string = self.icy_title_prefix + sp[1]
return self._title... | [
" format vlc's title "
] |
Please provide a description of the function:def _is_accepted_input(self, input_string):
ret = False
accept_filter = (self.volume_string, "http stream debug: ")
reject_filter = ()
for n in accept_filter:
if n in input_string:
ret = True
... | [
" vlc input filtering "
] |
Please provide a description of the function:def _no_mute_on_stop_playback(self):
if self.ctrl_c_pressed:
return
if self.isPlaying():
if self.actual_volume == -1:
self._get_volume()
while self.actual_volume == -1:
pass
... | [
" make sure vlc does not stop muted "
] |
Please provide a description of the function:def shell():
version_too_old = False
if sys.version_info[0] == 2:
if sys.version_info < (2, 7):
version_too_old = True
elif sys.version_info.major == 3 and sys.version_info < (3, 5):
version_too_old = True
if version_too_ol... | [
" Setting ESCAPE key delay to 25ms\n Refer to: https://stackoverflow.com/questions/27372068/why-does-the-escape-key-have-a-delay-in-python-curses"
] |
Please provide a description of the function:def _move_old_csv(self, usr):
src = path.join(getenv('HOME', '~'), '.pyradio')
dst = path.join(usr, 'pyradio.csv')
dst1 = path.join(usr, 'stations.csv')
if path.exists(src) and path.isfile(src):
if path.exists(dst1):
... | [
" if a ~/.pyradio files exists, relocate it in user\n config folder and rename it to stations.csv, or if\n that exists, to pyradio.csv "
] |
Please provide a description of the function:def _check_stations_csv(self, usr, root):
''' Reclocate a stations.csv copy in user home for easy manage.
E.g. not need sudo when you add new station, etc '''
if path.exists(path.join(usr, 'stations.csv')):
return
else:
... | [] |
Please provide a description of the function:def copy_playlist_to_config_dir(self):
ret = 0
st = path.join(self.stations_dir, self.stations_filename_only)
if path.exists(st):
ret = 1
st = datetime.now().strftime("%Y-%m-%d_%H-%M-%S_")
st = path.join(se... | [
" Copy a foreign playlist in config dir\n Returns:\n -1: error copying file\n 0: success\n 1: playlist renamed\n "
] |
Please provide a description of the function:def _is_playlist_in_config_dir(self):
if path.dirname(self.stations_file) == self.stations_dir:
self.foreign_file = False
self.foreign_filename_only_no_extension = ''
else:
self.foreign_file = True
self... | [
" Check if a csv file is in the config dir "
] |
Please provide a description of the function:def _get_playlist_abspath_from_data(self, stationFile=''):
ret = -1
orig_input = stationFile
if stationFile:
if stationFile.endswith('.csv'):
stationFile = path.abspath(stationFile)
els... | [
" Get playlist absolute path\n Returns: playlist path, result\n Result is:\n 0 - playlist found\n -2 - playlist not found\n -3 - negative number specified\n -4 - number not found\n ",
" relative or absolute path... |
Please provide a description of the function:def read_playlist_file(self, stationFile=''):
prev_file = self.stations_file
prev_format = self.new_format
self.new_format = False
ret = 0
stationFile, ret = self._get_playlist_abspath_from_data(stationFile)
if ret < ... | [
" Read a csv file\n Returns: number\n x - number of stations or\n -1 - playlist is malformed\n -2 - playlist not found\n "
] |
Please provide a description of the function:def _playlist_format_changed(self):
new_format = False
for n in self.stations:
if n[2] != '':
new_format = True
break
if self.new_format == new_format:
return False
else:
... | [
" Check if we have new or old format\n and report if format has changed\n\n Format type can change by editing encoding,\n deleting a non-utf-8 station etc.\n "
] |
Please provide a description of the function:def save_playlist_file(self, stationFile=''):
if self._playlist_format_changed():
self.dirty_playlist = True
self.new_format = not self.new_format
if stationFile:
st_file = stationFile
else:
st... | [
" Save a playlist\n Create a txt file and write stations in it.\n Then rename it to final target\n\n return 0: All ok\n -1: Error writing file\n -2: Error renaming file\n "
] |
Please provide a description of the function:def _bytes_to_human(self, B):
''' Return the given bytes as a human friendly KB, MB, GB, or TB string '''
KB = float(1024)
MB = float(KB ** 2) # 1,048,576
GB = float(KB ** 3) # 1,073,741,824
TB = float(KB ** 4) # 1,099,511,627,776
... | [] |
Please provide a description of the function:def append_station(self, params, stationFile=''):
if self.new_format:
if stationFile:
st_file = stationFile
else:
st_file = self.stations_file
st_file, ret = self._get_playlist_abspath_from... | [
" Append a station to csv file\n\n return 0: All ok\n -2 - playlist not found\n -3 - negative number specified\n -4 - number not found\n -5: Error writing file\n -6: Error renaming file\n "
] |
Please provide a description of the function:def read_playlists(self):
self.playlists = []
self.selected_playlist = -1
files = glob.glob(path.join(self.stations_dir, '*.csv'))
if len(files) == 0:
return 0, -1
else:
for a_file in files:
a_fi... | [
" get already loaded playlist id "
] |
Please provide a description of the function:def _check_config_file(self, usr):
''' Make sure a config file exists in the config dir '''
package_config_file = path.join(path.dirname(__file__), 'config')
user_config_file = path.join(usr, 'config')
''' restore config from bck file '''
... | [] |
Please provide a description of the function:def save_config(self):
if not self.opts['dirty_config'][1]:
if logger.isEnabledFor(logging.INFO):
logger.info('Config not saved (not modified)')
return 1
txt ='''# PyRadio Configuration File
# Player selection... | [
" Save config file\n\n Creates config.restore (back up file)\n Returns:\n -1: Error saving config\n 0: Config saved successfully\n 1: Config not saved (not modified"
] |
Please provide a description of the function:def initBody(self):
#self.bodyWin.timeout(100)
#self.bodyWin.keypad(1)
self.bodyMaxY, self.bodyMaxX = self.bodyWin.getmaxyx()
self.bodyWin.noutrefresh()
if self.operation_mode == NO_PLAYER_ERROR_MODE:
if self.reque... | [
" Initializes the body/story window ",
"Rypadio is not able to use the player you specified.\n\n This means that either this particular player is not supported\n by PyRadio, or that you have simply misspelled its name.\n\n PyRadio currently supports three players: mpv,... |
Please provide a description of the function:def initFooter(self):
self.footerWin.bkgd(' ', curses.color_pair(7))
self.footerWin.noutrefresh() | [
" Initializes the body/story window "
] |
Please provide a description of the function:def ctrl_c_handler(self, signum, frame):
self.ctrl_c_pressed = True
if self._cnf.dirty_playlist:
self.saveCurrentPlaylist()
self._cnf.save_config() | [
" Try to auto save playlist on exit\n Do not check result!!! ",
" Try to auto save config on exit\n Do not check result!!! "
] |
Please provide a description of the function:def _goto_playing_station(self, changing_playlist=False):
if (self.player.isPlaying() or self.operation_mode == PLAYLIST_MODE) and \
(self.selection != self.playing or changing_playlist):
if changing_playlist:
self.sta... | [
" make sure playing station is visible "
] |
Please provide a description of the function:def setStation(self, number):
# If we press up at the first station, we go to the last one
# and if we press down on the last one we go back to the first one.
if number < 0:
number = len(self.stations) - 1
elif number >= l... | [
" Select the given station number "
] |
Please provide a description of the function:def stopPlayer(self, show_message=True):
try:
self.player.close()
except:
pass
finally:
self.playing = -1
if show_message:
self.log.write('{}: Playback stopped'.format(self._form... | [
" stop player "
] |
Please provide a description of the function:def _show_help(self, txt,
mode_to_set=MAIN_HELP_MODE,
caption=' Help ',
prompt=' Press any key to hide ',
too_small_msg='Window too small to show message',
is_message=False):
sel... | [
" Display a help, info or question window. "
] |
Please provide a description of the function:def _format_playlist_line(self, lineNum, pad, station):
line = "{0}. {1}".format(str(lineNum + self.startPos + 1).rjust(pad), station[0])
f_data = ' [{0}, {1}]'.format(station[2], station[1])
if version_info < (3, 0):
if len(line.... | [
" format playlist line so that if fills self.maxX ",
" this is too long, try to shorten it\n by removing file size ",
" still too long. start removing chars ",
" if too short, pad f_data to the right ",
" this is too long, try to shorten it\n by removing file size ",
... |
Please provide a description of the function:def _print_foreign_playlist_message(self):
self.operation_mode = self.window_mode = NORMAL_MODE
self.refreshBody()
txt='''A playlist by this name:
__"|{0}|"
already exists in the config directory.
... | [
" reset previous message ",
" display new message "
] |
Please provide a description of the function:def _print_foreign_playlist_copy_error(self):
self.operation_mode = self.window_mode = NORMAL_MODE
self.refreshBody()
txt ='''Foreign playlist copying |failed|!
Make sure the file is not open with another
application ... | [
" reset previous message "
] |
Please provide a description of the function:def _align_stations_and_refresh(self, cur_mode):
need_to_scan_playlist = False
self.stations = self._cnf.stations
self.number_of_items = len(self.stations)
if self.number_of_items == 0:
if self.player.isPlayi... | [
" refresh reference ",
" The playlist is empty ",
" Remove selected station ",
" The playlist is not empty ",
" Previous playing station is now invalid\n Need to scan playlist ",
" ok, self.playing found, just find selection ",
" station playing id changed, try previous statio... |
Please provide a description of the function:def _open_playlist(self):
self._get_active_stations()
self.jumpnr = ''
self._random_requested = False
txt = '''Reading playlists. Please wait...'''
self._show_help(txt, NORMAL_MODE, caption=' ', prompt=' ', is_message=True)
... | [
" open playlist "
] |
Please provide a description of the function:def _toggle_transparency(self, changed_from_config_window=False, force_value=None):
if self.window_mode == CONFIG_MODE and not changed_from_config_window:
return
self._theme.toggleTransparency(force_value)
self._cnf.use_transparen... | [
" Toggles theme trasparency.\n\n changed_from_config_window is used to inhibit toggling from within\n Config Window when 'T' is pressed.\n\n force_value will set trasparency if True or False,\n or toggle trasparency if None\n "
] |
Please provide a description of the function:def _print_options_help(self):
for i, x in enumerate(self._help_lines[self.selection]):
if i + 2 == self.maxY:
break
self._win.addstr(i+2, self._second_column, ' ' * (self._second_column - 1), curses.color_pair(5))
... | [
"\n # Uncomment if trouble with help lines\n if logger.isEnabledFor(logging.DEBUG):\n logger.debug('self._num_of_help_lines = {}'.format(self._num_of_help_lines))\n "
] |
Please provide a description of the function:def refresh_win(self, set_encoding=True):
self._fix_geometry()
self.init_window(set_encoding)
self._win.bkgdset(' ', curses.color_pair(3))
self._win.erase()
self._win.box()
self._win.addstr(0,
int((self.max... | [
" set_encoding is False when resizing "
] |
Please provide a description of the function:def _resize(self, init=False):
col, row = self._selection_to_col_row(self.selection)
if not (self.startPos <= row <= self.startPos + self.list_maxY - 1):
while row > self.startPos:
self.startPos += 1
while row < self.st... | [] |
Please provide a description of the function:def refresh_win(self, resizing=False):
#self.init_window(set_encoding)
self._win.bkgdset(' ', curses.color_pair(3))
self._win.erase()
self._win.box()
self._win.addstr(0,
int((self.maxX - len(self._title)) / 2),
... | [
" set_encoding is False when resizing "
] |
Please provide a description of the function:def _read_items(self):
self._items = []
self._items = glob.glob(path.join(self._config_path, '*.csv'))
if len(self._items) == 0:
return 0, -1
else:
self._items.sort()
for i, an_item in enumerate(self._items):
... | [
" get already loaded playlist id "
] |
Please provide a description of the function:def write(self, msg, thread_lock=None, help_msg=False):
if self.cursesScreen:
if thread_lock is not None:
thread_lock.acquire()
self.cursesScreen.erase()
try:
self.msg = msg.strip()
... | [
" msg may or may not be encoded "
] |
Please provide a description of the function:def write_right(self, msg, thread_lock=None):
if self.cursesScreen:
if thread_lock is not None:
thread_lock.acquire()
try:
a_msg = msg.strip()
self.cursesScreen.addstr(0, self.width + 5 ... | [
" msg may or may not be encoded "
] |
Please provide a description of the function:def keypress(self, win, char):
if not self._focused:
return 1
if self.log is not None:
self.log('char = {}\n'.format(char))
if char in (curses.KEY_ENTER, ord('\n'), ord('\r')):
if self._has_his... | [
"\n returns:\n 1: get next char\n 0: exit edit mode, string isvalid\n -1: cancel\n ",
" ENTER ",
" ESCAPE ",
" KEY_RIGHT, Alt-F ",
" KEY_LEFT ",
" KEY_HOME, ^A ",
" KEY_END, ^E ",
" DEL key, ^D ",
" KEY_BACKSPACE ",
" KEY_UP, ^N ",
" KEY_DOWN, ^P ",... |
Please provide a description of the function:def _get_char(self, win, char):
def get_check_next_byte():
char = win.getch()
if 128 <= char <= 191:
return char
else:
raise UnicodeError
bytes = []
if char <= 127:
# 1 b... | [
" no zero byte allowed "
] |
Please provide a description of the function:def _get_history_next(self):
if self._has_history:
ret = self._input_history.return_history(1)
self.string = ret
self._curs_pos = len(ret) | [
" callback function for key down "
] |
Please provide a description of the function:def apply_transformations(collection, transformations, select=None):
''' Apply all transformations to the variables in the collection.
Args:
transformations (list): List of transformations to apply.
select (list): Optional list of names of variables ... | [] |
Please provide a description of the function:def setup(self, steps=None, drop_na=False, **kwargs):
''' Set up the sequence of steps for analysis.
Args:
steps (list): Optional list of steps to set up. Each element
must be either an int giving the index of the step in the
... | [] |
Please provide a description of the function:def setup(self, input_nodes=None, drop_na=False, **kwargs):
''' Set up the Step and construct the design matrix.
Args:
input_nodes (list): Optional list of Node objects produced by
the preceding Step in the analysis. If None, uses... | [] |
Please provide a description of the function:def get_design_matrix(self, names=None, format='long', mode='both',
force=False, sampling_rate='TR', **kwargs):
''' Get design matrix and associated information.
Args:
names (list): Optional list of names of variables to... | [] |
Please provide a description of the function:def get_contrasts(self, names=None, variables=None, **kwargs):
''' Return contrast information for the current block.
Args:
names (list): Optional list of names of contrasts to return. If
None (default), all contrasts are returned... | [] |
Please provide a description of the function:def get_design_matrix(self, names=None, format='long', mode='both',
force=False, sampling_rate='TR', **kwargs):
''' Get design matrix and associated information.
Args:
names (list): Optional list of names of variables to... | [] |
Please provide a description of the function:def get_contrasts(self, names=None, variables=None):
''' Return contrast information for the current block.
Args:
names (list): Optional list of names of contrasts to return. If
None (default), all contrasts are returned.
... | [] |
Please provide a description of the function:def remove_duplicates(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] | [
"\n Return unique elements from list while preserving order.\n From https://stackoverflow.com/a/480227/2589328\n "
] |
Please provide a description of the function:def list_to_str(lst):
if len(lst) == 1:
str_ = lst[0]
elif len(lst) == 2:
str_ = ' and '.join(lst)
elif len(lst) > 2:
str_ = ', '.join(lst[:-1])
str_ += ', and {0}'.format(lst[-1])
else:
raise ValueError('List of l... | [
"\n Turn a list into a comma- and/or and-separated string.\n\n Parameters\n ----------\n lst : :obj:`list`\n A list of strings to join into a single string.\n\n Returns\n -------\n str_ : :obj:`str`\n A string with commas and/or ands separating th elements from ``lst``.\n\n "
] |
Please provide a description of the function:def get_slice_info(slice_times):
# Slice order
slice_times = remove_duplicates(slice_times)
slice_order = sorted(range(len(slice_times)), key=lambda k: slice_times[k])
if slice_order == range(len(slice_order)):
slice_order_name = 'sequential asce... | [
"\n Extract slice order from slice timing info.\n\n TODO: Be more specific with slice orders.\n Currently anything where there's some kind of skipping is interpreted as\n interleaved of some kind.\n\n Parameters\n ----------\n slice_times : array-like\n A list of slice times in seconds o... |
Please provide a description of the function:def get_seqstr(config, metadata):
seq_abbrs = metadata.get('ScanningSequence', '').split('_')
seqs = [config['seq'].get(seq, seq) for seq in seq_abbrs]
variants = [config['seqvar'].get(var, var) for var in \
metadata.get('SequenceVariant', ''... | [
"\n Extract and reformat imaging sequence(s) and variant(s) into pretty\n strings.\n\n Parameters\n ----------\n config : :obj:`dict`\n A dictionary with relevant information regarding sequences, sequence\n variants, phase encoding directions, and task names.\n metadata : :obj:`dict`... |
Please provide a description of the function:def get_sizestr(img):
n_x, n_y, n_slices = img.shape[:3]
import numpy as np
voxel_dims = np.array(img.header.get_zooms()[:3])
matrix_size = '{0}x{1}'.format(num_to_str(n_x), num_to_str(n_y))
voxel_size = 'x'.join([num_to_str(s) for s in voxel_dims])
... | [
"\n Extract and reformat voxel size, matrix size, field of view, and number of\n slices into pretty strings.\n\n Parameters\n ----------\n img : :obj:`nibabel.Nifti1Image`\n Image from scan from which to derive parameters.\n\n Returns\n -------\n n_slices : :obj:`int`\n Number ... |
Please provide a description of the function:def parse_file_entities(filename, entities=None, config=None,
include_unmatched=False):
# Load Configs if needed
if entities is None:
if config is None:
config = ['bids', 'derivatives']
config = [Config.load... | [
" Parse the passed filename for entity/value pairs.\n\n Args:\n filename (str): The filename to parse for entity values\n entities (list): An optional list of Entity instances to use in\n extraction. If passed, the config argument is ignored.\n config (str, Config, list): One or m... |
Please provide a description of the function:def add_config_paths(**kwargs):
for k, path in kwargs.items():
if not os.path.exists(path):
raise ValueError(
'Configuration file "{}" does not exist'.format(k))
if k in cf.get_option('config_paths'):
raise Va... | [
" Add to the pool of available configuration files for BIDSLayout.\n\n Args:\n kwargs: dictionary specifying where to find additional config files.\n Keys are names, values are paths to the corresponding .json file.\n\n Example:\n > add_config_paths(my_config='/path/to/config')\n ... |
Please provide a description of the function:def parse_file_entities(self, filename, scope='all', entities=None,
config=None, include_unmatched=False):
''' Parse the passed filename for entity/value pairs.
Args:
filename (str): The filename to parse for entity va... | [] |
Please provide a description of the function:def add_derivatives(self, path, **kwargs):
''' Add BIDS-Derivatives datasets to tracking.
Args:
path (str, list): One or more paths to BIDS-Derivatives datasets.
Each path can point to either a derivatives/ directory
... | [] |
Please provide a description of the function:def get(self, return_type='object', target=None, extensions=None,
scope='all', regex_search=False, defined_fields=None,
absolute_paths=None,
**kwargs):
# Warn users still expecting 0.6 behavior
if 'type' in kwargs... | [
"\n Retrieve files and/or metadata from the current Layout.\n\n Args:\n return_type (str): Type of result to return. Valid values:\n 'object' (default): return a list of matching BIDSFile objects.\n 'file': return a list of matching filenames.\n ... |
Please provide a description of the function:def get_file(self, filename, scope='all'):
''' Returns the BIDSFile object with the specified path.
Args:
filename (str): The path of the file to retrieve. Must be either
an absolute path, or relative to the root of this BIDSLayou... | [] |
Please provide a description of the function:def get_collections(self, level, types=None, variables=None, merge=False,
sampling_rate=None, skip_empty=False, **kwargs):
from bids.variables import load_variables
index = load_variables(self, types=types, levels=level,
... | [
"Return one or more variable Collections in the BIDS project.\n\n Args:\n level (str): The level of analysis to return variables for. Must be\n one of 'run', 'session', 'subject', or 'dataset'.\n types (str, list): Types of variables to retrieve. All valid values\n ... |
Please provide a description of the function:def get_metadata(self, path, include_entities=False, **kwargs):
f = self.get_file(path)
# For querying efficiency, store metadata in the MetadataIndex cache
self.metadata_index.index_file(f.path)
if include_entities:
en... | [
"Return metadata found in JSON sidecars for the specified file.\n\n Args:\n path (str): Path to the file to get metadata for.\n include_entities (bool): If True, all available entities extracted\n from the filename (rather than JSON sidecars) are included in\n ... |
Please provide a description of the function:def get_bval(self, path, **kwargs):
result = self.get_nearest(path, extensions='bval', suffix='dwi',
all_=True, **kwargs)
return listify(result)[0] | [
" Get bval file for passed path. "
] |
Please provide a description of the function:def get_fieldmap(self, path, return_list=False):
fieldmaps = self._get_fieldmaps(path)
if return_list:
return fieldmaps
else:
if len(fieldmaps) == 1:
return fieldmaps[0]
elif len(fieldmaps)... | [
" Get fieldmap(s) for specified path. "
] |
Please provide a description of the function:def get_tr(self, derivatives=False, **selectors):
# Constrain search to functional images
selectors.update(suffix='bold', datatype='func')
scope = None if derivatives else 'raw'
images = self.get(extensions=['.nii', '.nii.gz'], scope=... | [
" Returns the scanning repetition time (TR) for one or more runs.\n\n Args:\n derivatives (bool): If True, also checks derivatives images.\n selectors: Optional keywords used to constrain the selected runs.\n Can be any arguments valid for a .get call (e.g., BIDS entities... |
Please provide a description of the function:def build_path(self, source, path_patterns=None, strict=False, scope='all'):
''' Constructs a target filename for a file or dictionary of entities.
Args:
source (str, BIDSFile, dict): The source data to use to construct
the new fi... | [] |
Please provide a description of the function:def copy_files(self, files=None, path_patterns=None, symbolic_links=True,
root=None, conflicts='fail', **kwargs):
_files = self.get(return_type='objects', **kwargs)
if files:
_files = list(set(files).intersection(_files... | [
"\n Copies one or more BIDSFiles to new locations defined by each\n BIDSFile's entities and the specified path_patterns.\n\n Args:\n files (list): Optional list of BIDSFile objects to write out. If\n none provided, use files from running a get() query using\n ... |
Please provide a description of the function:def write_contents_to_file(self, entities, path_patterns=None,
contents=None, link_to=None,
content_mode='text', conflicts='fail',
strict=False):
path = self.build_p... | [
"\n Write arbitrary data to a file defined by the passed entities and\n path patterns.\n\n Args:\n entities (dict): A dictionary of entities, with Entity names in\n keys and values for the desired file in values.\n path_patterns (list): Optional path pattern... |
Please provide a description of the function:def index_file(self, f, overwrite=False):
if isinstance(f, six.string_types):
f = self.layout.get_file(f)
if f.path in self.file_index and not overwrite:
return
if 'suffix' not in f.entities: # Skip files without su... | [
"Index metadata for the specified file.\n\n Args:\n f (BIDSFile, str): A BIDSFile or path to an indexed file.\n overwrite (bool): If True, forces reindexing of the file even if\n an entry already exists.\n "
] |
Please provide a description of the function:def search(self, files=None, defined_fields=None, **kwargs):
if defined_fields is None:
defined_fields = []
all_keys = set(defined_fields) | set(kwargs.keys())
if not all_keys:
raise ValueError("At least one field to... | [
"Search files in the layout by metadata fields.\n\n Args:\n files (list): Optional list of names of files to search. If None,\n all files in the layout are scanned.\n defined_fields (list): Optional list of names of fields that must\n be defined in the JSON... |
Please provide a description of the function:def load_variables(layout, types=None, levels=None, skip_empty=True,
dataset=None, scope='all', **kwargs):
''' A convenience wrapper for one or more load_*_variables() calls.
Args:
layout (BIDSLayout): BIDSLayout containing variable files.... | [] |
Please provide a description of the function:def _load_time_variables(layout, dataset=None, columns=None, scan_length=None,
drop_na=True, events=True, physio=True, stim=True,
regressors=True, skip_empty=True, scope='all',
**selectors):
''' L... | [] |
Please provide a description of the function:def _load_tsv_variables(layout, suffix, dataset=None, columns=None,
prepend_type=False, scope='all', **selectors):
''' Reads variables from scans.tsv, sessions.tsv, and participants.tsv.
Args:
layout (BIDSLayout): The BIDSLayout to us... | [] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.