_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q251700
add_mongo_config_simple
train
def add_mongo_config_simple(app, connection_string, collection_name): """ Configure the app to use MongoDB. :param app: Flask Application :type app: Flask :param connection_string: in format host:port:database or database (default: sacred) :type connection_string: str :param co...
python
{ "resource": "" }
q251701
add_mongo_config_with_uri
train
def add_mongo_config_with_uri(app, connection_string_uri, database_name, collection_name): """ Configure PyMongo with a MongoDB connection string. :param app: Flask application :param connection_string_uri: MongoDB connection string :param database_name: Sacred databas...
python
{ "resource": "" }
q251702
stop_all_tensorboards
train
def stop_all_tensorboards(): """Terminate all TensorBoard instances.""" for process in Process.instances: print("Process '%s', running %d" % (process.command[0], process.is_running())) if process.is_running() and process.command[0] == "tensorboard": ...
python
{ "resource": "" }
q251703
run_tensorboard
train
def run_tensorboard(logdir, listen_on="0.0.0.0", port=0, tensorboard_args=None, timeout=10): """ Launch a new TensorBoard instance. :param logdir: Path to a TensorFlow summary directory :param listen_on: The IP address TensorBoard should listen on. :param port: Port number to listen on. 0 for a ran...
python
{ "resource": "" }
q251704
parse_port_from_tensorboard_output
train
def parse_port_from_tensorboard_output(tensorboard_output: str) -> int: """ Parse tensorboard port from its outputted message. :param tensorboard_output: Output message of Tensorboard in format TensorBoard 1.8.0 at http://martin-VirtualBox:36869 :return: Returns the port TensorBoard is listening on...
python
{ "resource": "" }
q251705
PyMongoDataAccess.connect
train
def connect(self): """Initialize the database connection.""" self._client = self._create_client() self._db = getattr(self._client, self._db_name) self._generic_dao = GenericDAO(self._client, self._db_name)
python
{ "resource": "" }
q251706
PyMongoDataAccess.build_data_access
train
def build_data_access(host, port, database_name, collection_name): """ Create data access gateway. :param host: The database server to connect to. :type host: str :param port: Database port. :type port: int :param database_name: Database name. :type datab...
python
{ "resource": "" }
q251707
run_tensorboard
train
def run_tensorboard(run_id, tflog_id): """Launch TensorBoard for a given run ID and log ID of that run.""" data = current_app.config["data"] # optimisticaly suppose the run exists... run = data.get_run_dao().get(run_id) base_dir = Path(run["experiment"]["base_dir"]) log_dir = Path(run["info"]["t...
python
{ "resource": "" }
q251708
MongoMetricsDAO.get
train
def get(self, run_id, metric_id): """ Read a metric of the given id and run. The returned object has the following format (timestamps are datetime objects). .. code:: {"steps": [0,1,20,40,...], "timestamps": [timestamp1,timestamp2,timestamp3,...], ...
python
{ "resource": "" }
q251709
MongoMetricsDAO.delete
train
def delete(self, run_id): """ Delete all metrics belonging to the given run. :param run_id: ID of the Run that the metric belongs to. """ self.generic_dao.delete_record( self.metrics_collection_name, {"run_id": self._parse_run_id(run_id)})
python
{ "resource": "" }
q251710
RunFacade.delete_run
train
def delete_run(self, run_id): """ Delete run of the given run_id. :raise NotImplementedError If not supported by the backend. :raise DataSourceError General data source error. :raise NotFoundError The run was not found. (Some backends may succeed even if the run does not exist. ...
python
{ "resource": "" }
q251711
FileStoreRunDAO.get_runs
train
def get_runs(self, sort_by=None, sort_direction=None, start=0, limit=None, query={"type": "and", "filters": []}): """ Return all runs in the file store. If a run is corrupt, e.g. missing files, it is skipped. :param sort_by: NotImplemented :param sort_direction: NotImplemented...
python
{ "resource": "" }
q251712
FileStoreRunDAO.get
train
def get(self, run_id): """ Return the run associated with a particular `run_id`. :param run_id: :return: dict :raises FileNotFoundError """ config = _read_json(_path_to_config(self.directory, run_id)) run = _read_json(_path_to_run(self.directory, run_id))...
python
{ "resource": "" }
q251713
get_metric
train
def get_metric(run_id, metric_id): """ Get a specific Sacred metric from the database. Returns a JSON response or HTTP 404 if not found. Issue: https://github.com/chovanecm/sacredboard/issues/58 """ data = current_app.config["data"] # type: DataStorage dao = data.get_metrics_dao() metr...
python
{ "resource": "" }
q251714
ServerRunner.initialize
train
def initialize(self, app: Flask, app_config): """ Prepare the server to run and determine the port. :param app: The Flask Application. :param app_config: Configuration dictionary. This module uses the `debug` (`True`/`False`) and `http.port` attributes. """ debug...
python
{ "resource": "" }
q251715
api_run_delete
train
def api_run_delete(run_id): """Delete the given run and corresponding entities.""" data = current_app.config["data"] # type: DataStorage RunFacade(data).delete_run(run_id) return "DELETED run %s" % run_id
python
{ "resource": "" }
q251716
api_run_get
train
def api_run_get(run_id): """Return a single run as a JSON object.""" data = current_app.config["data"] run = data.get_run_dao().get(run_id) records_total = 1 if run is not None else 0 if records_total == 0: return Response( render_template( "api/error.js", ...
python
{ "resource": "" }
q251717
parse_int_arg
train
def parse_int_arg(name, default): """Return a given URL parameter as int or return the default value.""" return default if request.args.get(name) is None \ else int(request.args.get(name))
python
{ "resource": "" }
q251718
parse_query_filter
train
def parse_query_filter(): """Parse the Run query filter from the URL as a dictionary.""" query_string = request.args.get("queryFilter") if query_string is None: return {"type": "and", "filters": []} query = json.loads(query_string) assert type(query) == dict assert type(query.get("type")...
python
{ "resource": "" }
q251719
get_runs
train
def get_runs(): """Get all runs, sort it and return a response.""" data = current_app.config["data"] draw = parse_int_arg("draw", 1) start = parse_int_arg("start", 0) length = parse_int_arg("length", -1) length = length if length >= 0 else None order_column = request.args.get("order[0][colum...
python
{ "resource": "" }
q251720
FileStoreFilesDAO.get
train
def get(self, file_id: str) -> [typing.BinaryIO, str, datetime.datetime]: """Return the file identified by a file_id string, its file name and upload date.""" raise NotImplementedError("Downloading files for downloading files in FileStore has not been implemented yet.")
python
{ "resource": "" }
q251721
timediff
train
def timediff(time): """Return the difference in seconds between now and the given time.""" now = datetime.datetime.utcnow() diff = now - time diff_sec = diff.total_seconds() return diff_sec
python
{ "resource": "" }
q251722
last_line
train
def last_line(text): """ Get the last meaningful line of the text, that is the last non-empty line. :param text: Text to search the last line :type text: str :return: :rtype: str """ last_line_of_text = "" while last_line_of_text == "" and len(text) > 0: last_line_start = te...
python
{ "resource": "" }
q251723
dump_json
train
def dump_json(obj): """Dump Python object as JSON string.""" return simplejson.dumps(obj, ignore_nan=True, default=json_util.default)
python
{ "resource": "" }
q251724
Process.terminate
train
def terminate(self, wait=False): """Terminate the process.""" if self.proc is not None: self.proc.stdout.close() try: self.proc.terminate() except ProcessLookupError: pass if wait: self.proc.wait()
python
{ "resource": "" }
q251725
Process.terminate_all
train
def terminate_all(wait=False): """ Terminate all processes. :param wait: Wait for each to terminate :type wait: bool :return: :rtype: """ for instance in Process.instances: if instance.is_running(): instance.terminate(wait)
python
{ "resource": "" }
q251726
calc_worklog
train
def calc_worklog(stdout=Ellipsis, stderr=Ellipsis, verbose=False): ''' calc_worklog constructs the worklog from the stdout, stderr, stdin, and verbose arguments. ''' try: cols = int(os.environ['COLUMNS']) except Exception: cols = 80 return pimms.worklog(columns=cols, stdout=stdout, stderr=stderr...
python
{ "resource": "" }
q251727
calc_subject
train
def calc_subject(argv, worklog): ''' calc_subject converts a subject_id into a subject object. Afferent parameters: @ argv The FreeSurfer subject name(s), HCP subject ID(s), or path(s) of the subject(s) to which the atlas should be applied. ''' if len(argv) == 0: raise ValueEr...
python
{ "resource": "" }
q251728
calc_atlases
train
def calc_atlases(worklog, atlas_subject_id='fsaverage'): ''' cacl_atlases finds all available atlases in the possible subject directories of the given atlas subject. In order to be a template, it must either be a collection of files (either mgh/mgz or FreeSurfer curv/morph-data files) named as '<he...
python
{ "resource": "" }
q251729
calc_filemap
train
def calc_filemap(atlas_properties, subject, atlas_version_tags, worklog, output_path=None, overwrite=False, output_format='mgz', create_directory=False): ''' calc_filemap is a calculator that converts the atlas properties nested-map into a single-depth map whose keys are filenames and whose...
python
{ "resource": "" }
q251730
ImageType.parse_type
train
def parse_type(self, hdat, dataobj=None): ''' Parses the dtype out of the header data or the array, depending on which is given; if both, then the header-data overrides the array; if neither, then np.float32. ''' try: dataobj = dataobj.dataobj except Exception: pass ...
python
{ "resource": "" }
q251731
ImageType.parse_affine
train
def parse_affine(self, hdat, dataobj=None): ''' Parses the affine out of the given header data and yields it. ''' if 'affine' in hdat: return to_affine(hdat['affine']) else: return to_affine(self.default_affine())
python
{ "resource": "" }
q251732
_parse_field_arguments
train
def _parse_field_arguments(arg, faces, edges, coords): '''See mesh_register.''' if not hasattr(arg, '__iter__'): raise RuntimeError('field argument must be a list-like collection of instructions') pot = [_parse_field_argument(instruct, faces, edges, coords) for instruct in arg] # make a new Pote...
python
{ "resource": "" }
q251733
retino_colors
train
def retino_colors(vcolorfn, *args, **kwargs): 'See eccen_colors, angle_colors, sigma_colors, and varea_colors.' if len(args) == 0: def _retino_color_pass(*args, **new_kwargs): return retino_colors(vcolorfn, *args, **{k:(new_kwargs[k] if k in new_kwargs else k...
python
{ "resource": "" }
q251734
_load_fsLR_atlasroi
train
def _load_fsLR_atlasroi(filename, data): ''' Loads the appropriate atlas for the given data; data may point to a cifti file whose atlas is needed or to an atlas file. ''' (fdir, fnm) = os.path.split(filename) fparts = fnm.split('.') atl = fparts[-3] if atl in _load_fsLR_atlasroi.atlases:...
python
{ "resource": "" }
q251735
_load_fsLR_atlasroi_for_size
train
def _load_fsLR_atlasroi_for_size(size, sid=100610): ''' Loads the appropriate atlas for the given size of data; size should be the number of stored vertices and sub-corticel voxels stored in the cifti file. ''' from .core import subject # it doesn't matter what subject we request, so just use an...
python
{ "resource": "" }
q251736
calc_arguments
train
def calc_arguments(args): ''' calc_arguments is a calculator that parses the command-line arguments for the registration command and produces the subject, the model, the log function, and the additional options. ''' (args, opts) = _retinotopy_parser(args) # We do some of the options right here.....
python
{ "resource": "" }
q251737
calc_retinotopy
train
def calc_retinotopy(note, error, subject, clean, run_lh, run_rh, invert_rh_angle, max_in_eccen, min_in_eccen, angle_lh_file, theta_lh_file, eccen_lh_file, rho_lh_file, weight_lh_file, radius_lh_file, angle_rh_file, theta...
python
{ "resource": "" }
q251738
calc_registrations
train
def calc_registrations(note, error, cortices, model, model_sym, weight_min, scale, prior, max_out_eccen, max_steps, max_step_size, radius_weight, field_sign_weight, resample, invert_rh_angle, part_vol_correct): ''' calc_registrations is the ca...
python
{ "resource": "" }
q251739
save_surface_files
train
def save_surface_files(note, error, registrations, subject, no_surf_export, no_reg_export, surface_format, surface_path, angle_tag, eccen_tag, label_tag, radius_tag, registration_name): ''' save_surface_files is the calculator that saves the registration data out as...
python
{ "resource": "" }
q251740
save_volume_files
train
def save_volume_files(note, error, registrations, subject, no_vol_export, volume_format, volume_path, angle_tag, eccen_tag, label_tag, radius_tag): ''' save_volume_files is the calculator that saves the registration data out as volume files, which are put back in ...
python
{ "resource": "" }
q251741
calc_empirical_retinotopy
train
def calc_empirical_retinotopy(cortex, polar_angle=None, eccentricity=None, pRF_radius=None, weight=None, eccentricity_range=None, weight_min=0, invert_rh_angle=False, partial_voluming_correction=False...
python
{ "resource": "" }
q251742
calc_model
train
def calc_model(cortex, model_argument, model_hemi=Ellipsis, radius=np.pi/3): ''' calc_model loads the appropriate model object given the model argument, which may given the name of the model or a model object itself. Required afferent parameters: @ model_argument Must be either a RegisteredRetino...
python
{ "resource": "" }
q251743
calc_anchors
train
def calc_anchors(preregistration_map, model, model_hemi, scale=1, sigma=Ellipsis, radius_weight=0, field_sign_weight=0, invert_rh_field_sign=False): ''' calc_anchors is a calculator that creates a set of anchor instructions for a registration. Required afferent parameters:...
python
{ "resource": "" }
q251744
calc_registration
train
def calc_registration(preregistration_map, anchors, max_steps=2000, max_step_size=0.05, method='random'): ''' calc_registration is a calculator that creates the registration coordinates. ''' # if max steps is a tuple (max, stride) then a trajectory is saved into # the registere...
python
{ "resource": "" }
q251745
calc_prediction
train
def calc_prediction(registered_map, preregistration_mesh, native_mesh, model): ''' calc_registration_prediction is a pimms calculator that creates the both the prediction and the registration_prediction, both of which are pimms itables including the fields 'polar_angle', 'eccentricity', and 'visual_area...
python
{ "resource": "" }
q251746
Market.ticker
train
def ticker(self, currency="", **kwargs): """ This endpoint displays cryptocurrency ticker data in order of rank. The maximum number of results per call is 100. Pagination is possible by using the start and limit parameters. GET /ticker/ Optional parameters: (int) start - return results from rank [sta...
python
{ "resource": "" }
q251747
_surpress_formatting_errors
train
def _surpress_formatting_errors(fn): """ I know this is dangerous and the wrong way to solve the problem, but when using both row and columns summaries it's easier to just swallow errors so users can format their tables how they need. """ @wraps(fn) def inner(*args, **kwargs): try: ...
python
{ "resource": "" }
q251748
_format_numer
train
def _format_numer(number_format, prefix='', suffix=''): """Format a number to a string.""" @_surpress_formatting_errors def inner(v): if isinstance(v, Number): return ("{{}}{{:{}}}{{}}" .format(number_format) .format(prefix, v, suffix)) els...
python
{ "resource": "" }
q251749
as_percent
train
def as_percent(precision=2, **kwargs): """Convert number to percentage string. Parameters: ----------- :param v: numerical value to be converted :param precision: int decimal places to round to """ if not isinstance(precision, Integral): raise TypeError("Precision must be an...
python
{ "resource": "" }
q251750
as_unit
train
def as_unit(unit, precision=2, location='suffix'): """Convert value to unit. Parameters: ----------- :param v: numerical value :param unit: string of unit :param precision: int decimal places to round to :param location: 'prefix' or 'suffix' representing where the currency s...
python
{ "resource": "" }
q251751
Aggregate.apply
train
def apply(self, df): """Compute aggregate over DataFrame""" if self.subset: if _axis_is_rows(self.axis): df = df[self.subset] if _axis_is_cols(self.axis): df = df.loc[self.subset] result = df.agg(self.func, axis=self.axis, *self.args, **s...
python
{ "resource": "" }
q251752
Formatter.apply
train
def apply(self, styler): """Apply Summary over Pandas Styler""" return styler.format(self.formatter, *self.args, **self.kwargs)
python
{ "resource": "" }
q251753
PrettyPandas._apply_summaries
train
def _apply_summaries(self): """Add all summary rows and columns.""" def as_frame(r): if isinstance(r, pd.Series): return r.to_frame() else: return r df = self.data if df.index.nlevels > 1: raise ValueError( ...
python
{ "resource": "" }
q251754
PrettyPandas.style
train
def style(self): """Add summaries and convert to Pandas Styler""" row_titles = [a.title for a in self._cleaned_summary_rows] col_titles = [a.title for a in self._cleaned_summary_cols] row_ix = pd.IndexSlice[row_titles, :] col_ix = pd.IndexSlice[:, col_titles] def handle_...
python
{ "resource": "" }
q251755
PrettyPandas.summary
train
def summary(self, func=methodcaller('sum'), title='Total', axis=0, subset=None, *args, **kwargs): """Add multiple summary rows or columns to the dataframe. Parameters ---------- :param func: ...
python
{ "resource": "" }
q251756
PrettyPandas.as_percent
train
def as_percent(self, precision=2, *args, **kwargs): """Format subset as percentages :param precision: Decimal precision :param subset: Pandas subset """ f = Formatter(as_percent(precision), args, kwargs) return self._add_formatter(f)
python
{ "resource": "" }
q251757
PrettyPandas.as_currency
train
def as_currency(self, currency='USD', locale=LOCALE_OBJ, *args, **kwargs): """Format subset as currency :param currency: Currency :param locale: Babel locale for currency formatting :param subset: Pandas subset """ f = Formatter( as_currency(currency=currency...
python
{ "resource": "" }
q251758
PrettyPandas.as_unit
train
def as_unit(self, unit, location='suffix', *args, **kwargs): """Format subset as with units :param unit: string to use as unit :param location: prefix or suffix :param subset: Pandas subset """ f = Formatter( as_unit(unit, location=location), args...
python
{ "resource": "" }
q251759
EventBasedMetrics.validate_onset
train
def validate_onset(reference_event, estimated_event, t_collar=0.200): """Validate estimated event based on event onset Parameters ---------- reference_event : dict Reference event. estimated_event: dict Estimated event. t_collar : float > 0, sec...
python
{ "resource": "" }
q251760
EventBasedMetrics.validate_offset
train
def validate_offset(reference_event, estimated_event, t_collar=0.200, percentage_of_length=0.5): """Validate estimated event based on event offset Parameters ---------- reference_event : dict Reference event. estimated_event : dict Estimated event. ...
python
{ "resource": "" }
q251761
load_event_list
train
def load_event_list(filename, **kwargs): """Load event list from csv formatted text-file Supported formats (see more `dcase_util.containers.MetaDataContainer.load()` method): - [event onset (float >= 0)][delimiter][event offset (float >= 0)] - [event onset (float >= 0)][delimiter][event offset (float ...
python
{ "resource": "" }
q251762
load_scene_list
train
def load_scene_list(filename, **kwargs): """Load scene list from csv formatted text-file Supported formats (see more `dcase_util.containers.MetaDataContainer.load()` method): - [filename][delimiter][scene label] - [filename][delimiter][segment start (float >= 0)][delimiter][segment stop (float >= 0)][...
python
{ "resource": "" }
q251763
load_file_pair_list
train
def load_file_pair_list(filename): """Load file pair list csv formatted text-file Format is [reference_file][delimiter][estimated_file] Supported delimiters: ``,``, ``;``, ``tab`` Example of file-list:: office_snr0_high_v2.txt office_snr0_high_v2_detected.txt office_snr0_med_v2.txt o...
python
{ "resource": "" }
q251764
SceneClassificationMetrics.class_wise_accuracy
train
def class_wise_accuracy(self, scene_label): """Class-wise accuracy Returns ------- dict results in a dictionary format """ if len(self.accuracies_per_class.shape) == 2: return { 'accuracy': float(numpy.mean(self.accuracies_per_cl...
python
{ "resource": "" }
q251765
unique_scene_labels
train
def unique_scene_labels(scene_list): """Find the unique scene labels Parameters ---------- scene_list : list, shape=(n,) A list containing scene dicts Returns ------- labels: list, shape=(n,) Unique labels in alphabetical order """ if isinstance(scene_list, dcase_u...
python
{ "resource": "" }
q251766
event_list_to_event_roll
train
def event_list_to_event_roll(source_event_list, event_label_list=None, time_resolution=0.01): """Convert event list into event roll, binary activity matrix Parameters ---------- source_event_list : list, shape=(n,) A list containing event dicts event_label_list : list, shape=(k,) or None ...
python
{ "resource": "" }
q251767
pad_event_roll
train
def pad_event_roll(event_roll, length): """Pad event roll's length to given length Parameters ---------- event_roll: np.ndarray, shape=(m,k) Event roll length : int Length to be padded Returns ------- event_roll: np.ndarray, shape=(m,k) Padded event roll "...
python
{ "resource": "" }
q251768
match_event_roll_lengths
train
def match_event_roll_lengths(event_roll_a, event_roll_b, length=None): """Fix the length of two event rolls Parameters ---------- event_roll_a: np.ndarray, shape=(m1,k) Event roll A event_roll_b: np.ndarray, shape=(m2,k) Event roll B length: int, optional Length of the...
python
{ "resource": "" }
q251769
filter_event_list
train
def filter_event_list(event_list, scene_label=None, event_label=None, filename=None): """Filter event list based on given fields Parameters ---------- event_list : list, shape=(n,) A list containing event dicts scene_label : str Scene label event_label : str Event labe...
python
{ "resource": "" }
q251770
unique_files
train
def unique_files(event_list): """Find the unique files Parameters ---------- event_list : list or dcase_util.containers.MetaDataContainer A list containing event dicts Returns ------- list Unique filenames in alphabetical order """ if isinstance(event_list, dcase_...
python
{ "resource": "" }
q251771
unique_event_labels
train
def unique_event_labels(event_list): """Find the unique event labels Parameters ---------- event_list : list or dcase_util.containers.MetaDataContainer A list containing event dicts Returns ------- list Unique labels in alphabetical order """ if isinstance(event_l...
python
{ "resource": "" }
q251772
YTActions.__getChannelId
train
def __getChannelId(self): """ Obtain channel id for channel name, if present in ``self.search_params``. """ if not self.search_params.get("channelId"): return api_fixed_url = "https://www.googleapis.com/youtube/v3/channels?part=id&maxResults=1&fields=items%2Fid&" ...
python
{ "resource": "" }
q251773
YTActions.__searchParser
train
def __searchParser(self, query): """ Parse `query` for advanced search options. Parameters ---------- query : str Search query to parse. Besides a search query, user can specify additional search parameters and YTFS specific options. Syntax: ...
python
{ "resource": "" }
q251774
YTActions.__search
train
def __search(self, pt=""): """ Method responsible for searching using YouTube API. Parameters ---------- pt : str Token of search results page. If ``None``, then the first page is downloaded. Returns ------- results : dict Parsed...
python
{ "resource": "" }
q251775
YTActions.clean
train
def clean(self): """Clear the data. For each ``YTStor`` object present in this object ``clean`` method is executed.""" for s in self.visible_files.values(): s.clean() for s in [sub[1][x] for sub in self.avail_files.values() for x in sub[1]]: # Double list comprehensions aren't very...
python
{ "resource": "" }
q251776
YTStor.obtainInfo
train
def obtainInfo(self): """ Method for obtaining information about the movie. """ try: info = self.ytdl.extract_info(self.yid, download=False) except youtube_dl.utils.DownloadError: raise ConnectionError if not self.preferences['stream']: ...
python
{ "resource": "" }
q251777
YTStor.registerHandler
train
def registerHandler(self, fh): # Do I even need that? possible FIXME. """ Register new file descriptor. Parameters ---------- fh : int File descriptor. """ self.fds.add(fh) self.atime = int(time()) # update access time self.lock.acq...
python
{ "resource": "" }
q251778
YTStor.read
train
def read(self, offset, length, fh): """ Read data. Method returns data instantly, if they're avaialable and in ``self.safe_range``. Otherwise data is downloaded and then returned. Parameters ---------- offset : int Read offset length : int ...
python
{ "resource": "" }
q251779
YTStor.clean
train
def clean(self): """ Clear data. Explicitly close ``self.data`` if object is unused. """ self.closing = True # schedule for closing. if not self.fds: self.data.close()
python
{ "resource": "" }
q251780
YTStor.unregisterHandler
train
def unregisterHandler(self, fh): """ Unregister a file descriptor. Clean data, if such operation has been scheduled. Parameters ---------- fh : int File descriptor. """ try: self.fds.remove(fh) except KeyError: pass ...
python
{ "resource": "" }
q251781
fd_dict.push
train
def push(self, yts): """ Search for, add and return new file descriptor. Parameters ---------- yts : YTStor-obj or None ``YTStor`` object for which we want to allocate a descriptor or ``None``, if we allocate descriptor for a control file. Retur...
python
{ "resource": "" }
q251782
YTFS.__pathToTuple
train
def __pathToTuple(self, path): """ Convert directory or file path to its tuple identifier. Parameters ---------- path : str Path to convert. It can look like /, /directory, /directory/ or /directory/filename. Returns ------- tup_id : tuple ...
python
{ "resource": "" }
q251783
YTFS.__exists
train
def __exists(self, p): """ Check if file of given path exists. Parameters ---------- p : str or tuple Path or tuple identifier. Returns ------- exists : bool ``True``, if file exists. Otherwise ``False``. """ try...
python
{ "resource": "" }
q251784
YTFS._pathdec
train
def _pathdec(method): """ Decorator that replaces string `path` argument with its tuple identifier. Parameters ---------- method : function Function/method to decorate. Returns ------- mod : function Function/method after decarot...
python
{ "resource": "" }
q251785
YTFS.getattr
train
def getattr(self, tid, fh=None): """ File attributes. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. fh : int File descriptor. Unnecessary, therefore ignored. ...
python
{ "resource": "" }
q251786
YTFS.readdir
train
def readdir(self, tid, fh): """ Read directory contents. Lists visible elements of ``YTActions`` object. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. fh : int F...
python
{ "resource": "" }
q251787
YTFS.mkdir
train
def mkdir(self, tid, mode): """ Directory creation. Search is performed. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. mode : int Ignored. """ p...
python
{ "resource": "" }
q251788
YTFS.rename
train
def rename(self, old, new): """ Directory renaming support. Needed because many file managers create directories with default names, wich makes it impossible to perform a search without CLI. Name changes for files are not allowed, only for directories. Parameters ------...
python
{ "resource": "" }
q251789
YTFS.rmdir
train
def rmdir(self, tid): """ Directory removal. ``YTActions`` object under `tid` is told to clean all data, and then it is deleted. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. ...
python
{ "resource": "" }
q251790
YTFS.open
train
def open(self, tid, flags): """ File open. ``YTStor`` object associated with this file is initialised and written to ``self.fds``. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. ...
python
{ "resource": "" }
q251791
YTFS.write
train
def write(self, tid, data, offset, fh): """ Write operation. Applicable only for control files - updateResults is called. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. data ...
python
{ "resource": "" }
q251792
YTFS.release
train
def release(self, tid, fh): """ Close file. Descriptor is removed from ``self.fds``. Parameters ---------- tid : str Path to file. Ignored. fh : int File descriptor to release. """ try: try: self.fds[f...
python
{ "resource": "" }
q251793
range_t.__match_l
train
def __match_l(self, k, _set): """ Method for searching subranges from `_set` that overlap on `k` range. Parameters ---------- k : tuple or list or range Range for which we search overlapping subranges from `_set`. _set : set Subranges set. ...
python
{ "resource": "" }
q251794
range_t.contains
train
def contains(self, val): """ Check if given value or range is present. Parameters ---------- val : int or tuple or list or range Range or integer being checked. Returns ------- retlen : int Length of overlapping with `val` subran...
python
{ "resource": "" }
q251795
range_t.__add
train
def __add(self, val): """ Helper method for range addition. It is allowed to add only one compact subrange or ``range_t`` object at once. Parameters ---------- val : int or tuple or list or range Integer or range to add. Returns ------- __ha...
python
{ "resource": "" }
q251796
AbstractExperiment.done
train
def done(self, warn=True): """Is the subprocess done?""" if not self.process: raise Exception("Not implemented yet or process not started yet, make sure to overload the done() method in your Experiment class") self.process.poll() if self.process.returncode == None: ...
python
{ "resource": "" }
q251797
GizaSentenceAlignment.getalignedtarget
train
def getalignedtarget(self, index): """Returns target range only if source index aligns to a single consecutive range of target tokens.""" targetindices = [] target = None foundindex = -1 for sourceindex, targetindex in self.alignment: if sourceindex == index: ...
python
{ "resource": "" }
q251798
WordAlignment.targetword
train
def targetword(self, index, targetwords, alignment): """Return the aligned targetword for a specified index in the source words""" if alignment[index]: return targetwords[alignment[index]] else: return None
python
{ "resource": "" }
q251799
MultiWordAlignment.targetwords
train
def targetwords(self, index, targetwords, alignment): """Return the aligned targetwords for a specified index in the source words""" return [ targetwords[x] for x in alignment[index] ]
python
{ "resource": "" }