_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q58000
object_to_items
train
def object_to_items(data_structure): """Converts a object to a items list respecting also slots. Use dict(object_to_items(obj)) to get a dictionary.""" items = [] # Get all items from dict try: items = list(data_structure.__dict__.items()) except: pass # Get all slots hi...
python
{ "resource": "" }
q58001
recursive_sort
train
def recursive_sort(data_structure): """Sort a recursive data_structure. :param data_structure: The structure to convert. data_structure must be already sortable or you must use freeze() or dump(). The function will work with many kinds of input. Dictionaries will be converted to lists of tuples....
python
{ "resource": "" }
q58002
traverse_frozen_data
train
def traverse_frozen_data(data_structure): """Yields the leaves of the frozen data-structure pre-order. It will produce the same order as one would write the data-structure.""" parent_stack = [data_structure] while parent_stack: node = parent_stack.pop(0) # We don't iterate strings ...
python
{ "resource": "" }
q58003
tree_diff
train
def tree_diff(a, b, n=5, sort=False): """Dump any data-structure or object, traverse it depth-first in-order and apply a unified diff. Depth-first in-order is just like structure would be printed. :param a: data_structure a :param b: data_structure b :param ...
python
{ "resource": "" }
q58004
Group.stats
train
def stats(self): """Basic group statistics. Returned dict has the following keys: 'online' - users online count 'ingame' - users currently in game count 'chatting' - users chatting count :return: dict """ stats_online = CRef.cint() s...
python
{ "resource": "" }
q58005
startproject
train
def startproject(name, directory, verbosity): """ Creates a Trading-Bots project directory structure for the given project NAME in the current directory or optionally in the given DIRECTORY. """ handle_template('project', name, target=directory, verbosity=verbosity) click.echo(f"Success: '{name}...
python
{ "resource": "" }
q58006
createbot
train
def createbot(name, directory, verbosity): """ Creates a Bot's directory structure for the given bot NAME in the current directory or optionally in the given DIRECTORY. """ handle_template('bot', name, target=directory, verbosity=verbosity) click.echo(f"Success: '{name}' bot was successfully cre...
python
{ "resource": "" }
q58007
User.get_state
train
def get_state(self, as_str=False): """Returns user state. See ``UserState``. :param bool as_str: Return human-friendly state name instead of an ID. :rtype: int|str """ uid = self.user_id if self._iface_user.get_id() == uid: result = self._iface.get_my_state...
python
{ "resource": "" }
q58008
load_permissions_on_identity_loaded
train
def load_permissions_on_identity_loaded(sender, identity): """Add system roles "Needs" to users' identities. Every user gets the **any_user** Need. Authenticated users get in addition the **authenticated_user** Need. """ identity.provides.add( any_user ) # if the user is not anonymo...
python
{ "resource": "" }
q58009
Validator.print_errors
train
def print_errors(self, file_name): """ Prints the errors observed for a file """ for error in self.get_messages(file_name): print('\t', error.__unicode__())
python
{ "resource": "" }
q58010
RasterQueryForm.clean
train
def clean(self): """Return cleaned fields as a dict, determine which geom takes precedence. """ data = super(RasterQueryForm, self).clean() geom = data.pop('upload', None) or data.pop('bbox', None) if geom: data['g'] = geom return data
python
{ "resource": "" }
q58011
register
train
def register(matcher, *aliases): """ Register a matcher associated to one or more aliases. Each alias given is also normalized. """ docstr = matcher.__doc__ if matcher.__doc__ is not None else '' helpmatchers[matcher] = docstr.strip() for alias in aliases: matchers[alias] = matcher ...
python
{ "resource": "" }
q58012
normalize
train
def normalize(alias): """ Normalizes an alias by removing adverbs defined in IGNORED_WORDS """ # Convert from CamelCase to snake_case alias = re.sub(r'([a-z])([A-Z])', r'\1_\2', alias) # Ignore words words = alias.lower().split('_') words = filter(lambda w: w not in IGNORED_WORDS, words) ...
python
{ "resource": "" }
q58013
lookup
train
def lookup(alias): """ Tries to find a matcher callable associated to the given alias. If an exact match does not exists it will try normalizing it and even removing underscores to find one. """ if alias in matchers: return matchers[alias] else: norm = normalize(alias) ...
python
{ "resource": "" }
q58014
suggest
train
def suggest(alias, max=3, cutoff=0.5): """ Suggest a list of aliases which are similar enough """ aliases = matchers.keys() similar = get_close_matches(alias, aliases, n=max, cutoff=cutoff) return similar
python
{ "resource": "" }
q58015
sample_chromosomes
train
def sample_chromosomes(job, genome_fai_file): """ Get a list of chromosomes in the input data. :param toil.fileStore.FileID genome_fai_file: Job store file ID for the genome fai file :return: Chromosomes in the sample :rtype: list[str] """ work_dir = os.getcwd() genome_fai = untargz(job...
python
{ "resource": "" }
q58016
run_mutation_aggregator
train
def run_mutation_aggregator(job, mutation_results, univ_options): """ Aggregate all the called mutations. :param dict mutation_results: Dict of dicts of the various mutation callers in a per chromosome format :param dict univ_options: Dict of universal options used by almost all tools :r...
python
{ "resource": "" }
q58017
merge_perchrom_mutations
train
def merge_perchrom_mutations(job, chrom, mutations, univ_options): """ Merge the mutation calls for a single chromosome. :param str chrom: Chromosome to process :param dict mutations: dict of dicts of the various mutation caller names as keys, and a dict of per chromosome job store ids for v...
python
{ "resource": "" }
q58018
read_vcf
train
def read_vcf(vcf_file): """ Read a vcf file to a dict of lists. :param str vcf_file: Path to a vcf file. :return: dict of lists of vcf records :rtype: dict """ vcf_dict = [] with open(vcf_file, 'r') as invcf: for line in invcf: if line.startswith('#'): ...
python
{ "resource": "" }
q58019
merge_perchrom_vcfs
train
def merge_perchrom_vcfs(job, perchrom_vcfs, tool_name, univ_options): """ Merge per-chromosome vcf files into a single genome level vcf. :param dict perchrom_vcfs: Dictionary with chromosome name as key and fsID of the corresponding vcf as value :param str tool_name: Name of the tool that ge...
python
{ "resource": "" }
q58020
unmerge
train
def unmerge(job, input_vcf, tool_name, chromosomes, tool_options, univ_options): """ Un-merge a vcf file into per-chromosome vcfs. :param str input_vcf: Input vcf :param str tool_name: The name of the mutation caller :param list chromosomes: List of chromosomes to retain :param dict tool_option...
python
{ "resource": "" }
q58021
as_feature
train
def as_feature(data): """Returns a Feature or FeatureCollection. Arguments: data -- Sequence or Mapping of Feature-like or FeatureCollection-like data """ if not isinstance(data, (Feature, FeatureCollection)): if is_featurelike(data): data = Feature(**data) elif has_feat...
python
{ "resource": "" }
q58022
has_layer
train
def has_layer(fcollection): """Returns true for a multi-layer dict of FeatureCollections.""" for val in six.viewvalues(fcollection): if has_features(val): return True return False
python
{ "resource": "" }
q58023
wrap_rsem
train
def wrap_rsem(job, star_bams, univ_options, rsem_options): """ A wrapper for run_rsem using the results from run_star as input. :param dict star_bams: dict of results from star :param dict univ_options: Dict of universal options used by almost all tools :param dict rsem_options: Options specific to...
python
{ "resource": "" }
q58024
run_rsem
train
def run_rsem(job, rna_bam, univ_options, rsem_options): """ Run rsem on the input RNA bam. ARGUMENTS :param toil.fileStore.FileID rna_bam: fsID of a transcriptome bam generated by STAR :param dict univ_options: Dict of universal options used by almost all tools :param dict rsem_options: Options...
python
{ "resource": "" }
q58025
Overlay.activate
train
def activate(self, page=None): """Activates overlay with browser, optionally opened at a given page. :param str page: Overlay page alias (see OVERLAY_PAGE_*) or a custom URL. """ page = page or '' if '://' in page: self._iface.activate_overlay_url(page)...
python
{ "resource": "" }
q58026
any_of
train
def any_of(value, *args): """ At least one of the items in value should match """ if len(args): value = (value,) + args return ExpectationAny(value)
python
{ "resource": "" }
q58027
all_of
train
def all_of(value, *args): """ All the items in value should match """ if len(args): value = (value,) + args return ExpectationAll(value)
python
{ "resource": "" }
q58028
none_of
train
def none_of(value, *args): """ None of the items in value should match """ if len(args): value = (value,) + args return ExpectationNone(value)
python
{ "resource": "" }
q58029
run_cutadapt
train
def run_cutadapt(job, fastqs, univ_options, cutadapt_options): """ Runs cutadapt on the input RNA fastq files. :param list fastqs: List of fsIDs for input an RNA-Seq fastq pair :param dict univ_options: Dict of universal options used by almost all tools :param dict cutadapt_options: Options specifi...
python
{ "resource": "" }
q58030
index
train
def index(): """Basic test view.""" identity = g.identity actions = {} for action in access.actions.values(): actions[action.value] = DynamicPermission(action).allows(identity) if current_user.is_anonymous: return render_template("invenio_access/open.html", ...
python
{ "resource": "" }
q58031
role_admin
train
def role_admin(): """View only allowed to admin role.""" identity = g.identity actions = {} for action in access.actions.values(): actions[action.value] = DynamicPermission(action).allows(identity) message = 'You are opening a page requiring the "admin-access" permission' return render_...
python
{ "resource": "" }
q58032
read_fastas
train
def read_fastas(input_files): """ Read the tumor and normal fastas into a joint dict. :param dict input_files: A dict containing filename: filepath for T_ and N_ transgened files. :return: The read fastas in a dictionary of tuples :rtype: dict """ tumor_file = [y for x, y in input_files.ite...
python
{ "resource": "" }
q58033
_read_fasta
train
def _read_fasta(fasta_file, output_dict): """ Read the peptide fasta into an existing dict. :param str fasta_file: The peptide file :param dict output_dict: The dict to appends results to. :return: output_dict :rtype: dict """ read_name = None with open(fasta_file, 'r') as f: ...
python
{ "resource": "" }
q58034
_process_consensus_mhcii
train
def _process_consensus_mhcii(mhc_file, normal=False): """ Process the results from running IEDB MHCII binding predictions using the consensus method into a pandas dataframe. :param str mhc_file: Output file containing consensus mhcii:peptide binding predictions :param bool normal: Is this processin...
python
{ "resource": "" }
q58035
_process_net_mhcii
train
def _process_net_mhcii(mhc_file, normal=False): """ Process the results from running NetMHCIIpan binding predictions into a pandas dataframe. :param str mhc_file: Output file containing netmhciipan mhcii:peptide binding predictions :param bool normal: Is this processing the results of a normal? :re...
python
{ "resource": "" }
q58036
_process_mhci
train
def _process_mhci(mhc_file, normal=False): """ Process the results from running IEDB MHCI binding predictions into a pandas dataframe. :param str mhc_file: Output file containing netmhciipan mhci:peptide binding predictions :param bool normal: Is this processing the results of a normal? :return: Re...
python
{ "resource": "" }
q58037
pept_diff
train
def pept_diff(p1, p2): """ Return the number of differences betweeen 2 peptides :param str p1: Peptide 1 :param str p2: Peptide 2 :return: The number of differences between the pepetides :rtype: int >>> pept_diff('ABCDE', 'ABCDF') 1 >>> pept_diff('ABCDE', 'ABDFE') 2 >>> pep...
python
{ "resource": "" }
q58038
print_mhc_peptide
train
def print_mhc_peptide(neoepitope_info, peptides, pepmap, outfile, netmhc=False): """ Accept data about one neoepitope from merge_mhc_peptide_calls and print it to outfile. This is a generic module to reduce code redundancy. :param pandas.core.frame neoepitope_info: object containing with allele, pept,...
python
{ "resource": "" }
q58039
check
train
def check(domain, prefix, code, strategies='*'): """ Check the ownership of a domain by going thru a serie of strategies. If at least one strategy succeed, the domain is considered verified, and this methods returns true. The prefix is a fixed DNS safe string like "yourservice-domain-verification" ...
python
{ "resource": "" }
q58040
CacheBuster.register_cache_buster
train
def register_cache_buster(self, app, config=None): """ Register `app` in cache buster so that `url_for` adds a unique prefix to URLs generated for the `'static'` endpoint. Also make the app able to serve cache-busted static files. This allows setting long cache expiration values...
python
{ "resource": "" }
q58041
env_or_default
train
def env_or_default(var, default=None): """Get environment variable or provide default. Args: var (str): environment variable to search for default (optional(str)): default to return """ if var in os.environ: return os.environ[var] return default
python
{ "resource": "" }
q58042
kms_encrypt
train
def kms_encrypt(value, key, aws_config=None): """Encrypt and value with KMS key. Args: value (str): value to encrypt key (str): key id or alias aws_config (optional[dict]): aws credentials dict of arguments passed into boto3 session example: aws_c...
python
{ "resource": "" }
q58043
get_value
train
def get_value(*args, **kwargs): """Get from config object by exposing Config.get_value method. dict.get() method on Config.values """ global _config if _config is None: raise ValueError('configuration not set; must run figgypy.set_config first') return _config.get_value(*args, **kwargs)
python
{ "resource": "" }
q58044
set_value
train
def set_value(*args, **kwargs): """Set value in the global Config object.""" global _config if _config is None: raise ValueError('configuration not set; must run figgypy.set_config first') return _config.set_value(*args, **kwargs)
python
{ "resource": "" }
q58045
decode_escapes
train
def decode_escapes(s): '''Unescape libconfig string literals''' def decode_match(match): return codecs.decode(match.group(0), 'unicode-escape') return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
python
{ "resource": "" }
q58046
loads
train
def loads(string, filename=None, includedir=''): '''Load the contents of ``string`` to a Python object The returned object is a subclass of ``dict`` that exposes string keys as attributes as well. Example: >>> config = libconf.loads('window: { title: "libconfig example"; };') >>> conf...
python
{ "resource": "" }
q58047
dump_string
train
def dump_string(s): '''Stringize ``s``, adding double quotes and escaping as necessary Backslash escape backslashes, double quotes, ``\f``, ``\n``, ``\r``, and ``\t``. Escape all remaining unprintable characters in ``\xFF``-style. The returned string will be surrounded by double quotes. ''' s ...
python
{ "resource": "" }
q58048
get_dump_type
train
def get_dump_type(value): '''Get the libconfig datatype of a value Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array), ``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool), ``'f'`` (float), or ``'s'`` (string). Produces the proper type for LibconfList, LibconfArray, LibconfInt64...
python
{ "resource": "" }
q58049
get_array_value_dtype
train
def get_array_value_dtype(lst): '''Return array value type, raise ConfigSerializeError for invalid arrays Libconfig arrays must only contain scalar values and all elements must be of the same libconfig data type. Raises ConfigSerializeError if these invariants are not met. Returns the value type o...
python
{ "resource": "" }
q58050
dump_value
train
def dump_value(key, value, f, indent=0): '''Save a value of any libconfig type This function serializes takes ``key`` and ``value`` and serializes them into ``f``. If ``key`` is ``None``, a list-style output is produced. Otherwise, output has ``key = value`` format. ''' spaces = ' ' * indent ...
python
{ "resource": "" }
q58051
dump_collection
train
def dump_collection(cfg, f, indent=0): '''Save a collection of attributes''' for i, value in enumerate(cfg): dump_value(None, value, f, indent) if i < len(cfg) - 1: f.write(u',\n')
python
{ "resource": "" }
q58052
dump_dict
train
def dump_dict(cfg, f, indent=0): '''Save a dictionary of attributes''' for key in cfg: if not isstr(key): raise ConfigSerializeError("Dict keys must be strings: %r" % (key,)) dump_value(key, cfg[key], f, indent) f.write(u';\n')
python
{ "resource": "" }
q58053
dumps
train
def dumps(cfg): '''Serialize ``cfg`` into a libconfig-formatted ``str`` ``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values (numbers, strings, booleans, possibly nested dicts, lists, and tuples). Returns the formatted string. ''' str_file = io.StringIO() dump(cfg, st...
python
{ "resource": "" }
q58054
dump
train
def dump(cfg, f): '''Serialize ``cfg`` as a libconfig-formatted stream into ``f`` ``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values (numbers, strings, booleans, possibly nested dicts, lists, and tuples). ``f`` must be a ``file``-like object with a ``write()`` method. ''' ...
python
{ "resource": "" }
q58055
Tokenizer.tokenize
train
def tokenize(self, string): '''Yield tokens from the input string or throw ConfigParseError''' pos = 0 while pos < len(string): m = SKIP_RE.match(string, pos=pos) if m: skip_lines = m.group(0).split('\n') if len(skip_lines) > 1: ...
python
{ "resource": "" }
q58056
TokenStream.from_file
train
def from_file(cls, f, filename=None, includedir='', seenfiles=None): '''Create a token stream by reading an input file Read tokens from `f`. If an include directive ('@include "file.cfg"') is found, read its contents as well. The `filename` argument is used for error messages and to de...
python
{ "resource": "" }
q58057
TokenStream.error
train
def error(self, msg): '''Raise a ConfigParseError at the current input position''' if self.finished(): raise ConfigParseError("Unexpected end of input; %s" % (msg,)) else: t = self.peek() raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
python
{ "resource": "" }
q58058
load_variables
train
def load_variables(): """Load variables from environment variables.""" if (not os.environ.get("PYCONFLUENCE_TOKEN") or not os.environ.get("PYCONFLUENCE_USER") or not os.environ.get("PYCONFLUENCE_ORG")): print ("One or more pyconfluence environment variables are not set. " ...
python
{ "resource": "" }
q58059
rest
train
def rest(url, req="GET", data=None): """Main function to be called from this module. send a request using method 'req' and to the url. the _rest() function will add the base_url to this, so 'url' should be something like '/ips'. """ load_variables() return _rest(base_url + url, req, data)
python
{ "resource": "" }
q58060
_rest
train
def _rest(url, req, data=None): """Send a rest rest request to the server.""" if url.upper().startswith("HTTPS"): print("Secure connection required: Please use HTTPS or https") return "" req = req.upper() if req != "GET" and req != "PUT" and req != "POST" and req != "DELETE": re...
python
{ "resource": "" }
q58061
_api_action
train
def _api_action(url, req, data=None): """Take action based on what kind of request is needed.""" requisite_headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} auth = (user, token) if req == "GET": response = requests.get(url, headers=requisite_h...
python
{ "resource": "" }
q58062
PatternManager._platform_patterns
train
def _platform_patterns(self, platform='generic', compiled=False): """Return all the patterns for specific platform.""" patterns = self._dict_compiled.get(platform, None) if compiled else self._dict_text.get(platform, None) if patterns is None: raise KeyError("Unknown platform: {}".fo...
python
{ "resource": "" }
q58063
PatternManager.pattern
train
def pattern(self, platform, key, compiled=True): """Return the pattern defined by the key string specific to the platform. :param platform: :param key: :param compiled: :return: Pattern string or RE object. """ patterns = self._platform_patterns(platform, compile...
python
{ "resource": "" }
q58064
PatternManager.description
train
def description(self, platform, key): """Return the patter description.""" patterns = self._dict_dscr.get(platform, None) description = patterns.get(key, None) return description
python
{ "resource": "" }
q58065
PatternManager.platform
train
def platform(self, with_prompt, platforms=None): """Return the platform name based on the prompt matching.""" if platforms is None: platforms = self._dict['generic']['prompt_detection'] for platform in platforms: pattern = self.pattern(platform, 'prompt') res...
python
{ "resource": "" }
q58066
Driver.after_connect
train
def after_connect(self): """Execute after connect.""" # TODO: check if this works. show_users = self.device.send("show users", timeout=120) result = re.search(pattern_manager.pattern(self.platform, 'connected_locally'), show_users) if result: self.log('Locally connect...
python
{ "resource": "" }
q58067
Driver.get_hostname_text
train
def get_hostname_text(self): """Return hostname information from the Unix host.""" # FIXME: fix it, too complex logic try: hostname_text = self.device.send('hostname', timeout=10) if hostname_text: self.device.hostname = hostname_text.splitlines()[0] ...
python
{ "resource": "" }
q58068
Config._find_file
train
def _find_file(f): """Find a config file if possible.""" if os.path.isabs(f): return f else: for d in Config._dirs: _f = os.path.join(d, f) if os.path.isfile(_f): return _f raise FiggypyError( ...
python
{ "resource": "" }
q58069
Config._load_file
train
def _load_file(self, f): """Get values from config file""" try: with open(f, 'r') as _fo: _seria_in = seria.load(_fo) _y = _seria_in.dump('yaml') except IOError: raise FiggypyError("could not open configuration file") self.values.up...
python
{ "resource": "" }
q58070
Config.setup
train
def setup(self, config_file=None, aws_config=None, gpg_config=None, decrypt_gpg=True, decrypt_kms=True): """Make setup easier by providing a constructor method. Move to config_file File can be located with a filename only, relative path, or absolute path. If only name or r...
python
{ "resource": "" }
q58071
Console.authenticate
train
def authenticate(self, driver): """Authenticate using the Console Server protocol specific FSM.""" # 0 1 2 3 events = [driver.username_re, driver.password_re, self.device.prompt_re, driver.rommon_re, ...
python
{ "resource": "" }
q58072
delegate
train
def delegate(attribute_name, method_names): """Pass the call to the attribute called attribute_name for every method listed in method_names.""" # hack for python 2.7 as nonlocal is not available info = { 'attribute': attribute_name, 'methods': method_names } def decorator(cls): ...
python
{ "resource": "" }
q58073
pattern_to_str
train
def pattern_to_str(pattern): """Convert regex pattern to string. If pattern is string it returns itself, if pattern is SRE_Pattern then return pattern attribute :param pattern: pattern object or string :return: str: pattern sttring """ if isinstance(pattern, str): return repr(patter...
python
{ "resource": "" }
q58074
levenshtein_distance
train
def levenshtein_distance(str_a, str_b): """Calculate the Levenshtein distance between string a and b. :param str_a: String - input string a :param str_b: String - input string b :return: Number - Levenshtein Distance between string a and b """ len_a, len_b = len(str_a), len(str_b) if len_a ...
python
{ "resource": "" }
q58075
parse_inventory
train
def parse_inventory(inventory_output=None): """Parse the inventory text and return udi dict.""" udi = { "name": "", "description": "", "pid": "", "vid": "", "sn": "" } if inventory_output is None: return udi # find the record with chassis text in name...
python
{ "resource": "" }
q58076
normalize_urls
train
def normalize_urls(urls): """Overload urls and make list of lists of urls.""" _urls = [] if isinstance(urls, list): if urls: if isinstance(urls[0], list): # multiple connections (list of the lists) _urls = urls elif isinstance(urls[0], str): ...
python
{ "resource": "" }
q58077
yaml_file_to_dict
train
def yaml_file_to_dict(script_name, path=None): """Read yaml file and return the dict. It assumes the module file exists with the defaults. If the CONDOOR_{SCRIPT_NAME} env is set then the user file from the env is loaded and merged with the default There can be user file located in ~/.condoor director...
python
{ "resource": "" }
q58078
FilteredFile.write
train
def write(self, text): """Override the standard write method to filter the content.""" index = text.find('\n') if index == -1: self._buffer = self._buffer + text else: self._buffer = self._buffer + text[:index + 1] if self._pattern: # p...
python
{ "resource": "" }
q58079
start
train
def start(builtins=False, profile_threads=True): """ Start profiler. """ if profile_threads: threading.setprofile(_callback) _yappi.start(builtins, profile_threads)
python
{ "resource": "" }
q58080
set_clock_type
train
def set_clock_type(type): """ Sets the internal clock type for timing. Profiler shall not have any previous stats. Otherwise an exception is thrown. """ type = type.upper() if type not in CLOCK_TYPES: raise YappiError("Invalid clock type:%s" % (type)) _yappi.set_clock_type(C...
python
{ "resource": "" }
q58081
SMTPStreamReader.read_reply
train
async def read_reply(self): """ Reads a reply from the server. Raises: ConnectionResetError: If the connection with the server is lost (we can't read any response anymore). Or if the server replies without a proper return code. Returns: ...
python
{ "resource": "" }
q58082
make_hop_info_from_url
train
def make_hop_info_from_url(url, verify_reachability=None): """Build HopInfo object from url. It allows only telnet and ssh as a valid protocols. Args: url (str): The url string describing the node. i.e. telnet://username@1.1.1.1. The protocol, username and address portion o...
python
{ "resource": "" }
q58083
HopInfo.is_reachable
train
def is_reachable(self): """Return if host is reachable.""" if self.verify_reachability and \ hasattr(self.verify_reachability, '__call__'): return self.verify_reachability(host=self.hostname, port=self.port) # assume is reachable if can't verify return True
python
{ "resource": "" }
q58084
Driver.enable
train
def enable(self, enable_password): """Change to the privilege mode.""" if self.device.prompt[-1] == '#': self.log("Device is already in privileged mode") return events = [self.password_re, self.device.prompt_re, pexpect.TIMEOUT, pexpect.EOF] transitions = [ ...
python
{ "resource": "" }
q58085
tags.description
train
def description(tag): """ Gets a list of descriptions given the tag. :param str tag: (hyphen-separated) tag. :return: list of string descriptions. The return list can be empty. """ tag_object = Tag(tag) results = [] results.extend(tag_object.descriptions)...
python
{ "resource": "" }
q58086
Posterior.prior_draw
train
def prior_draw(self, N=1): """ Draw ``N`` samples from the prior. """ p = np.random.ranf(size=(N, self.ndim)) p = (self._upper_right - self._lower_left) * p + self._lower_left return p
python
{ "resource": "" }
q58087
Posterior.lnprior
train
def lnprior(self, X): """ Use a uniform, bounded prior. """ if np.any(X < self._lower_left) or np.any(X > self._upper_right): return -np.inf else: return 0.0
python
{ "resource": "" }
q58088
Posterior.lnlike
train
def lnlike(self, X): """ Use a softened version of the interpolant as a likelihood. """ return -3.5*np.log(self._interpolant(X[0], X[1], grid=False))
python
{ "resource": "" }
q58089
echo_info
train
def echo_info(conn): """Print detected information.""" click.echo("General information:") click.echo(" Hostname: {}".format(conn.hostname)) click.echo(" HW Family: {}".format(conn.family)) click.echo(" HW Platform: {}".format(conn.platform)) click.echo(" SW Type: {}".format(conn.os_type)) cl...
python
{ "resource": "" }
q58090
run
train
def run(url, cmd, log_path, log_level, log_session, force_discovery, print_info): """Run the main function.""" log_level = log_levels[log_level] conn = condoor.Connection("host", list(url), log_session=log_session, log_level=log_level, log_dir=log_path) try: conn.connect(force_discovery=force_di...
python
{ "resource": "" }
q58091
URL.convert
train
def convert(self, value, param, ctx): """Convert to URL scheme.""" if not isinstance(value, tuple): parsed = urlparse.urlparse(value) if parsed.scheme not in ('telnet', 'ssh'): self.fail('invalid URL scheme (%s). Only telnet and ssh URLs are ' ...
python
{ "resource": "" }
q58092
a_send_line
train
def a_send_line(text, ctx): """Send text line to the controller followed by `os.linesep`.""" if hasattr(text, '__iter__'): try: ctx.ctrl.sendline(text.next()) except StopIteration: ctx.finished = True else: ctx.ctrl.sendline(text) return True
python
{ "resource": "" }
q58093
a_send_username
train
def a_send_username(username, ctx): """Sent the username text.""" if username: ctx.ctrl.sendline(username) return True else: ctx.ctrl.disconnect() raise ConnectionAuthenticationError("Username not provided", ctx.ctrl.hostname)
python
{ "resource": "" }
q58094
a_send_password
train
def a_send_password(password, ctx): """Send the password text. Before sending the password local echo is disabled. If password not provided it disconnects from the device and raises ConnectionAuthenticationError exception. """ if password: ctx.ctrl.send_command(password, password=True) ...
python
{ "resource": "" }
q58095
a_standby_console
train
def a_standby_console(ctx): """Raise ConnectionError exception when connected to standby console.""" ctx.device.is_console = True ctx.ctrl.disconnect() raise ConnectionError("Standby console", ctx.ctrl.hostname)
python
{ "resource": "" }
q58096
a_not_committed
train
def a_not_committed(ctx): """Provide the message that current software is not committed and reload is not possible.""" ctx.ctrl.sendline('n') ctx.msg = "Some active software packages are not yet committed. Reload may cause software rollback." ctx.device.chain.connection.emit_message(ctx.msg, log_level=l...
python
{ "resource": "" }
q58097
a_stays_connected
train
def a_stays_connected(ctx): """Stay connected.""" ctx.ctrl.connected = True ctx.device.connected = False return True
python
{ "resource": "" }
q58098
a_unexpected_prompt
train
def a_unexpected_prompt(ctx): """Provide message when received humphost prompt.""" prompt = ctx.ctrl.match.group(0) ctx.msg = "Received the jump host prompt: '{}'".format(prompt) ctx.device.connected = False ctx.finished = True raise ConnectionError("Unable to connect to the device.", ctx.ctrl.h...
python
{ "resource": "" }
q58099
a_connection_timeout
train
def a_connection_timeout(ctx): """Check the prompt and update the drivers.""" prompt = ctx.ctrl.after ctx.msg = "Received the jump host prompt: '{}'".format(prompt) ctx.device.connected = False ctx.finished = True raise ConnectionTimeoutError("Unable to connect to the device.", ctx.ctrl.hostname...
python
{ "resource": "" }