_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q46000
ScssInspector._get_recursive_dependancies
train
def _get_recursive_dependancies(self, dependencies_map, sourcepath, recursive=True): """ Return all dependencies of a source, recursively searching through its dependencies. This is a common method used by ``children`` and ``parents`` methods. ...
python
{ "resource": "" }
q46001
ScssInspector.children
train
def children(self, sourcepath, recursive=True): """ Recursively find all children that are imported from the given source path. Args: sourcepath (str): Source file path to search for. Keyword Arguments: recursive (bool): Switch to enabled recursive findi...
python
{ "resource": "" }
q46002
ScssInspector.parents
train
def parents(self, sourcepath, recursive=True): """ Recursively find all parents that import the given source path. Args: sourcepath (str): Source file path to search for. Keyword Arguments: recursive (bool): Switch to enabled recursive finding (if True). ...
python
{ "resource": "" }
q46003
AWSInfo.show_cloudwatch_logs
train
def show_cloudwatch_logs(self, count=10, grp_name=None): """ Show ``count`` latest CloudWatch Logs entries for our lambda function. :param count: number of log entries to show :type count: int """ if grp_name is None: grp_name = '/aws/lambda/%s' % self.config...
python
{ "resource": "" }
q46004
AWSInfo._show_log_stream
train
def _show_log_stream(self, conn, grp_name, stream_name, max_count=10): """ Show up to ``max`` events from a specified log stream; return the number of events shown. :param conn: AWS Logs API connection :type conn: :py:class:`botocore:CloudWatchLogs.Client` :param grp_nam...
python
{ "resource": "" }
q46005
AWSInfo._url_for_queue
train
def _url_for_queue(self, conn, name): """ Given a queue name, return the URL for it. :param conn: SQS API connection :type conn: :py:class:`botocore:SQS.Client` :param name: queue name, or None for all queues in config. :type name: str :return: queue URL ...
python
{ "resource": "" }
q46006
AWSInfo._delete_msg
train
def _delete_msg(self, conn, queue_url, receipt_handle): """ Delete the message specified by ``receipt_handle`` in the queue specified by ``queue_url``. :param conn: SQS API connection :type conn: :py:class:`botocore:SQS.Client` :param queue_url: queue URL to delete the m...
python
{ "resource": "" }
q46007
AWSInfo._show_one_queue
train
def _show_one_queue(self, conn, name, count, delete=False): """ Show ``count`` messages from the specified SQS queue. :param conn: SQS API connection :type conn: :py:class:`botocore:SQS.Client` :param name: queue name, or None for all queues in config. :type name: str ...
python
{ "resource": "" }
q46008
AWSInfo._all_queue_names
train
def _all_queue_names(self): """ Return a list of all unique queue names in our config. :return: list of all queue names (str) :rtype: :std:term:`list` """ queues = set() endpoints = self.config.get('endpoints') for e in endpoints: for q in end...
python
{ "resource": "" }
q46009
AWSInfo.show_queue
train
def show_queue(self, name=None, count=10, delete=False): """ Show up to ``count`` messages from the queue named ``name``. If ``name`` is None, show for each queue in our config. If ``delete`` is True, delete the messages after showing them. :param name: queue name, or None for a...
python
{ "resource": "" }
q46010
AWSInfo.get_api_id
train
def get_api_id(self): """ Return the API ID. :return: API ID :rtype: str """ logger.debug('Connecting to AWS apigateway API') conn = client('apigateway') apis = conn.get_rest_apis() api_id = None for api in apis['items']: if ap...
python
{ "resource": "" }
q46011
AWSInfo._add_method_setting
train
def _add_method_setting(self, conn, api_id, stage_name, path, key, value, op): """ Update a single method setting on the specified stage. This uses the 'add' operation to PATCH the resource. :param conn: APIGateway API connection :type conn: :py:class...
python
{ "resource": "" }
q46012
initialize_repository
train
def initialize_repository(path, spor_dir='.spor'): """Initialize a spor repository in `path` if one doesn't already exist. Args: path: Path to any file or directory within the repository. spor_dir: The name of the directory containing spor data. Returns: A `Repository` instance. Raise...
python
{ "resource": "" }
q46013
open_repository
train
def open_repository(path, spor_dir='.spor'): """Open an existing repository. Args: path: Path to any file or directory within the repository. spor_dir: The name of the directory containing spor data. Returns: A `Repository` instance. Raises: ValueError: No repository is found....
python
{ "resource": "" }
q46014
_find_root_dir
train
def _find_root_dir(path, spor_dir): """Search for a spor repo containing `path`. This searches for `spor_dir` in directories dominating `path`. If a directory containing `spor_dir` is found, then that directory is returned as a `pathlib.Path`. Returns: The dominating directory containing `spor_dir...
python
{ "resource": "" }
q46015
Repository.add
train
def add(self, anchor): """Add a new anchor to the repository. This will create a new ID for the anchor and provision new storage for it. Returns: The storage ID for the Anchor which can be used to retrieve the anchor later. """ anchor_id = uuid.uuid4().hex ...
python
{ "resource": "" }
q46016
Repository._anchor_path
train
def _anchor_path(self, anchor_id): "Absolute path to the data file for `anchor_id`." file_name = '{}.yml'.format(anchor_id) file_path = self._spor_dir / file_name return file_path
python
{ "resource": "" }
q46017
log
train
def log(**data): """RPC method for logging events Makes entry with new account creating Return None """ # Get data from request body entry = { "module": data["params"]["module"], "event": data["params"]["event"], "timestamp": data["params"]["timestamp"], "arguments": data["params"]["arguments"] } # Call...
python
{ "resource": "" }
q46018
HistoryHandler.post
train
def post(self): """Accepts jsorpc post request. Retrieves data from request body. Calls log method for writung data to database """ data = json.loads(self.request.body.decode()) response = dispatch([log],{'jsonrpc': '2.0', 'method': 'log', 'params': data, 'id': 1})
python
{ "resource": "" }
q46019
MMCAlign.start_optimisation
train
def start_optimisation(self, rounds: int, max_angle: float, max_distance: float, temp: float=298.15, stop_when=None, verbose=None): """Starts the loop fitting protocol. Parameters ---------- rounds : int The number of Mon...
python
{ "resource": "" }
q46020
MMCAlign._generate_initial_score
train
def _generate_initial_score(self): """Runs the evaluation function for the initial pose.""" self.current_energy = self.eval_fn(self.polypeptide, *self.eval_args) self.best_energy = copy.deepcopy(self.current_energy) self.best_model = copy.deepcopy(self.polypeptide) return
python
{ "resource": "" }
q46021
MMCAlign._mmc_loop
train
def _mmc_loop(self, rounds, max_angle, max_distance, temp=298.15, stop_when=None, verbose=True): """The main Metropolis Monte Carlo loop.""" current_round = 0 while current_round < rounds: working_model = copy.deepcopy(self.polypeptide) random_vector = u...
python
{ "resource": "" }
q46022
MMCAlign.check_move
train
def check_move(new, old, t): """Determines if a model will be accepted.""" if (t <= 0) or numpy.isclose(t, 0.0): return False K_BOLTZ = 1.9872041E-003 # kcal/mol.K if new < old: return True else: move_prob = math.exp(-(new - old) / (K_BOLTZ * ...
python
{ "resource": "" }
q46023
Discover.scan_backends
train
def scan_backends(self, backends): """ From given backends create and return engine, filename and extension indexes. Arguments: backends (list): List of backend engines to scan. Order does matter since resulted indexes are stored in an ``OrderedDict``. So ...
python
{ "resource": "" }
q46024
Discover.get_engine
train
def get_engine(self, filepath, kind=None): """ From given filepath try to discover which backend format to use. Discovering is pretty naive as it find format from file extension. Args: filepath (str): Settings filepath or filename. Keyword Arguments: ki...
python
{ "resource": "" }
q46025
Discover.guess_filename
train
def guess_filename(self, basedir, kind=None): """ Try to find existing settings filename from base directory using default filename from available engines. First finded filename from available engines win. So registred engines order matter. Arguments: basedi...
python
{ "resource": "" }
q46026
Discover.search
train
def search(self, filepath=None, basedir=None, kind=None): """ Search for a settings file. Keyword Arguments: filepath (string): Path to a config file, either absolute or relative. If absolute set its directory as basedir (omitting given basedir argume...
python
{ "resource": "" }
q46027
create
train
def create(python, env_dir, system, prompt, bare, virtualenv_py=None): """Main entry point to use this as a module. """ if not python or python == sys.executable: _create_with_this( env_dir=env_dir, system=system, prompt=prompt, bare=bare, virtualenv_py=virtualenv_py, ...
python
{ "resource": "" }
q46028
event.matches
train
def matches(self, client, event_data): """True if all filters are matching.""" for f in self.filters: if not f(client, event_data): return False return True
python
{ "resource": "" }
q46029
event.filter_events
train
def filter_events(cls, client, event_data): """Filter registered events and yield them.""" for event in cls.events: # try event filters if event.matches(client, event_data): yield event
python
{ "resource": "" }
q46030
event.filter_callbacks
train
def filter_callbacks(cls, client, event_data): """Filter registered events and yield all of their callbacks.""" for event in cls.filter_events(client, event_data): for cb in event.callbacks: yield cb
python
{ "resource": "" }
q46031
ImportProcessor.validate_parameters
train
def validate_parameters(self): """Validate that the parameters are correctly specified.""" for p in self.params: if p not in self.known_params: raise errors.UnknownParameter(p, self.known_params)
python
{ "resource": "" }
q46032
get_api_id
train
def get_api_id(config, args): """ Get the API ID from Terraform, or from AWS if that fails. :param config: configuration :type config: :py:class:`~.Config` :param args: command line arguments :type args: :py:class:`argparse.Namespace` :return: API Gateway ID :rtype: str """ try:...
python
{ "resource": "" }
q46033
cmdline
train
def cmdline(argv=sys.argv[1:]): """ Script for merging different collections of stop words. """ parser = ArgumentParser( description='Create and merge collections of stop words') parser.add_argument( 'language', help='The language used in the collection') parser.add_argument('sou...
python
{ "resource": "" }
q46034
authenticate
train
def authenticate(api_key, api_url, **kwargs): """Returns a muddle instance, with API key and url set for requests.""" muddle = Muddle(**kwargs) # Login. muddle.authenticate(api_key, api_url) return muddle
python
{ "resource": "" }
q46035
ConfigManager.get_job_config
train
def get_job_config(conf): """ Extract handler names from job_conf.xml """ rval = [] root = elementtree.parse(conf).getroot() for handler in root.find('handlers'): rval.append({'service_name' : handler.attrib['id']}) return rval
python
{ "resource": "" }
q46036
ConfigManager.__load_state
train
def __load_state(self): """ Read persisted state from the JSON statefile """ try: return ConfigState(json.load(open(self.config_state_path))) except (OSError, IOError) as exc: if exc.errno == errno.ENOENT: self.__dump_state({}) retu...
python
{ "resource": "" }
q46037
ConfigManager._deregister_config_file
train
def _deregister_config_file(self, key): """ Deregister a previously registered config file. The caller should ensure that it was previously registered. """ state = self.__load_state() if 'remove_configs' not in state: state['remove_configs'] = {} state['remov...
python
{ "resource": "" }
q46038
ConfigManager._purge_config_file
train
def _purge_config_file(self, key): """ Forget a previously deregister config file. The caller should ensure that it was previously deregistered. """ state = self.__load_state() del state['remove_configs'][key] self.__dump_state(state)
python
{ "resource": "" }
q46039
ConfigManager.register_config_changes
train
def register_config_changes(self, configs, meta_changes): """ Persist config changes to the JSON state file. When a config changes, a process manager may perform certain actions based on these changes. This method can be called once the actions are complete. """ for config_file i...
python
{ "resource": "" }
q46040
ConfigManager.get_registered_configs
train
def get_registered_configs(self, instances=None): """ Return the persisted values of all config files registered with the config manager. """ configs = self.state.get('config_files', {}) if instances is not None: for config_file, config in configs.items(): if ...
python
{ "resource": "" }
q46041
ConfigManager.get_registered_instances
train
def get_registered_instances(self, include_removed=False): """ Return the persisted names of all instances across all registered configs. """ rval = [] configs = self.state.get('config_files', {}).values() if include_removed: configs.extend(self.state.get('remove_conf...
python
{ "resource": "" }
q46042
main
train
async def main(): """`sublemon` library example!""" for c in (1, 2, 4,): async with Sublemon(max_concurrency=c) as s: start = time.perf_counter() await asyncio.gather(one(s), two(s)) end = time.perf_counter() print('Limiting to', c, 'concurrent subprocess(...
python
{ "resource": "" }
q46043
catalog_to_moc
train
def catalog_to_moc(catalog, radius, order, **kwargs): """ Convert a catalog to a MOC. The catalog is given as an Astropy SkyCoord object containing multiple coordinates. The radius of catalog entries can be given as an Astropy Quantity (with units), otherwise it is assumed to be in arcseconds....
python
{ "resource": "" }
q46044
_catalog_to_cells_neighbor
train
def _catalog_to_cells_neighbor(catalog, radius, order): """ Convert a catalog to a list of cells. This is the original implementation of the `catalog_to_cells` function which does not make use of the Healpy `query_disc` routine. Note: this function uses a simple flood-filling approach and is v...
python
{ "resource": "" }
q46045
catalog_to_cells
train
def catalog_to_cells(catalog, radius, order, include_fallback=True, **kwargs): """ Convert a catalog to a set of cells. This function is intended to be used via `catalog_to_moc` but is available for separate usage. It takes the same arguments as that function. This function uses the Healpy `q...
python
{ "resource": "" }
q46046
read_ascii_catalog
train
def read_ascii_catalog(filename, format_, unit=None): """ Read an ASCII catalog file using Astropy. This routine is used by pymoctool to load coordinates from a catalog file in order to generate a MOC representation. """ catalog = ascii.read(filename, format=format_) columns = catalog.colu...
python
{ "resource": "" }
q46047
ThreadFixAPI._build_list_params
train
def _build_list_params(param_name, key, values): """Builds a list of POST parameters from a list or single value.""" params = {} if hasattr(values, '__iter__'): index = 0 for value in values: params[str(param_name) + '[' + str(index) + '].' + str(key)] = s...
python
{ "resource": "" }
q46048
ThreadFixAPI._request
train
def _request(self, method, url, params=None, files=None): """Common handler for all HTTP requests.""" if not params: params = {} params['apiKey'] = self.api_key headers = { 'User-Agent': self.user_agent, 'Accept': 'application/json' } ...
python
{ "resource": "" }
q46049
ThreadFixResponse.data_json
train
def data_json(self, pretty=False): """Returns the data as a valid JSON string.""" if pretty: return json.dumps(self.data, sort_keys=True, indent=4, separators=(',', ': ')) else: return json.dumps(self.data)
python
{ "resource": "" }
q46050
get_anchor_diff
train
def get_anchor_diff(anchor): """Get the get_anchor_diff between an anchor and the current state of its source. Returns: A tuple of get_anchor_diff lines. If there is not different, then this returns an empty tuple. """ new_anchor = make_anchor( file_path=anchor.file_path, offset...
python
{ "resource": "" }
q46051
make_anchor
train
def make_anchor(file_path: pathlib.Path, offset: int, width: int, context_width: int, metadata, encoding: str = 'utf-8', handle=None): """Construct a new `Anchor`. Args: file_path: The absolute path to the t...
python
{ "resource": "" }
q46052
Encoder.rgba_to_int
train
def rgba_to_int(cls, red, green, blue, alpha): """ Encodes the color as an Integer in RGBA encoding Returns None if any of red, green or blue are None. If alpha is None we use 255 by default. :return: Integer :rtype: int """ red = unwrap(red) ...
python
{ "resource": "" }
q46053
amerge
train
async def amerge(*agens) -> AsyncGenerator[Any, None]: """Thin wrapper around aiostream.stream.merge.""" xs = stream.merge(*agens) async with xs.stream() as streamer: async for x in streamer: yield x
python
{ "resource": "" }
q46054
crossplat_loop_run
train
def crossplat_loop_run(coro) -> Any: """Cross-platform method for running a subprocess-spawning coroutine.""" if sys.platform == 'win32': signal.signal(signal.SIGINT, signal.SIG_DFL) loop = asyncio.ProactorEventLoop() else: loop = asyncio.new_event_loop() asyncio.set_event_loop(...
python
{ "resource": "" }
q46055
parse_args
train
def parse_args(args): ''' Parse an argument string http://stackoverflow.com/questions/18160078/ how-do-you-write-tests-for-the-argparse-portion-of-a-python-module ''' parser = argparse.ArgumentParser() parser.add_argument('config_file', nargs='?', help='Configura...
python
{ "resource": "" }
q46056
_factory
train
def _factory(importname, base_class_type, path=None, *args, **kargs): ''' Load a module of a given base class type Parameter -------- importname: string Name of the module, etc. converter base_class_type: class type E.g converter path: Absoulte path o...
python
{ "resource": "" }
q46057
json_numpy_obj_hook
train
def json_numpy_obj_hook(dct): """Decodes a previously encoded numpy ndarray with proper shape and dtype. And decompresses the data with blosc :param dct: (dict) json encoded ndarray :return: (ndarray) if input was an encoded ndarray """ if isinstance(dct, dict) and '__ndarray__' in dct: ...
python
{ "resource": "" }
q46058
NumpyEncoder.default
train
def default(self, obj): """If input object is an ndarray it will be converted into a dict holding dtype, shape and the data, base64 encoded and blosc compressed. """ if isinstance(obj, np.ndarray): if obj.flags['C_CONTIGUOUS']: obj_data = obj.data ...
python
{ "resource": "" }
q46059
extract_all_ss_dssp
train
def extract_all_ss_dssp(in_dssp, path=True): """Uses DSSP to extract secondary structure information on every residue. Parameters ---------- in_dssp : str Path to DSSP file. path : bool, optional Indicates if pdb is a path or a string. Returns ------- dssp_residues : [t...
python
{ "resource": "" }
q46060
tag_dssp_data
train
def tag_dssp_data(assembly, loop_assignments=(' ', 'B', 'S', 'T')): """Adds output data from DSSP to an Assembly. A dictionary will be added to the `tags` dictionary of each residue called `dssp_data`, which contains the secondary structure definition, solvent accessibility phi and psi values from ...
python
{ "resource": "" }
q46061
get_ss_regions
train
def get_ss_regions(assembly, ss_types): """Returns an Assembly containing Polymers for each region of structure. Parameters ---------- assembly : ampal.Assembly `Assembly` object to be searched secondary structure regions. ss_types : list List of secondary structure tags to be separ...
python
{ "resource": "" }
q46062
snaql_migration
train
def snaql_migration(ctx, db_uri, migrations, app, config): """ Lightweight SQL Schema migration tool based on Snaql queries """ if config: migrations_config = _parse_config(config) else: if db_uri and migrations and app: migrations_config = _generate_config(db_uri, migra...
python
{ "resource": "" }
q46063
show
train
def show(ctx): """ Show migrations list """ for app_name, app in ctx.obj['config']['apps'].items(): click.echo(click.style(app_name, fg='green', bold=True)) for migration in app['migrations']: applied = ctx.obj['db'].is_migration_applied(app_name, migration) clic...
python
{ "resource": "" }
q46064
BaseHandler.bundle
train
def bundle(self, name: str) -> models.Bundle: """Fetch a bundle from the store.""" return self.Bundle.filter_by(name=name).first()
python
{ "resource": "" }
q46065
BaseHandler.version
train
def version(self, bundle: str, date: dt.datetime) -> models.Version: """Fetch a version from the store.""" return (self.Version.query .join(models.Version.bundle) .filter(models.Bundle.name == bundle, models.Vers...
python
{ "resource": "" }
q46066
BaseHandler.tag
train
def tag(self, name: str) -> models.Tag: """Fetch a tag from the database.""" return self.Tag.filter_by(name=name).first()
python
{ "resource": "" }
q46067
BaseHandler.new_bundle
train
def new_bundle(self, name: str, created_at: dt.datetime=None) -> models.Bundle: """Create a new file bundle.""" new_bundle = self.Bundle(name=name, created_at=created_at) return new_bundle
python
{ "resource": "" }
q46068
BaseHandler.new_version
train
def new_version(self, created_at: dt.datetime, expires_at: dt.datetime=None) -> models.Version: """Create a new bundle version.""" new_version = self.Version(created_at=created_at, expires_at=expires_at) return new_version
python
{ "resource": "" }
q46069
BaseHandler.new_file
train
def new_file(self, path: str, checksum: str=None, to_archive: bool=False, tags: List[models.Tag]=None) -> models.File: """Create a new file.""" new_file = self.File(path=path, checksum=checksum, to_archive=to_archive, tags=tags) return new_file
python
{ "resource": "" }
q46070
BaseHandler.new_tag
train
def new_tag(self, name: str, category: str=None) -> models.Tag: """Create a new tag.""" new_tag = self.Tag(name=name, category=category) return new_tag
python
{ "resource": "" }
q46071
BaseHandler.files
train
def files(self, *, bundle: str=None, tags: List[str]=None, version: int=None, path: str=None) -> models.File: """Fetch files from the store.""" query = self.File.query if bundle: query = (query.join(self.File.version, self.Version.bundle) .filt...
python
{ "resource": "" }
q46072
BaseHandler.files_before
train
def files_before(self, *, bundle: str=None, tags: List[str]=None, before: str=None) -> models.File: """Fetch files before date from store""" query = self.files(tags=tags, bundle=bundle) if before: before_dt = parse_date(before) query = query.join(mode...
python
{ "resource": "" }
q46073
BaseHandler.files_ondisk
train
def files_ondisk(self, file_objs: models.File) -> set: """Returns a list of files that are not on disk.""" return set([ file_obj for file_obj in file_objs if Path(file_obj.full_path).is_file() ])
python
{ "resource": "" }
q46074
LineBasedParser.readline
train
def readline(self): """Get the next line including the newline or '' on EOF.""" self.lineno += 1 if self._buffer: return self._buffer.pop() else: return self.input.readline()
python
{ "resource": "" }
q46075
LineBasedParser.push_line
train
def push_line(self, line): """Push line back onto the line buffer. :param line: the line with no trailing newline """ self.lineno -= 1 self._buffer.append(line + b'\n')
python
{ "resource": "" }
q46076
LineBasedParser.read_bytes
train
def read_bytes(self, count): """Read a given number of bytes from the input stream. Throws MissingBytes if the bytes are not found. Note: This method does not read from the line buffer. :return: a string """ result = self.input.read(count) found = len(result) ...
python
{ "resource": "" }
q46077
LineBasedParser.read_until
train
def read_until(self, terminator): """Read the input stream until the terminator is found. Throws MissingTerminator if the terminator is not found. Note: This method does not read from the line buffer. :return: the bytes read up to but excluding the terminator. """ lin...
python
{ "resource": "" }
q46078
ImportParser.iter_commands
train
def iter_commands(self): """Iterator returning ImportCommand objects.""" while True: line = self.next_line() if line is None: if b'done' in self.features: raise errors.PrematureEndOfStream(self.lineno) break elif len...
python
{ "resource": "" }
q46079
ImportParser.iter_file_commands
train
def iter_file_commands(self): """Iterator returning FileCommand objects. If an invalid file command is found, the line is silently pushed back and iteration ends. """ while True: line = self.next_line() if line is None: break e...
python
{ "resource": "" }
q46080
ImportParser._parse_blob
train
def _parse_blob(self): """Parse a blob command.""" lineno = self.lineno mark = self._get_mark_if_any() data = self._get_data(b'blob') return commands.BlobCommand(mark, data, lineno)
python
{ "resource": "" }
q46081
ImportParser._parse_commit
train
def _parse_commit(self, ref): """Parse a commit command.""" lineno = self.lineno mark = self._get_mark_if_any() author = self._get_user_info(b'commit', b'author', False) more_authors = [] while True: another_author = self._get_user_info(b'commit', b'author', ...
python
{ "resource": "" }
q46082
ImportParser._parse_feature
train
def _parse_feature(self, info): """Parse a feature command.""" parts = info.split(b'=', 1) name = parts[0] if len(parts) > 1: value = self._path(parts[1]) else: value = None self.features[name] = value return commands.FeatureCommand(name, v...
python
{ "resource": "" }
q46083
ImportParser._parse_file_modify
train
def _parse_file_modify(self, info): """Parse a filemodify command within a commit. :param info: a string in the format "mode dataref path" (where dataref might be the hard-coded literal 'inline'). """ params = info.split(b' ', 2) path = self._path(params[2]) mo...
python
{ "resource": "" }
q46084
ImportParser._parse_reset
train
def _parse_reset(self, ref): """Parse a reset command.""" from_ = self._get_from() return commands.ResetCommand(ref, from_)
python
{ "resource": "" }
q46085
ImportParser._parse_tag
train
def _parse_tag(self, name): """Parse a tag command.""" from_ = self._get_from(b'tag') tagger = self._get_user_info(b'tag', b'tagger', accept_just_who=True) message = self._get_data(b'tag', b'message') return commands.TagCommand(name, from_, tagger, message)
python
{ "resource": "" }
q46086
ImportParser._get_mark_if_any
train
def _get_mark_if_any(self): """Parse a mark section.""" line = self.next_line() if line.startswith(b'mark :'): return line[len(b'mark :'):] else: self.push_line(line) return None
python
{ "resource": "" }
q46087
ImportParser._get_from
train
def _get_from(self, required_for=None): """Parse a from section.""" line = self.next_line() if line is None: return None elif line.startswith(b'from '): return line[len(b'from '):] elif required_for: self.abort(errors.MissingSection, required_f...
python
{ "resource": "" }
q46088
ImportParser._get_merge
train
def _get_merge(self): """Parse a merge section.""" line = self.next_line() if line is None: return None elif line.startswith(b'merge '): return line[len(b'merge '):] else: self.push_line(line) return None
python
{ "resource": "" }
q46089
ImportParser._get_property
train
def _get_property(self): """Parse a property section.""" line = self.next_line() if line is None: return None elif line.startswith(b'property '): return self._name_value(line[len(b'property '):]) else: self.push_line(line) return No...
python
{ "resource": "" }
q46090
ImportParser._get_user_info
train
def _get_user_info(self, cmd, section, required=True, accept_just_who=False): """Parse a user section.""" line = self.next_line() if line.startswith(section + b' '): return self._who_when(line[len(section + b' '):], cmd, section, accept_just_who=accept_just_wh...
python
{ "resource": "" }
q46091
ImportParser._get_data
train
def _get_data(self, required_for, section=b'data'): """Parse a data section.""" line = self.next_line() if line.startswith(b'data '): rest = line[len(b'data '):] if rest.startswith(b'<<'): return self.read_until(rest[2:]) else: ...
python
{ "resource": "" }
q46092
ImportParser._who_when
train
def _who_when(self, s, cmd, section, accept_just_who=False): """Parse who and when information from a string. :return: a tuple of (name,email,timestamp,timezone). name may be the empty string if only an email address was given. """ match = _WHO_AND_WHEN_RE.search(s) ...
python
{ "resource": "" }
q46093
ImportParser._path
train
def _path(self, s): """Parse a path.""" if s.startswith(b'"'): if not s.endswith(b'"'): self.abort(errors.BadFormat, '?', '?', s) else: return _unquote_c_string(s[1:-1]) return s
python
{ "resource": "" }
q46094
ImportParser._path_pair
train
def _path_pair(self, s): """Parse two paths separated by a space.""" # TODO: handle a space in the first path if s.startswith(b'"'): parts = s[1:].split(b'" ', 1) else: parts = s.split(b' ', 1) if len(parts) != 2: self.abort(errors.BadFormat, '...
python
{ "resource": "" }
q46095
ImportParser._mode
train
def _mode(self, s): """Check file mode format and parse into an int. :return: mode as integer """ # Note: Output from git-fast-export slightly different to spec if s in [b'644', b'100644', b'0100644']: return 0o100644 elif s in [b'755', b'100755', b'0100755']...
python
{ "resource": "" }
q46096
common_directory
train
def common_directory(paths): """Find the deepest common directory of a list of paths. :return: if no paths are provided, None is returned; if there is no common directory, '' is returned; otherwise the common directory with a trailing / is returned. """ import posixpath def get_dir_with...
python
{ "resource": "" }
q46097
is_inside
train
def is_inside(directory, fname): """True if fname is inside directory. The parameters should typically be passed to osutils.normpath first, so that . and .. and repeated slashes are eliminated, and the separators are canonical for the platform. The empty string as a dir name is taken as top-of-tre...
python
{ "resource": "" }
q46098
is_inside_any
train
def is_inside_any(dir_list, fname): """True if fname is inside any of given dirs.""" for dirname in dir_list: if is_inside(dirname, fname): return True return False
python
{ "resource": "" }
q46099
binary_stream
train
def binary_stream(stream): """Ensure a stream is binary on Windows. :return: the stream """ try: import os if os.name == 'nt': fileno = getattr(stream, 'fileno', None) if fileno: no = fileno() if no >= 0: # -1 means we're worki...
python
{ "resource": "" }