_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q55300 | get_descriptions | train | def get_descriptions(fastas):
"""
get the description for each ORF
"""
id2desc = {}
for fasta in fastas:
for seq in parse_fasta(fasta):
header = seq[0].split('>')[1].split(' ')
id = header[0]
if len(header) > 1:
desc = ' '.join(header[1:])... | python | {
"resource": ""
} |
q55301 | print_genome_matrix | train | def print_genome_matrix(hits, fastas, id2desc, file_name):
"""
optimize later? slow ...
should combine with calculate_threshold module
"""
out = open(file_name, 'w')
fastas = sorted(fastas)
print('## percent identity between genomes', file=out)
print('# - \t %s' % ('\t'.join(fastas)), fi... | python | {
"resource": ""
} |
q55302 | self_compare | train | def self_compare(fastas, id2desc, algorithm):
"""
compare genome to self to get the best possible bit score for each ORF
"""
for fasta in fastas:
blast = open(search(fasta, fasta, method = algorithm, alignment = 'local'))
for hit in best_blast(blast, 1):
id, bit = hit[0].spli... | python | {
"resource": ""
} |
q55303 | calc_thresholds | train | def calc_thresholds(rbh, file_name, thresholds = [False, False, False, False], stdevs = 2):
"""
if thresholds are not specififed, calculate based on the distribution of normalized bit scores
"""
calc_threshold = thresholds[-1]
norm_threshold = {}
for pair in itertools.permutations([i for i in rb... | python | {
"resource": ""
} |
q55304 | neto | train | def neto(fastas, algorithm = 'usearch', e = 0.01, bit = 40, length = .65, norm_bit = False):
"""
make and split a rbh network
"""
thresholds = [e, bit, length, norm_bit]
id2desc = get_descriptions(fastas)
# get [fasta, description, length] for ORF id
id2desc = self_compare(fastas, id... | python | {
"resource": ""
} |
q55305 | IsoParser._parse_raster_info | train | def _parse_raster_info(self, prop=RASTER_INFO):
""" Collapses multiple dimensions into a single raster_info complex struct """
raster_info = {}.fromkeys(_iso_definitions[prop], u'')
# Ensure conversion of lists to newlines is in place
raster_info['dimensions'] = get_default_for_complex... | python | {
"resource": ""
} |
q55306 | IsoParser._update_raster_info | train | def _update_raster_info(self, **update_props):
""" Derives multiple dimensions from a single raster_info complex struct """
tree_to_update = update_props['tree_to_update']
prop = update_props['prop']
values = update_props.pop('values')
# Update number of dimensions at raster_in... | python | {
"resource": ""
} |
q55307 | IsoParser._trim_xpath | train | def _trim_xpath(self, xpath, prop):
""" Removes primitive type tags from an XPATH """
xroot = self._get_xroot_for(prop)
if xroot is None and isinstance(xpath, string_types):
xtags = xpath.split(XPATH_DELIM)
if xtags[-1] in _iso_tag_primitives:
xroot = X... | python | {
"resource": ""
} |
q55308 | shortcut_app_id | train | def shortcut_app_id(shortcut):
"""
Generates the app id for a given shortcut. Steam uses app ids as a unique
identifier for games, but since shortcuts dont have a canonical serverside
representation they need to be generated on the fly. The important part
about this function is that it will generate the same ... | python | {
"resource": ""
} |
q55309 | VCS._config | train | def _config(self):
"""Execute git config."""
cfg_wr = self.repo.config_writer()
cfg_wr.add_section('user')
cfg_wr.set_value('user', 'name', self.metadata.author)
cfg_wr.set_value('user', 'email', self.metadata.email)
cfg_wr.release() | python | {
"resource": ""
} |
q55310 | VCS._remote_add | train | def _remote_add(self):
"""Execute git remote add."""
self.repo.create_remote(
'origin',
'git@github.com:{username}/{repo}.git'.format(
username=self.metadata.username,
repo=self.metadata.name)) | python | {
"resource": ""
} |
q55311 | BaseScript.start | train | def start(self):
'''
Starts execution of the script
'''
# invoke the appropriate sub-command as requested from command-line
try:
self.args.func()
except SystemExit as e:
if e.code != 0:
raise
except KeyboardInterrupt:
... | python | {
"resource": ""
} |
q55312 | BaseScript.define_baseargs | train | def define_baseargs(self, parser):
'''
Define basic command-line arguments required by the script.
@parser is a parser object created using the `argparse` module.
returns: None
'''
parser.add_argument('--name', default=sys.argv[0],
help='Name to identify this ... | python | {
"resource": ""
} |
q55313 | SourceCoder.cleanup_payload | train | def cleanup_payload(self, payload):
"""
Basically, turns payload that looks like ' \\n ' to ''. In the
calling function, if this function returns '' no object is added
for that payload.
"""
p = payload.replace('\n', '')
p = p.rstrip()
p = p.lstrip()
... | python | {
"resource": ""
} |
q55314 | get_default_for | train | def get_default_for(prop, value):
""" Ensures complex property types have the correct default values """
prop = prop.strip('_') # Handle alternate props (leading underscores)
val = reduce_value(value) # Filtering of value happens here
if prop in _COMPLEX_LISTS:
return wrap_value(val)
... | python | {
"resource": ""
} |
q55315 | update_property | train | def update_property(tree_to_update, xpath_root, xpaths, prop, values, supported=None):
"""
Either update the tree the default way, or call the custom updater
Default Way: Existing values in the tree are overwritten. If xpaths contains a single path,
then each value is written to the tree at that path. ... | python | {
"resource": ""
} |
q55316 | _update_property | train | def _update_property(tree_to_update, xpath_root, xpaths, values):
"""
Default update operation for a single parser property. If xpaths contains one xpath,
then one element per value will be inserted at that location in the tree_to_update;
otherwise, the number of values must match the number of xpaths.
... | python | {
"resource": ""
} |
q55317 | validate_complex | train | def validate_complex(prop, value, xpath_map=None):
""" Default validation for single complex data structure """
if value is not None:
validate_type(prop, value, dict)
if prop in _complex_definitions:
complex_keys = _complex_definitions[prop]
else:
complex_keys =... | python | {
"resource": ""
} |
q55318 | validate_complex_list | train | def validate_complex_list(prop, value, xpath_map=None):
""" Default validation for Attribute Details data structure """
if value is not None:
validate_type(prop, value, (dict, list))
if prop in _complex_definitions:
complex_keys = _complex_definitions[prop]
else:
... | python | {
"resource": ""
} |
q55319 | validate_dates | train | def validate_dates(prop, value, xpath_map=None):
""" Default validation for Date Types data structure """
if value is not None:
validate_type(prop, value, dict)
date_keys = set(value)
if date_keys:
if DATE_TYPE not in date_keys or DATE_VALUES not in date_keys:
... | python | {
"resource": ""
} |
q55320 | validate_process_steps | train | def validate_process_steps(prop, value):
""" Default validation for Process Steps data structure """
if value is not None:
validate_type(prop, value, (dict, list))
procstep_keys = set(_complex_definitions[prop])
for idx, procstep in enumerate(wrap_value(value)):
ps_idx = p... | python | {
"resource": ""
} |
q55321 | validate_type | train | def validate_type(prop, value, expected):
""" Default validation for all types """
# Validate on expected type(s), but ignore None: defaults handled elsewhere
if value is not None and not isinstance(value, expected):
_validation_error(prop, type(value).__name__, None, expected) | python | {
"resource": ""
} |
q55322 | _validation_error | train | def _validation_error(prop, prop_type, prop_value, expected):
""" Default validation for updated properties """
if prop_type is None:
attrib = 'value'
assigned = prop_value
else:
attrib = 'type'
assigned = prop_type
raise ValidationError(
'Invalid property {attr... | python | {
"resource": ""
} |
q55323 | ParserProperty.get_prop | train | def get_prop(self, prop):
""" Calls the getter with no arguments and returns its value """
if self._parser is None:
raise ConfigurationError('Cannot call ParserProperty."get_prop" with no parser configured')
return self._parser(prop) if prop else self._parser() | python | {
"resource": ""
} |
q55324 | can_group_commands | train | def can_group_commands(command, next_command):
"""
Returns a boolean representing whether these commands can be
grouped together or not.
A few things are taken into account for this decision:
For ``set`` commands:
- Are all arguments other than the key/value the same?
For ``delete`` and ... | python | {
"resource": ""
} |
q55325 | find_databases | train | def find_databases(databases):
"""
define ribosomal proteins and location of curated databases
"""
# 16 ribosomal proteins in their expected order
proteins = ['L15', 'L18', 'L6', 'S8', 'L5', 'L24', 'L14',
'S17', 'L16', 'S3', 'L22', 'S19', 'L2', 'L4', 'L3', 'S10']
# curated databases
... | python | {
"resource": ""
} |
q55326 | find_next | train | def find_next(start, stop, i2hits):
"""
which protein has the best hit, the one to the 'right' or to the 'left?'
"""
if start not in i2hits and stop in i2hits:
index = stop
elif stop not in i2hits and start in i2hits:
index = start
elif start not in i2hits and stop not in i2hits:... | python | {
"resource": ""
} |
q55327 | find_ribosomal | train | def find_ribosomal(rps, scaffolds, s2rp, min_hits, max_hits_rp, max_errors):
"""
determine which hits represent real ribosomal proteins, identify each in syntenic block
max_hits_rp = maximum number of hits to consider per ribosomal protein per scaffold
"""
for scaffold, proteins in list(s2rp.items()... | python | {
"resource": ""
} |
q55328 | filter_rep_set | train | def filter_rep_set(inF, otuSet):
"""
Parse the rep set file and remove all sequences not associated with unique
OTUs.
:@type inF: file
:@param inF: The representative sequence set
:@rtype: list
:@return: The set of sequences associated with unique OTUs
"""
seqs = []
for record ... | python | {
"resource": ""
} |
q55329 | ArcGISParser._update_report_item | train | def _update_report_item(self, **update_props):
""" Update the text for each element at the configured path if attribute matches """
tree_to_update = update_props['tree_to_update']
prop = update_props['prop']
values = wrap_value(update_props['values'])
xroot = self._get_xroot_for... | python | {
"resource": ""
} |
q55330 | VCNL4010._clear_interrupt | train | def _clear_interrupt(self, intbit):
"""Clear the specified interrupt bit in the interrupt status register.
"""
int_status = self._device.readU8(VCNL4010_INTSTAT);
int_status &= ~intbit;
self._device.write8(VCNL4010_INTSTAT, int_status); | python | {
"resource": ""
} |
q55331 | SimAlg.move | train | def move(self):
"""Swaps two nodes"""
a = random.randint(0, len(self.state) - 1)
b = random.randint(0, len(self.state) - 1)
self.state[[a,b]] = self.state[[b,a]] | python | {
"resource": ""
} |
q55332 | CertificateBuilder.self_signed | train | def self_signed(self, value):
"""
A bool - if the certificate should be self-signed.
"""
self._self_signed = bool(value)
if self._self_signed:
self._issuer = None | python | {
"resource": ""
} |
q55333 | CertificateBuilder._get_crl_url | train | def _get_crl_url(self, distribution_points):
"""
Grabs the first URL out of a asn1crypto.x509.CRLDistributionPoints
object
:param distribution_points:
The x509.CRLDistributionPoints object to pull the URL out of
:return:
A unicode string or None
... | python | {
"resource": ""
} |
q55334 | CertificateBuilder.ocsp_no_check | train | def ocsp_no_check(self, value):
"""
A bool - if the certificate should have the OCSP no check extension.
Only applicable to certificates created for signing OCSP responses.
Such certificates should normally be issued for a very short period of
time since they are effectively whit... | python | {
"resource": ""
} |
q55335 | emptylineless | train | def emptylineless(parser, token):
"""
Removes empty line.
Example usage::
{% emptylineless %}
test1
test2
test3
{% endemptylineless %}
This example would return this HTML::
test1
test2
test3
"""
nodeli... | python | {
"resource": ""
} |
q55336 | http_purge_url | train | def http_purge_url(url):
"""
Do an HTTP PURGE of the given asset.
The URL is run through urlparse and must point to the varnish instance not the varnishadm
"""
url = urlparse(url)
connection = HTTPConnection(url.hostname, url.port or 80)
path = url.path or '/'
connection.request('PURGE',... | python | {
"resource": ""
} |
q55337 | run | train | def run(addr, *commands, **kwargs):
"""
Non-threaded batch command runner returning output results
"""
results = []
handler = VarnishHandler(addr, **kwargs)
for cmd in commands:
if isinstance(cmd, tuple) and len(cmd)>1:
results.extend([getattr(handler, c[0].replace('.','_'))(... | python | {
"resource": ""
} |
q55338 | SuperMarkdown.add_stylesheets | train | def add_stylesheets(self, *css_files):
"""add stylesheet files in HTML head"""
for css_file in css_files:
self.main_soup.style.append(self._text_file(css_file)) | python | {
"resource": ""
} |
q55339 | SuperMarkdown.add_javascripts | train | def add_javascripts(self, *js_files):
"""add javascripts files in HTML body"""
# create the script tag if don't exists
if self.main_soup.script is None:
script_tag = self.main_soup.new_tag('script')
self.main_soup.body.append(script_tag)
for js_file in js_files:
... | python | {
"resource": ""
} |
q55340 | SuperMarkdown.export | train | def export(self):
"""return the object in a file"""
with open(self.export_url, 'w', encoding='utf-8') as file:
file.write(self.build())
if self.open_browser:
webbrowser.open_new_tab(self.export_url) | python | {
"resource": ""
} |
q55341 | SuperMarkdown.build | train | def build(self):
"""convert Markdown text as html. return the html file as string"""
markdown_html = markdown.markdown(self.markdown_text, extensions=[
TocExtension(), 'fenced_code', 'markdown_checklist.extension',
'markdown.extensions.tables'])
markdown_soup = Be... | python | {
"resource": ""
} |
q55342 | SuperMarkdown._text_file | train | def _text_file(self, url):
"""return the content of a file"""
try:
with open(url, 'r', encoding='utf-8') as file:
return file.read()
except FileNotFoundError:
print('File `{}` not found'.format(url))
sys.exit(0) | python | {
"resource": ""
} |
q55343 | SuperMarkdown._text_to_graphiz | train | def _text_to_graphiz(self, text):
"""create a graphviz graph from text"""
dot = Source(text, format='svg')
return dot.pipe().decode('utf-8') | python | {
"resource": ""
} |
q55344 | SuperMarkdown._add_mermaid_js | train | def _add_mermaid_js(self):
"""add js libraries and css files of mermaid js_file"""
self.add_javascripts('{}/js/jquery-1.11.3.min.js'.format(self.resources_path))
self.add_javascripts('{}/js/mermaid.min.js'.format(self.resources_path))
self.add_stylesheets('{}/css/mermaid.css'.format(self... | python | {
"resource": ""
} |
q55345 | StringGenerator.getCharacterSet | train | def getCharacterSet(self):
'''Get a character set with individual members or ranges.
Current index is on '[', the start of the character set.
'''
chars = u''
c = None
cnt = 1
start = 0
while True:
escaped_slash = False
c... | python | {
"resource": ""
} |
q55346 | StringGenerator.getLiteral | train | def getLiteral(self):
'''Get a sequence of non-special characters.'''
# we are on the first non-special character
chars = u''
c = self.current()
while True:
if c and c == u"\\":
c = self.next()
if c:
chars += c
... | python | {
"resource": ""
} |
q55347 | StringGenerator.getSequence | train | def getSequence(self, level=0):
'''Get a sequence of nodes.'''
seq = []
op = ''
left_operand = None
right_operand = None
sequence_closed = False
while True:
c = self.next()
if not c:
break
if c and c not in self... | python | {
"resource": ""
} |
q55348 | StringGenerator.dump | train | def dump(self, **kwargs):
import sys
'''Print the parse tree and then call render for an example.'''
if not self.seq:
self.seq = self.getSequence()
print("StringGenerator version: %s" % (__version__))
print("Python version: %s" % sys.version)
# this doesn't wo... | python | {
"resource": ""
} |
q55349 | StringGenerator.render_list | train | def render_list(self, cnt, unique=False, progress_callback=None, **kwargs):
'''Return a list of generated strings.
Args:
cnt (int): length of list
unique (bool): whether to make entries unique
Returns:
list.
We keep track of total attempts because a... | python | {
"resource": ""
} |
q55350 | S3utils.connect | train | def connect(self):
"""
Establish the connection. This is done automatically for you.
If you lose the connection, you can manually run this to be re-connected.
"""
self.conn = boto.connect_s3(self.AWS_ACCESS_KEY_ID, self.AWS_SECRET_ACCESS_KEY, debug=self.S3UTILS_DEBUG_LEVEL)
... | python | {
"resource": ""
} |
q55351 | S3utils.connect_cloudfront | train | def connect_cloudfront(self):
"Connect to Cloud Front. This is done automatically for you when needed."
self.conn_cloudfront = connect_cloudfront(self.AWS_ACCESS_KEY_ID, self.AWS_SECRET_ACCESS_KEY, debug=self.S3UTILS_DEBUG_LEVEL) | python | {
"resource": ""
} |
q55352 | S3utils.mkdir | train | def mkdir(self, target_folder):
"""
Create a folder on S3.
Examples
--------
>>> s3utils.mkdir("path/to/my_folder")
Making directory: path/to/my_folder
"""
self.printv("Making directory: %s" % target_folder)
self.k.key = re.sub(r"^/|/$", "... | python | {
"resource": ""
} |
q55353 | S3utils.rm | train | def rm(self, path):
"""
Delete the path and anything under the path.
Example
-------
>>> s3utils.rm("path/to/file_or_folder")
"""
list_of_files = list(self.ls(path))
if list_of_files:
if len(list_of_files) == 1:
self.buck... | python | {
"resource": ""
} |
q55354 | S3utils.__put_key | train | def __put_key(self, local_file, target_file, acl='public-read', del_after_upload=False, overwrite=True, source="filename"):
"""Copy a file to s3."""
action_word = "moving" if del_after_upload else "copying"
try:
self.k.key = target_file # setting the path (key) of file in the conta... | python | {
"resource": ""
} |
q55355 | S3utils.cp | train | def cp(self, local_path, target_path, acl='public-read',
del_after_upload=False, overwrite=True, invalidate=False):
"""
Copy a file or folder from local to s3.
Parameters
----------
local_path : string
Path to file or folder. Or if you want to copy only t... | python | {
"resource": ""
} |
q55356 | S3utils.mv | train | def mv(self, local_file, target_file, acl='public-read', overwrite=True, invalidate=False):
"""
Similar to Linux mv command.
Move the file to the S3 and deletes the local copy
It is basically s3utils.cp that has del_after_upload=True
Examples
--------
>>> s... | python | {
"resource": ""
} |
q55357 | S3utils.cp_cropduster_image | train | def cp_cropduster_image(self, the_image_path, del_after_upload=False, overwrite=False, invalidate=False):
"""
Deal with saving cropduster images to S3. Cropduster is a Django library for resizing editorial images.
S3utils was originally written to put cropduster images on S3 bucket.
Ext... | python | {
"resource": ""
} |
q55358 | S3utils.chmod | train | def chmod(self, target_file, acl='public-read'):
"""
sets permissions for a file on S3
Parameters
----------
target_file : string
Path to file on S3
acl : string, optional
File permissions on S3. Default is public-read
options:
... | python | {
"resource": ""
} |
q55359 | S3utils.ll | train | def ll(self, folder="", begin_from_file="", num=-1, all_grant_data=False):
"""
Get the list of files and permissions from S3.
This is similar to LL (ls -lah) in Linux: List of files with permissions.
Parameters
----------
folder : string
Path to file on S3
... | python | {
"resource": ""
} |
q55360 | get_path | train | def get_path(url):
"""
Get the path from a given url, including the querystring.
Args:
url (str)
Returns:
str
"""
url = urlsplit(url)
path = url.path
if url.query:
path += "?{}".format(url.query)
return path | python | {
"resource": ""
} |
q55361 | Build.run | train | def run(self):
"""Reads data from disk and generates CSV files."""
# Try to create the directory
if not os.path.exists(self.output):
try:
os.mkdir(self.output)
except:
print 'failed to create output directory %s' % self.output
# Be... | python | {
"resource": ""
} |
q55362 | Index.process_fields | train | def process_fields(self, fields):
"""Process a list of simple string field definitions and assign their order based on prefix."""
result = []
strip = ''.join(self.PREFIX_MAP)
for field in fields:
direction = self.PREFIX_MAP['']
if field[0] in self.PREFIX_MAP:
direction = self.PREFIX_MAP[fiel... | python | {
"resource": ""
} |
q55363 | API.search_in_rubric | train | def search_in_rubric(self, **kwargs):
"""Firms search in rubric
http://api.2gis.ru/doc/firms/searches/searchinrubric/
"""
point = kwargs.pop('point', False)
if point:
kwargs['point'] = '%s,%s' % point
bound = kwargs.pop('bound', False)
if bound:
... | python | {
"resource": ""
} |
q55364 | RetoxRefreshMixin.refresh | train | def refresh(self):
'''
Refresh the list and the screen
'''
self._screen.force_update()
self._screen.refresh()
self._update(1) | python | {
"resource": ""
} |
q55365 | VirtualEnvironmentFrame.start | train | def start(self, activity, action):
'''
Mark an action as started
:param activity: The virtualenv activity name
:type activity: ``str``
:param action: The virtualenv action
:type action: :class:`tox.session.Action`
'''
try:
self._start_actio... | python | {
"resource": ""
} |
q55366 | VirtualEnvironmentFrame.stop | train | def stop(self, activity, action):
'''
Mark a task as completed
:param activity: The virtualenv activity name
:type activity: ``str``
:param action: The virtualenv action
:type action: :class:`tox.session.Action`
'''
try:
self._remove_runnin... | python | {
"resource": ""
} |
q55367 | VirtualEnvironmentFrame.finish | train | def finish(self, status):
'''
Move laggard tasks over
:param activity: The virtualenv status
:type activity: ``str``
'''
retox_log.info("Completing %s with status %s" % (self.name, status))
result = Screen.COLOUR_GREEN if not status else Screen.COLOUR_RED
... | python | {
"resource": ""
} |
q55368 | VirtualEnvironmentFrame.reset | train | def reset(self):
'''
Reset the frame between jobs
'''
self.palette['title'] = (Screen.COLOUR_WHITE, Screen.A_BOLD, Screen.COLOUR_BLUE)
self._completed_view.options = []
self._task_view.options = []
self.refresh() | python | {
"resource": ""
} |
q55369 | Decorator.default_arguments | train | def default_arguments(cls):
"""Returns the available kwargs of the called class"""
func = cls.__init__
args = func.__code__.co_varnames
defaults = func.__defaults__
index = -len(defaults)
return {k: v for k, v in zip(args[index:], defaults)} | python | {
"resource": ""
} |
q55370 | Decorator.recreate | train | def recreate(cls, *args, **kwargs):
"""Recreate the class based in your args, multiple uses"""
cls.check_arguments(kwargs)
first_is_callable = True if any(args) and callable(args[0]) else False
signature = cls.default_arguments()
allowed_arguments = {k: v for k, v in kwargs.items... | python | {
"resource": ""
} |
q55371 | Decorator.check_arguments | train | def check_arguments(cls, passed):
"""Put warnings of arguments whose can't be handle by the class"""
defaults = list(cls.default_arguments().keys())
template = ("Pass arg {argument:!r} in {cname:!r}, can be a typo? "
"Supported key arguments: {defaults}")
fails = []
... | python | {
"resource": ""
} |
q55372 | Builder.process | train | def process(self, data, type, history):
""" process the specified type then process its children """
if type in history:
return
if type.enum():
return
history.append(type)
resolved = type.resolve()
value = None
if type.multi_occurrence():
... | python | {
"resource": ""
} |
q55373 | Builder.skip_child | train | def skip_child(self, child, ancestry):
""" get whether or not to skip the specified child """
if child.any(): return True
for x in ancestry:
if x.choice():
return True
return False | python | {
"resource": ""
} |
q55374 | active_knocks | train | def active_knocks(obj):
"""
Checks whether knocks are enabled for the model given as argument
:param obj: model instance
:return True if knocks are active
"""
if not hasattr(_thread_locals, 'knock_enabled'):
return True
return _thread_locals.knock_enabled.get(obj.__class__, True) | python | {
"resource": ""
} |
q55375 | pause_knocks | train | def pause_knocks(obj):
"""
Context manager to suspend sending knocks for the given model
:param obj: model instance
"""
if not hasattr(_thread_locals, 'knock_enabled'):
_thread_locals.knock_enabled = {}
obj.__class__._disconnect()
_thread_locals.knock_enabled[obj.__class__] = False
... | python | {
"resource": ""
} |
q55376 | RetoxReporter._loopreport | train | def _loopreport(self):
'''
Loop over the report progress
'''
while 1:
eventlet.sleep(0.2)
ac2popenlist = {}
for action in self.session._actions:
for popen in action._popenlist:
if popen.poll() is None:
... | python | {
"resource": ""
} |
q55377 | send | train | def send(email, subject=None,
from_email=None, to_email=None,
cc=None, bcc=None, reply_to=None,
smtp=None):
"""Send markdown email
Args:
email (str/obj): A markdown string or EmailContent object
subject (str): subject line
from_email (str): sender email addre... | python | {
"resource": ""
} |
q55378 | Date._process_tz | train | def _process_tz(self, dt, naive, tz):
"""Process timezone casting and conversion."""
def _tz(t):
if t in (None, 'naive'):
return t
if t == 'local':
if __debug__ and not localtz:
raise ValueError("Requested conversion to local timezone, but `localtz` not installed.")
t = localtz
... | python | {
"resource": ""
} |
q55379 | Document._prepare_defaults | train | def _prepare_defaults(self):
"""Trigger assignment of default values."""
for name, field in self.__fields__.items():
if field.assign:
getattr(self, name) | python | {
"resource": ""
} |
q55380 | Document.from_mongo | train | def from_mongo(cls, doc):
"""Convert data coming in from the MongoDB wire driver into a Document instance."""
if doc is None: # To support simplified iterative use, None should return None.
return None
if isinstance(doc, Document): # No need to perform processing on existing Document instances.
retu... | python | {
"resource": ""
} |
q55381 | Document.pop | train | def pop(self, name, default=SENTINEL):
"""Retrieve and remove a value from the backing store, optionally with a default."""
if default is SENTINEL:
return self.__data__.pop(name)
return self.__data__.pop(name, default) | python | {
"resource": ""
} |
q55382 | Q._op | train | def _op(self, operation, other, *allowed):
"""A basic operation operating on a single value."""
f = self._field
if self._combining: # We are a field-compound query fragment, e.g. (Foo.bar & Foo.baz).
return reduce(self._combining,
(q._op(operation, other, *allowed) for q in f)) # pylint:disable=pr... | python | {
"resource": ""
} |
q55383 | Q._iop | train | def _iop(self, operation, other, *allowed):
"""An iterative operation operating on multiple values.
Consumes iterators to construct a concrete list at time of execution.
"""
f = self._field
if self._combining: # We are a field-compound query fragment, e.g. (Foo.bar & Foo.baz).
return reduce(self.... | python | {
"resource": ""
} |
q55384 | HopcroftKarp.__dfs | train | def __dfs(self, v, index, layers):
"""
we recursively run dfs on each vertices in free_vertex,
:param v: vertices in free_vertex
:return: True if P is not empty (i.e., the maximal set of vertex-disjoint alternating path of length k)
and false otherwise.
"""
if in... | python | {
"resource": ""
} |
q55385 | Parser.method | train | def method(self, symbol):
'''
Symbol decorator.
'''
assert issubclass(symbol, SymbolBase)
def wrapped(fn):
setattr(symbol, fn.__name__, fn)
return wrapped | python | {
"resource": ""
} |
q55386 | _simpleparsefun | train | def _simpleparsefun(date):
"""Simple date parsing function"""
if hasattr(date, 'year'):
return date
try:
date = datetime.datetime.strptime(date, '%Y-%m-%d')
except ValueError:
date = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
return date | python | {
"resource": ""
} |
q55387 | KnockerModel._connect | train | def _connect(cls):
"""
Connect signal to current model
"""
post_save.connect(
notify_items, sender=cls,
dispatch_uid='knocker_{0}'.format(cls.__name__)
) | python | {
"resource": ""
} |
q55388 | KnockerModel._disconnect | train | def _disconnect(cls):
"""
Disconnect signal from current model
"""
post_save.disconnect(
notify_items, sender=cls,
dispatch_uid='knocker_{0}'.format(cls.__name__)
) | python | {
"resource": ""
} |
q55389 | KnockerModel.as_knock | train | def as_knock(self, created=False):
"""
Returns a dictionary with the knock data built from _knocker_data
"""
knock = {}
if self.should_knock(created):
for field, data in self._retrieve_data(None, self._knocker_data):
knock[field] = data
return ... | python | {
"resource": ""
} |
q55390 | KnockerModel.send_knock | train | def send_knock(self, created=False):
"""
Send the knock in the associated channels Group
"""
knock = self.as_knock(created)
if knock:
gr = Group('knocker-{0}'.format(knock['language']))
gr.send({'text': json.dumps(knock)}) | python | {
"resource": ""
} |
q55391 | colorize | train | def colorize(printable, color, style='normal', autoreset=True):
"""Colorize some message with ANSI colors specification
:param printable: interface whose has __str__ or __repr__ method
:param color: the colors defined in COLOR_MAP to colorize the text
:style: can be 'normal', 'bold' or 'underline'
... | python | {
"resource": ""
} |
q55392 | color | train | def color(string, status=True, warning=False, bold=True):
"""
Change text color for the linux terminal, defaults to green.
Set "warning=True" for red.
"""
attr = []
if status:
# green
attr.append('32')
if warning:
# red
attr.append('31')
if bold:
a... | python | {
"resource": ""
} |
q55393 | _patch | train | def _patch():
"""Patch pymongo's Collection object to add a tail method.
While not nessicarily recommended, you can use this to inject `tail` as a method into Collection, making it
generally accessible.
"""
if not __debug__: # pragma: no cover
import warnings
warnings.warn("A catgirl has died.", ImportWar... | python | {
"resource": ""
} |
q55394 | Queryable._prepare_find | train | def _prepare_find(cls, *args, **kw):
"""Execute a find and return the resulting queryset using combined plain and parametric query generation.
Additionally, performs argument case normalization, refer to the `_prepare_query` method's docstring.
"""
cls, collection, query, options = cls._prepare_query(
... | python | {
"resource": ""
} |
q55395 | Queryable.reload | train | def reload(self, *fields, **kw):
"""Reload the entire document from the database, or refresh specific named top-level fields."""
Doc, collection, query, options = self._prepare_find(id=self.id, projection=fields, **kw)
result = collection.find_one(query, **options)
if fields: # Refresh only the requested... | python | {
"resource": ""
} |
q55396 | Pconf.get | train | def get(cls):
"""Get values gathered from the previously set hierarchy.
Respects the order in which sources are set, the first source set
has the highest priority, overrides values with the same key that
exist in sources with lower priority.
Returns:
dict: The dicti... | python | {
"resource": ""
} |
q55397 | Pconf.argv | train | def argv(cls, name, short_name=None, type=None, help=None):
""" Set command line arguments as a source
Parses the command line arguments described by the parameters.
Args:
name: the long name of the argument (foo)
short_name: the optional short name of the argument (f)
... | python | {
"resource": ""
} |
q55398 | Pconf.env | train | def env(cls, separator=None, match=None, whitelist=None, parse_values=None, to_lower=None, convert_underscores=None):
"""Set environment variables as a source.
By default all environment variables available to the process are used.
This can be narrowed by the args.
Args:
se... | python | {
"resource": ""
} |
q55399 | Pconf.file | train | def file(cls, path, encoding=None, parser=None):
"""Set a file as a source.
File are parsed as literal python dicts by default, this behaviour
can be configured.
Args:
path: The path to the file to be parsed
encoding: The encoding of the file.
De... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.