_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q50100 | find_comprehension_as_statement | train | def find_comprehension_as_statement(node):
"""Finds a comprehension as a statement"""
return (
isinstance(node, ast.Expr)
and isinstance(node.value, (ast.ListComp,
ast.DictComp,
ast.SetComp))
) | python | {
"resource": ""
} |
q50101 | find_generator_as_statement | train | def find_generator_as_statement(node):
"""Finds a generator as a statement"""
return (
isinstance(node, ast.Expr)
and isinstance(node.value, ast.GeneratorExp)
) | python | {
"resource": ""
} |
q50102 | compareBIMfiles | train | def compareBIMfiles(beforeFileName, afterFileName, outputFileName):
"""Compare two BIM files for differences.
:param beforeFileName: the name of the file before modification.
:param afterFileName: the name of the file after modification.
:param outputFileName: the name of the output file (containing th... | python | {
"resource": ""
} |
q50103 | computeHWE | train | def computeHWE(prefix, threshold, outPrefix):
"""Compute the Hardy Weinberg test using Plink.
:param prefix: the prefix of all the files.
:param threshold: the Hardy Weinberg threshold.
:param outPrefix: the prefix of the output file.
:type prefix: str
:type threshold: str
:type outPrefix:... | python | {
"resource": ""
} |
q50104 | subset_data | train | def subset_data(options):
"""Subset the data.
:param options: the options.
:type options: argparse.Namespace
Subset the data using either ``--exclude`` or ``--extract``for markers or
``--remove`` or ``keep`` for samples.
"""
# The plink command
plinkCommand = ["plink", "--noweb"]
... | python | {
"resource": ""
} |
q50105 | series2df | train | def series2df(Series, layer=2, split_sign = '_'):
"""expect pass a series that each row is string formated Json data with the same structure"""
try:
Series.columns
Series = Series.iloc[:,0]
except:
pass
def _helper(x, layer=2):
try:
return flatten_dict(as... | python | {
"resource": ""
} |
q50106 | LoadFile.convert | train | def convert(self, layer=2, split_sign = '_', *args, **kwargs):
"""convert data to DataFrame"""
return series2df(self.series, *args, **kwargs) | python | {
"resource": ""
} |
q50107 | createSummaryFile | train | def createSummaryFile(results, maf, prefix):
"""Creat the final summary file containing plate bias results.
:param results: the list of all the significant results.
:param maf: the minor allele frequency of the significant results.
:param prefix: the prefix of all the files.
:type results: list
... | python | {
"resource": ""
} |
q50108 | extractSignificantSNPs | train | def extractSignificantSNPs(prefix):
"""Extract significant SNPs in the fisher file.
:param prefix: the prefix of the input file.
:type prefix: str
Reads a list of significant markers (``prefix.assoc.fisher``) after plate
bias analysis with Plink. Writes a file (``prefix.significant_SNPs.txt``)
... | python | {
"resource": ""
} |
q50109 | computeFrequencyOfSignificantSNPs | train | def computeFrequencyOfSignificantSNPs(options):
"""Computes the frequency of the significant markers.
:param options: the options.
:type options: argparse.Namespace
Extract a list of markers (significant after plate bias analysis) and
computes their frequencies.
"""
# The plink command
... | python | {
"resource": ""
} |
q50110 | executePlateBiasAnalysis | train | def executePlateBiasAnalysis(options):
"""Execute the plate bias analysis with Plink.
:param options: the options.
:type options: argparse.Namespace
"""
# The plink command
plinkCommand = ["plink", "--noweb", "--bfile", options.bfile,
"--loop-assoc", options.loop_assoc, "-... | python | {
"resource": ""
} |
q50111 | random_variant | train | def random_variant(variants, weights):
"""
A generator that, given a list of variants and a corresponding list of
weights, returns one random weighted selection.
"""
total = 0
accumulator = []
for w in weights:
total += w
accumulator.append(total)
r = randint(0, total - ... | python | {
"resource": ""
} |
q50112 | parse | train | def parse(duration, context=None):
"""
parse the duration string which contains a human readable duration and
return a datetime.timedelta object representing that duration
arguments:
duration - the duration string following a notation like so:
"1 hour"
"1 m... | python | {
"resource": ""
} |
q50113 | findSnpWithMaf0 | train | def findSnpWithMaf0(freqFileName, prefix):
"""Finds SNPs with MAF of 0 and put them in a file.
:param freqFileName: the name of the frequency file.
:param prefix: the prefix of all the files.
:type freqFileName: str
:type prefix: str
Reads a frequency file from Plink, and find markers with a ... | python | {
"resource": ""
} |
q50114 | init_site | train | def init_site():
"""Initialize a Bower Cache site using the template."""
site_name = 'bowercachesite'
dir_name = sys.argv[1] if len(sys.argv) > 1 else site_name
settings = site_name + ".settings"
template_filename = resource_filename(bowercache.__name__,
'pr... | python | {
"resource": ""
} |
q50115 | airport_codes | train | def airport_codes():
"""
Returns the set of airport codes that is available to be requested.
"""
html = requests.get(URL).text
data_block = _find_data_block(html)
return _airport_codes_from_data_block(data_block) | python | {
"resource": ""
} |
q50116 | json_template | train | def json_template(data, template_name, template_context):
"""Old style, use JSONTemplateResponse instead of this.
"""
html = render_to_string(template_name, template_context)
data = data or {}
data['html'] = html
return HttpResponse(json_encode(data), content_type='application/json') | python | {
"resource": ""
} |
q50117 | check_save | train | def check_save(sender, **kwargs):
"""
Checks item type uniqueness, field applicability and multiplicity.
"""
tag = kwargs['instance']
obj = Tag.get_object(tag)
previous_tags = Tag.get_tags(obj)
err_uniq = check_item_type_uniqueness(tag, previous_tags)
err_appl = check_field_applicab... | python | {
"resource": ""
} |
q50118 | check_item_type_uniqueness | train | def check_item_type_uniqueness(tag, previous_tags):
"""
Check the uniqueness of the 'item type' for an object.
"""
fail = False
#If the tag is being created...
if not tag.id:
#... and the new item type is different from previous item types (for
#example, different from the first ... | python | {
"resource": ""
} |
q50119 | check_field_multiplicity | train | def check_field_multiplicity(tag, previous_tags):
"""
Check the multiplicity of a 'field' for an object.
"""
fail = False
#If the field is single
if not tag.field.multiple:
#If the tag is being created...
if not tag.id:
#... and the new field was already included in t... | python | {
"resource": ""
} |
q50120 | generate_error_message | train | def generate_error_message(tag, err_uniq, err_appl, err_mult):
"""
Generate the error message for an object.
"""
err = []
if err_uniq:
err.append('Uniqueness restriction: item type %s' % tag.item_type)
if err_appl:
err.append('Applicability restriction: field %s' % tag.field)
... | python | {
"resource": ""
} |
q50121 | delete_tags | train | def delete_tags(sender, **kwargs):
"""
Delete the tags pointing to an object.
"""
try:
obj = kwargs.get('instance')
tags = Tag.get_tags(obj)
tags.delete()
except AttributeError:
pass | python | {
"resource": ""
} |
q50122 | CheckstylePlugin.finished | train | def finished(self, filename):
"""Make Checkystyle ElementTree."""
if len(self.errors) < 1:
return
element = ET.SubElement(self.checkstyle_element, 'file', name=filename)
for error in self.errors:
message = error.code + ' ' + error.text
prefix = error.... | python | {
"resource": ""
} |
q50123 | CheckstylePlugin.stop | train | def stop(self):
"""Output Checkstyle XML reports."""
et = ET.ElementTree(self.checkstyle_element)
f = BytesIO()
et.write(f, encoding='utf-8', xml_declaration=True)
xml = f.getvalue().decode('utf-8')
if self.output_fd is None:
print(xml)
else:
... | python | {
"resource": ""
} |
q50124 | processTPEDandTFAM | train | def processTPEDandTFAM(tped, tfam, prefix):
"""Process the TPED and TFAM files.
:param tped: the name of the ``tped`` file.
:param tfam: the name of the ``tfam`` file.
:param prefix: the prefix of the output files.
:type tped: str
:type tfam: str
:type prefix: str
Copies the original ... | python | {
"resource": ""
} |
q50125 | weld_count | train | def weld_count(array):
"""Returns the length of the array.
Parameters
----------
array : numpy.ndarray or WeldObject
Input array.
Returns
-------
WeldObject
Representation of this computation.
"""
obj_id, weld_obj = create_weld_object(array)
weld_template = _w... | python | {
"resource": ""
} |
q50126 | weld_aggregate | train | def weld_aggregate(array, weld_type, operation):
"""Returns operation on the elements in the array.
Arguments
---------
array : WeldObject or numpy.ndarray
Input array.
weld_type : WeldType
Weld type of each element in the input array.
operation : {'+', '*', 'min', 'max'}
... | python | {
"resource": ""
} |
q50127 | weld_mean | train | def weld_mean(array, weld_type):
"""Returns the mean of the array.
Parameters
----------
array : numpy.ndarray or WeldObject
Input array.
weld_type : WeldType
Type of each element in the input array.
Returns
-------
WeldObject
Representation of this computation.... | python | {
"resource": ""
} |
q50128 | weld_variance | train | def weld_variance(array, weld_type):
"""Returns the variance of the array.
Parameters
----------
array : numpy.ndarray or WeldObject
Input array.
weld_type : WeldType
Type of each element in the input array.
Returns
-------
WeldObject
Representation of this comp... | python | {
"resource": ""
} |
q50129 | captchaform | train | def captchaform(field_name):
"""Decorator to add a simple captcha to a form
To use this decorator, you must specify the captcha field's name as an
argument to the decorator. For example:
@captchaform('captcha')
class MyForm(Form):
pass
This would add a new form field named 'captcha' t... | python | {
"resource": ""
} |
q50130 | _validate_incident_date_range | train | def _validate_incident_date_range(incident, numdays):
"""Returns true if incident is within date range"""
try:
datetime_object = datetime.datetime.strptime(incident.get('date'), '%m/%d/%y %I:%M %p')
except ValueError:
raise ValueError("Incorrect date format, should be MM/DD/YY HH:MM AM/PM")
... | python | {
"resource": ""
} |
q50131 | _incident_transform | train | def _incident_transform(incident):
"""Get output dict from incident."""
return {
'id': incident.get('cdid'),
'type': incident.get('type'),
'timestamp': incident.get('date'),
'lat': incident.get('lat'),
'lon': incident.get('lon'),
'location': incident.get('address'... | python | {
"resource": ""
} |
q50132 | SpotCrime.get_incidents | train | def get_incidents(self):
"""Get incidents."""
resp = requests.get(CRIME_URL, params=self._get_params(), headers=self.headers)
incidents = [] # type: List[Dict[str, str]]
data = resp.json()
if ATTR_CRIMES not in data:
return incidents
for incident in data.get(... | python | {
"resource": ""
} |
q50133 | _needs_git | train | def _needs_git(func):
"""
Small decorator to make sure we have the git repo, or report error
otherwise.
"""
@wraps(func)
def myfunc(*args, **kwargs):
if not WITH_GIT:
raise RuntimeError(
"Dulwich library not available, can't extract info from the "
... | python | {
"resource": ""
} |
q50134 | tag_versions | train | def tag_versions(repo_path):
"""
Given a repo will add a tag for each major version.
Args:
repo_path(str): path to the git repository to tag.
"""
repo = dulwich.repo.Repo(repo_path)
tags = get_tags(repo)
maj_version = 0
feat_version = 0
fix_version = 0
last_maj_version =... | python | {
"resource": ""
} |
q50135 | get_releasenotes | train | def get_releasenotes(repo_path, from_commit=None, bugtracker_url=''):
"""
Given a repo and optionally a base revision to start from, will return
a text suitable for the relase notes announcement, grouping the bugs, the
features and the api-breaking changes.
Args:
repo_path(str): Path to the... | python | {
"resource": ""
} |
q50136 | _weld_unary | train | def _weld_unary(array, weld_type, operation):
"""Apply operation on each element in the array.
As mentioned by Weld, the operations follow the behavior of the equivalent C functions from math.h
Parameters
----------
array : numpy.ndarray or WeldObject
Data
weld_type : WeldType
... | python | {
"resource": ""
} |
q50137 | APIClient._stream_raw_result | train | async def _stream_raw_result(self, res):
''' Stream result for TTY-enabled container above API 1.6 '''
async with res.context as response:
response.raise_for_status()
async for out in response.content.iter_chunked(1):
yield out.decode() | python | {
"resource": ""
} |
q50138 | compareBIM | train | def compareBIM(args):
"""Compare two BIM file.
:param args: the options.
:type args: argparse.Namespace
Creates a *Dummy* object to mimic an :py:class:`argparse.Namespace` class
containing the options for the :py:mod:`pyGenClean.PlinkUtils.compare_bim`
module.
"""
# Creating the Comp... | python | {
"resource": ""
} |
q50139 | read | train | def read(mfile, sfile):
""" Returns an IadhoreData object, constructed from the passed
i-ADHoRe multiplicon and segments output.
- mfile (str), location of multiplicons.txt
- sfile (str), location of segments.txt
"""
assert os.path.isfile(mfile), "%s multiplicon file does not exist"... | python | {
"resource": ""
} |
q50140 | IadhoreData._parse_segments | train | def _parse_segments(self):
""" Read the segment output file and parse into an SQLite database.
"""
reader = csv.reader(open(self._segment_file, 'rU'),
delimiter='\t')
for row in reader:
if reader.line_num == 1: # skip header
contin... | python | {
"resource": ""
} |
q50141 | IadhoreData.get_multiplicon_seeds | train | def get_multiplicon_seeds(self, redundant=False):
""" Return a generator of the IDs of multiplicons that are initial
seeding 'pairs' in level 2 multiplicons.
Arguments:
o redundant - if true, report redundant multiplicons
"""
for node in self._multiplicon_gr... | python | {
"resource": ""
} |
q50142 | IadhoreData.get_multiplicon_intermediates | train | def get_multiplicon_intermediates(self, redundant=False):
""" Return a generator of the IDs of multiplicons that are neither
seeding 'pairs' in level 2 multiplicons, nor leaves.
Arguments:
o redundant - if true, report redundant multiplicons
"""
for node in ... | python | {
"resource": ""
} |
q50143 | IadhoreData.get_multiplicons_at_level | train | def get_multiplicons_at_level(self, level, redundant=False):
""" Return a list of IDs of multiplicons at the requested level
"""
sql = '''SELECT id FROM multiplicons
WHERE level=:level'''
cur = self._dbconn.cursor()
cur.execute(sql, {'level': str(level)})
... | python | {
"resource": ""
} |
q50144 | IadhoreData.is_redundant_multiplicon | train | def is_redundant_multiplicon(self, value):
""" Returns True if the passed multiplicon ID is redundant, False
otherwise.
- value, (int) multiplicon ID
"""
if not hasattr(self, '_redundant_multiplicon_cache'):
sql = '''SELECT id FROM multiplicons WHERE is_redun... | python | {
"resource": ""
} |
q50145 | IadhoreData.write | train | def write(self, mfile="multiplicons.txt", sfile="segments.txt",
clobber=False):
""" Writes multiplicon and segment files to the named locations.
- mfile, (str) location for multiplicons file
- sfile, (str) location for segments file
- clobber, (Boolean) True if... | python | {
"resource": ""
} |
q50146 | IadhoreData._write_multiplicons | train | def _write_multiplicons(self, filename):
""" Write multiplicons to file.
- filename, (str) location of output file
"""
# Column headers
mhead = '\t'.join(['id', 'genome_x', 'list_x', 'parent', 'genome_y',
'list_y', 'level', 'number_of_anchorpoints'... | python | {
"resource": ""
} |
q50147 | IadhoreData._write_segments | train | def _write_segments(self, filename):
""" Write segments to file.
- filename, (str) location of output file
"""
# Column headers
shead = '\t'.join(['id', 'multiplicon', 'genome', 'list', 'first',
'last', 'order'])
with open(filename, 'w') as... | python | {
"resource": ""
} |
q50148 | IadhoreData.multiplicon_file | train | def multiplicon_file(self, value):
""" Setter for _multiplicon_file attribute """
assert os.path.isfile(value), "%s is not a valid file" % value
self._multiplicon_file = value | python | {
"resource": ""
} |
q50149 | IadhoreData.segment_file | train | def segment_file(self, value):
""" Setter for _segment_file attribute """
assert os.path.isfile(value), "%s is not a valid file" % value
self._segment_file = value | python | {
"resource": ""
} |
q50150 | IadhoreData.db_file | train | def db_file(self, value):
""" Setter for _db_file attribute """
assert not os.path.isfile(value), "%s already exists" % value
self._db_file = value | python | {
"resource": ""
} |
q50151 | IadhoreData.multiplicons | train | def multiplicons(self):
""" Multiplicon table from SQLite database. """
sql = '''SELECT * FROM multiplicons'''
cur = self._dbconn.cursor()
cur.execute(sql)
data = [r for r in cur.fetchall()]
cur.close()
return data | python | {
"resource": ""
} |
q50152 | compareSNPs | train | def compareSNPs(before, after, outFileName):
"""Compares two set of SNPs.
:param before: the names of the markers in the ``before`` file.
:param after: the names of the markers in the ``after`` file.
:param outFileName: the name of the output file.
:type before: set
:type after: set
:type ... | python | {
"resource": ""
} |
q50153 | readBIM | train | def readBIM(fileName):
"""Reads a BIM file.
:param fileName: the name of the BIM file to read.
:type fileName: str
:returns: the set of markers in the BIM file.
Reads a Plink BIM file and extract the name of the markers. There is one
marker per line, and the name of the marker is in the seco... | python | {
"resource": ""
} |
q50154 | Block.add_attr | train | def add_attr(self, name, value):
"""Add an attribute to an ``Block`` object"""
setattr(self, name, value)
self.attrs.append(name) | python | {
"resource": ""
} |
q50155 | Block.ids | train | def ids(self):
"""Convenience method to get the ids for Materials present"""
assert self.name == "Materials"
ids = list()
for attr in self.attrs:
attr_obj = getattr(self, attr)
if hasattr(attr_obj, 'Id'):
ids.append(getattr(attr_obj, 'Id'))
... | python | {
"resource": ""
} |
q50156 | get_version | train | def get_version():
"""Returns the version of formic.
This method retrieves the version from VERSION.txt, and it should be
exactly the same as the version retrieved from the package manager"""
try:
# Try with the package manager, if present
from pkg_resources import resource_string
... | python | {
"resource": ""
} |
q50157 | reconstitute_path | train | def reconstitute_path(drive, folders):
"""Reverts a tuple from `get_path_components` into a path.
:param drive: A drive (eg 'c:'). Only applicable for NT systems
:param folders: A list of folder names
:return: A path comprising the drive and list of folder names. The path terminate
with a ... | python | {
"resource": ""
} |
q50158 | FNMatcher.match | train | def match(self, string):
"""Returns True if the pattern matches the string"""
if self.casesensitive:
return fnmatch.fnmatch(string, self.pattern)
else:
return fnmatch.fnmatch(string.lower(), self.pattern.lower()) | python | {
"resource": ""
} |
q50159 | ConstantMatcher.match | train | def match(self, string):
"""Returns True if the argument matches the constant."""
if self.casesensitive:
return self.pattern == os.path.normcase(string)
else:
return self.pattern.lower() == os.path.normcase(string).lower() | python | {
"resource": ""
} |
q50160 | Section._match_iter_generic | train | def _match_iter_generic(self, path_elements, start_at):
"""Implementation of match_iter for >1 self.elements"""
length = len(path_elements)
# If bound to start, we stop searching at the first element
if self.bound_start:
end = 1
else:
end = length - self.... | python | {
"resource": ""
} |
q50161 | Section._match_iter_single | train | def _match_iter_single(self, path_elements, start_at):
"""Implementation of match_iter optimized for self.elements of length 1"""
length = len(path_elements)
if length == 0:
return
# If bound to end, we start searching as late as possible
if self.bound_end:
... | python | {
"resource": ""
} |
q50162 | PatternSet._compute_all_files | train | def _compute_all_files(self):
"""Handles lazy evaluation of self.all_files"""
self._all_files = any(pat.all_files() for pat in self.patterns) | python | {
"resource": ""
} |
q50163 | FileSetState._find_parent | train | def _find_parent(self, path_elements):
"""Recurse up the tree of FileSetStates until we find a parent, i.e.
one whose path_elements member is the start of the path_element
argument"""
if not self.path_elements:
# Automatically terminate on root
return self
... | python | {
"resource": ""
} |
q50164 | FileSetState._matching_pattern_sets | train | def _matching_pattern_sets(self):
"""Returns an iterator containing all PatternSets that match this
directory.
This is build by chaining the this-directory specific PatternSet
(self.matched_and_subdir), the local (non-inheriting) PatternSet
(self.matched_no_subdir) with all the ... | python | {
"resource": ""
} |
q50165 | FileSet._receive | train | def _receive(self, root, directory, dirs, files, include, exclude):
"""Internal function processing each yield from os.walk."""
self._received += 1
if not self.symlinks:
where = root + os.path.sep + directory + os.path.sep
files = [
file_name for file_na... | python | {
"resource": ""
} |
q50166 | FileSet.files | train | def files(self):
"""A generator function for iterating over the individual files of
the FileSet.
The generator yields a tuple of ``(rel_dir_name, file_name)``:
1. *rel_dir_name*: The path relative to the starting directory
2. *file_name*: The unqualified file name
"""
... | python | {
"resource": ""
} |
q50167 | order_qc_dir | train | def order_qc_dir(dirnames):
"""Order the QC directory names according to their date.
:param dirnames: the list of directories to merge data from.
:type dirnames: list
:returns: the sorted list of directories
:rtype: list
"""
return sorted(
dirnames, key=lambda dn: time.strptime(
... | python | {
"resource": ""
} |
q50168 | merge_required_files | train | def merge_required_files(dirnames, out_dir):
"""Merges the required files from each of the directories.
:param dirnames: the list of directories to merge data from.
:param out_dir: the name of the output directory.
:type dirnames: list
:type out_dir: str
"""
# The list of files to merge
... | python | {
"resource": ""
} |
q50169 | get_final_numbers | train | def get_final_numbers(filename, out_dir):
"""Copy the final_files file and get the number of markers and samples.
:param filename: the name of the file.
:param out_dir: the output directory.
:type filename: str
:type out_dir: str
:returns: the final number of markers and samples
:rtype: t... | python | {
"resource": ""
} |
q50170 | get_summary_files | train | def get_summary_files(dirnames):
"""Gets the TeX summary files for each test.
:param dirnames: the list of directories to merge data from.
:type dirnames: list
:returns: a list of summary file names.
:rtype: list
"""
# A useful regular expression to get step number in the current directo... | python | {
"resource": ""
} |
q50171 | generate_report | train | def generate_report(out_dir, latex_summaries, nb_markers, nb_samples, options):
"""Generates the report.
:param out_dir: the output directory.
:param latex_summaries: the list of LaTeX summaries.
:param nb_markers: the final number of markers.
:param nb_samples: the final number of samples.
:pa... | python | {
"resource": ""
} |
q50172 | splitFile | train | def splitFile(inputFileName, linePerFile, outPrefix):
"""Split a file.
:param inputFileName: the name of the input file.
:param linePerFile: the number of line per file (after splitting).
:param outPrefix: the prefix of the output files.
:type inputFileName: str
:type linePerFile: int
:typ... | python | {
"resource": ""
} |
q50173 | runGenome | train | def runGenome(bfile, options):
"""Runs the genome command from plink.
:param bfile: the input file prefix.
:param options: the options.
:type bfile: str
:type options: argparse.Namespace
:returns: the name of the ``genome`` file.
Runs Plink with the ``genome`` option. If the user asks fo... | python | {
"resource": ""
} |
q50174 | mergeGenomeLogFiles | train | def mergeGenomeLogFiles(outPrefix, nbSet):
"""Merge genome and log files together.
:param outPrefix: the prefix of the output files.
:param nbSet: The number of set of files to merge together.
:type outPrefix: str
:type nbSet: int
:returns: the name of the output file (the ``genome`` file).
... | python | {
"resource": ""
} |
q50175 | runGenomeSGE | train | def runGenomeSGE(bfile, freqFile, nbJob, outPrefix, options):
"""Runs the genome command from plink, on SGE.
:param bfile: the prefix of the input file.
:param freqFile: the name of the frequency file (from Plink).
:param nbJob: the number of jobs to launch.
:param outPrefix: the prefix of all the ... | python | {
"resource": ""
} |
q50176 | extractSNPs | train | def extractSNPs(snpsToExtract, options):
"""Extract markers using Plink.
:param snpsToExtract: the name of the file containing markers to extract.
:param options: the options
:type snpsToExtract: str
:type options: argparse.Namespace
:returns: the prefix of the output files.
"""
outP... | python | {
"resource": ""
} |
q50177 | selectSNPsAccordingToLD | train | def selectSNPsAccordingToLD(options):
"""Compute LD using Plink.
:param options: the options.
:type options: argparse.Namespace
:returns: the name of the output file (from Plink).
"""
# The plink command
outPrefix = options.out + ".pruning_" + options.indep_pairwise[2]
plinkCommand =... | python | {
"resource": ""
} |
q50178 | Linkfetcher.open | train | def open(self):
"""Open the URL with urllib.request."""
url = self.url
try:
request = urllib.request.Request(url)
handle = urllib.request.build_opener()
except IOError:
return None
return (request, handle) | python | {
"resource": ""
} |
q50179 | Linkfetcher._get_crawled_urls | train | def _get_crawled_urls(self, handle, request):
"""
Main method where the crawler html content is parsed with
beautiful soup and out of the DOM, we get the urls
"""
try:
content = six.text_type(handle.open(request).read(), "utf-8",
er... | python | {
"resource": ""
} |
q50180 | Linkfetcher.linkfetch | train | def linkfetch(self):
""""
Public method to call the internal methods
"""
request, handle = self.open()
self._add_headers(request)
if handle:
self._get_crawled_urls(handle, request) | python | {
"resource": ""
} |
q50181 | handle_lock | train | def handle_lock(handle):
"""
Decorate the handle method with a file lock to ensure there is only ever
one process running at any one time.
"""
def wrapper(self, *args, **options):
def on_interrupt(signum, frame):
# It's necessary to release lockfile
sys.exit()
... | python | {
"resource": ""
} |
q50182 | Highlighter.highlightBlock | train | def highlightBlock(self, text):
"""Takes a block, applies format to the document.
according to what's in it.
"""
# I need to know where in the document we are,
# because our formatting info is global to
# the document
cb = self.currentBlock()
p = cb.posit... | python | {
"resource": ""
} |
q50183 | Image.as_contours | train | def as_contours(self):
"""A dictionary of lists of contours keyed by byte_value"""
contours = dict()
for byte_value in self.__byte_values:
if byte_value == 0:
continue
mask = (self.__array == byte_value) * 255
found_contours = find_contours(mas... | python | {
"resource": ""
} |
q50184 | Image.show | train | def show(self):
"""Display the image"""
with_matplotlib = True
try:
import matplotlib.pyplot as plt
except RuntimeError:
import skimage.io as io
with_matplotlib = False
if with_matplotlib:
equalised_img = self.equalise(... | python | {
"resource": ""
} |
q50185 | ImageSet.segments | train | def segments(self):
"""A dictionary of lists of contours keyed by z-index"""
segments = dict()
for i in xrange(len(self)):
image = self[i]
for z, contour in image.as_segments.iteritems():
for byte_value, contour_set in contour.iteritems():
... | python | {
"resource": ""
} |
q50186 | AmiraMeshDataStream.to_volume | train | def to_volume(self):
"""Return a 3D volume of the data"""
if hasattr(self.header.definitions, "Lattice"):
X, Y, Z = self.header.definitions.Lattice
else:
raise ValueError("Unable to determine data size")
volume = self.decoded_data.reshape(Z, Y, X)
... | python | {
"resource": ""
} |
q50187 | WebfontStore.parse_manifest | train | def parse_manifest(self, fp):
"""
Open manifest JSON file and build icon map
Args:
fp (string or fileobject): Either manifest filepath to open or
manifest File object.
Returns:
dict: Webfont icon map. Contains:
* ``class_name``: Buil... | python | {
"resource": ""
} |
q50188 | WebfontStore.get | train | def get(self, webfont_name, webfont_settings):
"""
Get a manifest file, parse and store it.
Args:
webfont_name (string): Webfont key name. Used to store manifest
and potentially its parser error.
webfont_settings (dict): Webfont settings (an item value fr... | python | {
"resource": ""
} |
q50189 | WebfontStore.fetch | train | def fetch(self, webfonts):
"""
Store every defined webfonts.
Webfont are stored with sort on their name.
Args:
webfonts (dict): Dictionnary of webfont settings from
``settings.ICOMOON_WEBFONTS``.
"""
sorted_keys = sorted(webfonts.keys())
... | python | {
"resource": ""
} |
q50190 | read_csv | train | def read_csv(filepath, sep=',', header='infer', names=None, usecols=None, dtype=None, converters=None,
skiprows=None, nrows=None):
"""Read CSV into DataFrame.
Eager implementation using pandas, i.e. entire file is read at this point. Only common/relevant parameters
available at the moment; for... | python | {
"resource": ""
} |
q50191 | annotate_diamond | train | def annotate_diamond(fasta_path: 'path to fasta input',
diamond_path: 'path to Diamond taxonomic classification output'):
'''
Annotate fasta headers with taxonomy information from Diamond
'''
records = tictax.parse_seqs(fasta_path)
annotated_records = tictax.annotate_diamond(rec... | python | {
"resource": ""
} |
q50192 | filter_taxa | train | def filter_taxa(fasta_path: 'path to fasta input',
taxids: 'comma delimited list of taxon IDs',
unclassified: 'pass sequences unclassified at superkingdom level >(0)' = False,
discard: 'discard specified taxa' = False,
warnings: 'show warnings' = False):
... | python | {
"resource": ""
} |
q50193 | matrix | train | def matrix(fasta_path: 'path to tictax annotated fasta input',
scafstats_path: 'path to BBMap scaftstats file'):
'''
Generate taxonomic count matrix from tictax classified contigs
'''
records = SeqIO.parse(fasta_path, 'fasta')
df = tictax.matrix(records, scafstats_path)
df.to_csv(sys.... | python | {
"resource": ""
} |
q50194 | DictMixin.to_dict | train | def to_dict(self):
"""
Recusively exports object values to a dict
:return: `dict`of values
"""
if not hasattr(self, '_fields'):
return self.__dict__
result = dict()
for field_name, field in self._fields.items():
if isinstance(field, xmlmap... | python | {
"resource": ""
} |
q50195 | LoaderMixin.from_file | train | def from_file(cls, file_path, validate=True):
""" Creates a Python object from a XML file
:param file_path: Path to the XML file
:param validate: XML should be validated against the embedded XSD definition
:type validate: Boolean
:returns: the Python object
"""
r... | python | {
"resource": ""
} |
q50196 | LoaderMixin.from_string | train | def from_string(cls, xml_string, validate=True):
""" Creates a Python object from a XML string
:param xml_string: XML string
:param validate: XML should be validated against the embedded XSD definition
:type validate: Boolean
:returns: the Python object
"""
retur... | python | {
"resource": ""
} |
q50197 | Report.id | train | def id(self):
"""
Computes the signature of the record, a SHA-512 of significant values
:return: SHa-512 Hex string
"""
h = hashlib.new('sha512')
for value in (self.machine.name, self.machine.os, self.user, self.application.name,
self.application.pa... | python | {
"resource": ""
} |
q50198 | scratchpad | train | def scratchpad():
"""Dummy page for styling tests."""
return render_template(
'demo.html',
config=dict(
project_name='Scratchpad',
style=request.args.get('style', 'default'),
),
title='Style Scratchpad',
) | python | {
"resource": ""
} |
q50199 | update_service | train | def update_service(name, service_map):
"""Get an update from the specified service.
Arguments:
name (:py:class:`str`): The name of the service.
service_map (:py:class:`dict`): A mapping of service names to
:py:class:`flash.service.core.Service` instances.
Returns:
:py:class:`dict... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.