_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q49800 | Console.addTextOut | train | def addTextOut(self, text):
"""add black text"""
self._currentColor = self._black
self.addText(text) | python | {
"resource": ""
} |
q49801 | Console.addTextErr | train | def addTextErr(self, text):
"""add red text"""
self._currentColor = self._red
self.addText(text) | python | {
"resource": ""
} |
q49802 | Console.addText | train | def addText(self, text):
"""append text in the chosen color"""
# move to the end of the doc
self.moveCursor(QtGui.QTextCursor.End)
# insert the text
self.setTextColor(self._currentColor)
self.textCursor().insertText(text) | python | {
"resource": ""
} |
q49803 | createFinalTPEDandTFAM | train | def createFinalTPEDandTFAM(tped, toReadPrefix, prefix, snpToRemove):
"""Creates the final TPED and TFAM.
:param tped: a representation of the ``tped`` of duplicated markers.
:param toReadPrefix: the prefix of the unique files.
:param prefix: the prefix of the output files.
:param snpToRemove: the m... | python | {
"resource": ""
} |
q49804 | chooseBestSnps | train | def chooseBestSnps(tped, snps, trueCompletion, trueConcordance, prefix):
"""Choose the best duplicates according to the completion and concordance.
:param tped: a representation of the ``tped`` of duplicated markers.
:param snps: the position of the duplicated markers in the ``tped``.
:param trueComple... | python | {
"resource": ""
} |
q49805 | computeFrequency | train | def computeFrequency(prefix, outPrefix):
"""Computes the frequency of the SNPs using Plink.
:param prefix: the prefix of the input files.
:param outPrefix: the prefix of the output files.
:type prefix: str
:type outPrefix: str
:returns: a :py:class:`dict` containing the frequency of each mark... | python | {
"resource": ""
} |
q49806 | printDuplicatedTPEDandTFAM | train | def printDuplicatedTPEDandTFAM(tped, tfamFileName, outPrefix):
"""Print the duplicated SNPs TPED and TFAM.
:param tped: a representation of the ``tped`` of duplicated markers.
:param tfamFileName: the name of the original ``tfam`` file.
:param outPrefix: the output prefix.
:type tped: numpy.array
... | python | {
"resource": ""
} |
q49807 | getIndexOfHeteroMen | train | def getIndexOfHeteroMen(genotypes, menIndex):
"""Get the indexes of heterozygous men.
:param genotypes: the genotypes of everybody.
:param menIndex: the indexes of the men (for the genotypes).
:type genotypes: numpy.array
:type menIndex: numpy.array
:returns: a :py:class:`numpy.array` contain... | python | {
"resource": ""
} |
q49808 | flipGenotype | train | def flipGenotype(genotype):
"""Flips a genotype.
:param genotype: the genotype to flip.
:type genotype: set
:returns: the new flipped genotype (as a :py:class:`set`)
.. testsetup::
from pyGenClean.DupSNPs.duplicated_snps import flipGenotype
.. doctest::
>>> flipGenotype({"... | python | {
"resource": ""
} |
q49809 | findUniques | train | def findUniques(mapF):
"""Finds the unique markers in a MAP.
:param mapF: representation of a ``map`` file.
:type mapF: list
:returns: a :py:class:`dict` containing unique markers (according to their
genomic localisation).
"""
uSNPs = {}
dSNPs = defaultdict(list)
for i,... | python | {
"resource": ""
} |
q49810 | readTFAM | train | def readTFAM(fileName):
"""Reads the TFAM file.
:param fileName: the name of the ``tfam`` file.
:type fileName: str
:returns: a representation the ``tfam`` file (:py:class:`numpy.array`).
"""
# Saving the TFAM file
tfam = None
with open(fileName, 'r') as inputFile:
tfam = [
... | python | {
"resource": ""
} |
q49811 | readMAP | train | def readMAP(fileName, prefix):
"""Reads the MAP file.
:param fileName: the name of the ``map`` file.
:type fileName: str
:returns: a list of tuples, representing the ``map`` file.
While reading the ``map`` file, it saves a file
(``prefix.duplicated_marker_names``) containing the name of the ... | python | {
"resource": ""
} |
q49812 | MenuBar.findMenu | train | def findMenu(self, title):
"""
find a menu with a given title
@type title: string
@param title: English title of the menu
@rtype: QMenu
@return: None if no menu was found, else the menu with title
"""
# See also http://www.riverbankcomputing.c... | python | {
"resource": ""
} |
q49813 | MenuBar.insertMenuBefore | train | def insertMenuBefore(self, before_menu, new_menu):
"""
Insert a menu after another menu in the menubar
@type: before_menu QMenu instance or title string of menu
@param before_menu: menu which should be after the newly inserted menu
@rtype: QAction instance
@return: actio... | python | {
"resource": ""
} |
q49814 | WidgetParameterItem.updateDisplayLabel | train | def updateDisplayLabel(self, value=None):
"""Update the display label to reflect the value of the parameter."""
if value is None:
value = self.param.value()
opts = self.param.opts
if isinstance(self.widget, QtWidgets.QAbstractSpinBox):
text = asUnicode(self.widget... | python | {
"resource": ""
} |
q49815 | WidgetParameterItem.limitsChanged | train | def limitsChanged(self, param, limits):
"""Called when the parameter's limits have changed"""
ParameterItem.limitsChanged(self, param, limits)
t = self.param.opts['type']
if t == 'int' or t == 'float':
self.widget.setOpts(bounds=limits)
else:
return | python | {
"resource": ""
} |
q49816 | WidgetParameterItem.treeWidgetChanged | train | def treeWidgetChanged(self):
"""Called when this item is added or removed from a tree."""
ParameterItem.treeWidgetChanged(self)
# add all widgets for this item into the tree
if self.widget is not None:
tree = self.treeWidget()
if tree is None:
ret... | python | {
"resource": ""
} |
q49817 | WidgetParameterItem.optsChanged | train | def optsChanged(self, param, opts):
"""Called when any options are changed that are not
name, value, default, or limits"""
# print "opts changed:", opts
ParameterItem.optsChanged(self, param, opts)
w = self.widget
if 'readonly' in opts:
self.updateDefaultBtn()... | python | {
"resource": ""
} |
q49818 | GroupParameterItem.addChanged | train | def addChanged(self):
"""Called when "add new" combo is changed
The parameter MUST have an 'addNew' method defined.
"""
if self.addWidget.currentIndex() == 0:
return
typ = asUnicode(self.addWidget.currentText())
self.param.addNew(typ)
self.addWidget.se... | python | {
"resource": ""
} |
q49819 | create_parser | train | def create_parser():
"""Creat a commandline parser for epubcheck
:return Argumentparser:
"""
parser = ArgumentParser(
prog='epubcheck',
description="EpubCheck v%s - Validate your ebooks" % __version__
)
# Arguments
parser.add_argument(
'path',
nargs='?',
... | python | {
"resource": ""
} |
q49820 | main | train | def main(argv=None):
"""Command line app main function.
:param list | None argv: Overrides command options (for libuse or testing)
"""
parser = create_parser()
args = parser.parse_args() if argv is None else parser.parse_args(argv)
if not os.path.exists(args.path):
sys.exit(0)
al... | python | {
"resource": ""
} |
q49821 | A_cylinder | train | def A_cylinder(D, L):
r'''Returns the surface area of a cylinder.
.. math::
A = \pi D L + 2\cdot \frac{\pi D^2}{4}
Parameters
----------
D : float
Diameter of the cylinder, [m]
L : float
Length of the cylinder, [m]
Returns
-------
A : float
Surface ... | python | {
"resource": ""
} |
q49822 | V_hollow_cylinder | train | def V_hollow_cylinder(Di, Do, L):
r'''Returns the volume of a hollow cylinder.
.. math::
V = \frac{\pi D_o^2}{4}L - L\frac{\pi D_i^2}{4}
Parameters
----------
Di : float
Diameter of the hollow in the cylinder, [m]
Do : float
Diameter of the exterior of the cylinder, [m]... | python | {
"resource": ""
} |
q49823 | V_multiple_hole_cylinder | train | def V_multiple_hole_cylinder(Do, L, holes):
r'''Returns the solid volume of a cylinder with multiple cylindrical holes.
Calculation will naively return a negative value or other impossible
result if the number of cylinders added is physically impossible.
.. math::
V = \frac{\pi D_o^2}{4}L - L\f... | python | {
"resource": ""
} |
q49824 | handler404 | train | def handler404(request, template_name='404.html'):
"""
404 error handler.
Templates: `404.html`
Context:
MEDIA_URL
Path of static media (e.g. "media.example.org")
STATIC_URL
"""
t = loader.get_template(template_name) # You need to create a 404... | python | {
"resource": ""
} |
q49825 | RandomExcuseGenerator.pmxbot_excuse | train | def pmxbot_excuse(self, rest):
"Provide a convenient excuse"
args = rest.split(' ')[:2]
parser = argparse.ArgumentParser()
parser.add_argument('word', nargs="?")
parser.add_argument('index', type=int, nargs="?")
args = parser.parse_args(args)
if not args.word:
... | python | {
"resource": ""
} |
q49826 | load_with_scipy | train | def load_with_scipy(file, data_name):
import scipy.io
"""
Loads data from a netcdf file.
Parameters
----------
file : string or file-like
The name of the netcdf file to open.
data_name : string
The name of the data to extract from the netcdf file.
Returns
-------
... | python | {
"resource": ""
} |
q49827 | _connect_database | train | def _connect_database(config):
"""Create simple connection with Mongodb
config comes with settings from .ini file.
"""
settings = config.registry.settings
mongo_uri = "mongodb://localhost:27017"
mongodb_name = "test"
if settings.get("mongo_url"):
mongo_uri = settings["mongo_url"]
... | python | {
"resource": ""
} |
q49828 | get_content | train | def get_content(identifier, default=None):
'''
Returns the DynamicContent instance for the given identifier.
If no object is found, a new one will be created.
:param identifier: String representing the unique identifier of a
``DynamicContent`` object.
:param default: String that should be us... | python | {
"resource": ""
} |
q49829 | rescale_taps | train | def rescale_taps(taps):
"""
Rescale taps in that way that their sum equals 1
"""
taps = np.array(taps)
cs = sum(taps)
# fixme: not sure here, abs seems right as it avoids overflows in core,
# then again it reduces the fir gain
# cs = sum(abs(taps))
for (i, x) in enumerate(taps):
... | python | {
"resource": ""
} |
q49830 | to_json | train | def to_json(value):
"""
Converts a value to a jsonable type.
"""
if type(value) in JSON_TYPES:
return value
elif hasattr(value, "to_json"):
return value.to_json()
elif isinstance(value, list) or isinstance(value, set) or \
isinstance(value, deque) or isinstance(value,... | python | {
"resource": ""
} |
q49831 | FileLock.lock_pid | train | def lock_pid(self):
"""
Get the pid of the lock.
"""
if os.path.exists(self.lock_filename):
return int(open(self.lock_filename).read())
else:
return None | python | {
"resource": ""
} |
q49832 | FileLock.is_locked_by_me | train | def is_locked_by_me(self):
"""
See if the lock exists and is belongs to this process.
"""
## get pid of lock
lock_pid = self.lock_pid()
## not locked
if lock_pid is None:
logger.debug('Lock {} is not aquired.'.format(self.lock_filename))
... | python | {
"resource": ""
} |
q49833 | FileLock.acquire_try_once | train | def acquire_try_once(self):
"""
Try to aquire the lock once.
"""
if self.is_locked_by_me():
return True
else:
try:
self.fd = os.open(self.lock_filename, os.O_CREAT | os.O_RDWR | os.O_EXCL)
except FileExistsError:
... | python | {
"resource": ""
} |
q49834 | FileLock.acquire | train | def acquire(self):
"""
Try to aquire the lock.
"""
if self.timeout is not None:
sleep_intervals = int(self.timeout / self.sleep_time)
else:
sleep_intervals = float('inf')
while not self.acquire_try_once() and sleep_intervals > 0:
... | python | {
"resource": ""
} |
q49835 | create_scree_plot | train | def create_scree_plot(in_filename, out_filename, plot_title):
"""Creates a scree plot using smartpca results.
:param in_filename: the name of the input file.
:param out_filename: the name of the output file.
:param plot_title: the title of the scree plot.
:type in_filename: str
:type out_filen... | python | {
"resource": ""
} |
q49836 | compute_eigenvalues | train | def compute_eigenvalues(in_prefix, out_prefix):
"""Computes the Eigenvalues using smartpca from Eigensoft.
:param in_prefix: the prefix of the input files.
:param out_prefix: the prefix of the output files.
:type in_prefix: str
:type out_prefix: str
Creates a "parameter file" used by smartpca... | python | {
"resource": ""
} |
q49837 | find_the_outliers | train | def find_the_outliers(mds_file_name, population_file_name, ref_pop_name,
multiplier, out_prefix):
"""Finds the outliers of a given population.
:param mds_file_name: the name of the ``mds`` file.
:param population_file_name: the name of the population file.
:param ref_pop_name: the... | python | {
"resource": ""
} |
q49838 | createPopulationFile | train | def createPopulationFile(inputFiles, labels, outputFileName):
"""Creates a population file.
:param inputFiles: the list of input files.
:param labels: the list of labels (corresponding to the input files).
:param outputFileName: the name of the output file.
:type inputFiles: list
:type labels:... | python | {
"resource": ""
} |
q49839 | plotMDS | train | def plotMDS(inputFileName, outPrefix, populationFileName, options):
"""Plots the MDS value.
:param inputFileName: the name of the ``mds`` file.
:param outPrefix: the prefix of the output files.
:param populationFileName: the name of the population file.
:param options: the options
:type inputF... | python | {
"resource": ""
} |
q49840 | createMDSFile | train | def createMDSFile(nb_components, inPrefix, outPrefix, genomeFileName):
"""Creates a MDS file using Plink.
:param nb_components: the number of component.
:param inPrefix: the prefix of the input file.
:param outPrefix: the prefix of the output file.
:param genomeFileName: the name of the ``genome`` ... | python | {
"resource": ""
} |
q49841 | runRelatedness | train | def runRelatedness(inputPrefix, outPrefix, options):
"""Run the relatedness step of the data clean up.
:param inputPrefix: the prefix of the input file.
:param outPrefix: the prefix of the output file.
:param options: the options
:type inputPrefix: str
:type outPrefix: str
:type options: a... | python | {
"resource": ""
} |
q49842 | allFileExists | train | def allFileExists(fileList):
"""Check that all file exists.
:param fileList: the list of file to check.
:type fileList: list
Check if all the files in ``fileList`` exists.
"""
allExists = True
for fileName in fileList:
allExists = allExists and os.path.isfile(fileName)
return... | python | {
"resource": ""
} |
q49843 | excludeSNPs | train | def excludeSNPs(inPrefix, outPrefix, exclusionFileName):
"""Exclude some SNPs using Plink.
:param inPrefix: the prefix of the input file.
:param outPrefix: the prefix of the output file.
:param exclusionFileName: the name of the file containing the markers to be
excluded.
... | python | {
"resource": ""
} |
q49844 | findFlippedSNPs | train | def findFlippedSNPs(frqFile1, frqFile2, outPrefix):
"""Find flipped SNPs and flip them in the data.
:param frqFile1: the name of the first frequency file.
:param frqFile2: the name of the second frequency file.
:param outPrefix: the prefix of the output files.
:type frqFile1: str
:type frqFile... | python | {
"resource": ""
} |
q49845 | combinePlinkBinaryFiles | train | def combinePlinkBinaryFiles(prefixes, outPrefix):
"""Combine Plink binary files.
:param prefixes: a list of the prefix of the files that need to be
combined.
:param outPrefix: the prefix of the output file (the combined file).
:type prefixes: list
:type outPrefix: str
It ... | python | {
"resource": ""
} |
q49846 | extract_favicon | train | def extract_favicon(bs4):
"""Extracting favicon url from BeautifulSoup object
:param bs4: `BeautifulSoup`
:return: `list` List of favicon urls
"""
favicon = []
selectors = [
'link[rel="icon"]',
'link[rel="Icon"]',
'link[rel="ICON"]',
'link[rel^="shortcut"]',
... | python | {
"resource": ""
} |
q49847 | extract_metas | train | def extract_metas(bs4):
"""Extracting meta tags from BeautifulSoup object
:param bs4: `BeautifulSoup`
:return: `list` List of meta tags
"""
meta_tags = []
metas = bs4.select('meta')
for meta in metas:
meta_content = {}
meta_attrs = [
'charset',
'... | python | {
"resource": ""
} |
q49848 | extract_links | train | def extract_links(bs4):
"""Extracting links from BeautifulSoup object
:param bs4: `BeautifulSoup`
:return: `list` List of links
"""
unique_links = list(set([anchor['href'] for anchor in bs4.select('a[href]') if anchor.has_attr('href')]))
# remove irrelevant link
unique_links = [link for l... | python | {
"resource": ""
} |
q49849 | extract_original_links | train | def extract_original_links(base_url, bs4):
"""Extracting links that contains specific url from BeautifulSoup object
:param base_url: `str` specific url that matched with the links
:param bs4: `BeautifulSoup`
:return: `list` List of links
"""
valid_url = convert_invalid_url(base_url)
url = ... | python | {
"resource": ""
} |
q49850 | extract_css_links | train | def extract_css_links(bs4):
"""Extracting css links from BeautifulSoup object
:param bs4: `BeautifulSoup`
:return: `list` List of links
"""
links = extract_links(bs4)
real_css = [anchor for anchor in links if anchor.endswith(('.css', '.CSS'))]
css_link_tags = [anchor['href'] for anchor i... | python | {
"resource": ""
} |
q49851 | extract_js_links | train | def extract_js_links(bs4):
"""Extracting js links from BeautifulSoup object
:param bs4: `BeautifulSoup`
:return: `list` List of links
"""
links = extract_links(bs4)
real_js = [anchor for anchor in links if anchor.endswith(('.js', '.JS'))]
js_tags = [anchor['src'] for anchor in bs4.select... | python | {
"resource": ""
} |
q49852 | extract_images | train | def extract_images(bs4, lazy_image_attribute=None):
"""If lazy attribute is supplied, find image url on that attribute
:param bs4:
:param lazy_image_attribute:
:return:
"""
# get images form 'img' tags
if lazy_image_attribute:
images = [image[lazy_image_attribute] for image in bs4... | python | {
"resource": ""
} |
q49853 | extract_canonical | train | def extract_canonical(bs4):
"""Extracting canonical url
:param bs4:
:return:
"""
link_rel = bs4.select('link[rel="canonical"]')
if link_rel.__len__() > 0:
if link_rel[0].has_attr('href'):
return link_rel[0]['href']
return None | python | {
"resource": ""
} |
q49854 | Page.html | train | def html(self, selector):
"""Return html result that executed by given css selector
:param selector: `str` css selector
:return: `list` or `None`
"""
result = self.__bs4.select(selector)
return [str(r) for r in result] \
if result.__len__() > 1 else \
... | python | {
"resource": ""
} |
q49855 | Page.text | train | def text(self, selector):
"""Return text result that executed by given css selector
:param selector: `str` css selector
:return: `list` or `None`
"""
result = self.__bs4.select(selector)
return [r.get_text() for r in result] \
if result.__len__() > 1 else \... | python | {
"resource": ""
} |
q49856 | VariantStat.conversion_rate | train | def conversion_rate(self):
"""
The percentage of participants that have converted for this variant.
Returns a > 0 float representing a percentage rate.
"""
participants = self.participant_count
if participants == 0:
return 0.0
return self.experiment.c... | python | {
"resource": ""
} |
q49857 | VariantStat.z_score | train | def z_score(self):
"""
Calculate the Z-Score between this alternative and the project control.
Statistical formulas based on:
http://20bits.com/article/statistical-analysis-and-ab-testing
"""
control = VariantStat(self.experiment.control, self.experiment)
altern... | python | {
"resource": ""
} |
q49858 | VariantStat.confidence_level | train | def confidence_level(self):
"""
Based on the variant's Z-Score, returns a human-readable string that
describes the confidence with which we can say the results are
statistically significant.
"""
z = self.z_score
if isinstance(z, string_types):
return z... | python | {
"resource": ""
} |
q49859 | Index.tail | train | def tail(self, n=5):
"""Return Index with the last n values.
Parameters
----------
n : int
Number of values.
Returns
-------
Series
Index containing the last n values.
Examples
--------
>>> ind = bl.Index(np.arang... | python | {
"resource": ""
} |
q49860 | Index.fillna | train | def fillna(self, value):
"""Returns Index with missing values replaced with value.
Parameters
----------
value : {int, float, bytes, bool}
Scalar value to replace missing values with.
Returns
-------
Index
With missing values replaced.
... | python | {
"resource": ""
} |
q49861 | Index.from_pandas | train | def from_pandas(cls, index):
"""Create baloo Index from pandas Index.
Parameters
----------
index : pandas.base.Index
Returns
-------
Index
"""
from pandas import Index as PandasIndex
check_type(index, PandasIndex)
return Index(... | python | {
"resource": ""
} |
q49862 | Index.to_pandas | train | def to_pandas(self):
"""Convert to pandas Index.
Returns
-------
pandas.base.Index
"""
if not self.is_raw():
raise ValueError('Cannot convert to pandas Index if not evaluated.')
from pandas import Index as PandasIndex
return PandasIndex(sel... | python | {
"resource": ""
} |
q49863 | get_plink_version | train | def get_plink_version():
"""Gets the Plink version from the binary.
:returns: the version of the Plink software
:rtype: str
This function uses :py:class:`subprocess.Popen` to gather the version of
the Plink binary. Since executing the software to gather the version
creates an output file, it i... | python | {
"resource": ""
} |
q49864 | _normalise_weights | train | def _normalise_weights(logZ, weights, ntrim=None):
""" Correctly normalise the weights for trimming
This takes a list of log-evidences, and re-normalises the weights so that
the largest weight across all samples is 1, and the total weight in each
set of samples is proportional to the evidence.
Par... | python | {
"resource": ""
} |
q49865 | _equally_weight_samples | train | def _equally_weight_samples(samples, weights):
""" Convert samples to be equally weighted.
Samples are trimmed by discarding samples in accordance with a probability
determined by the corresponding weight.
This function has assumed you have normalised the weights properly.
If in doubt, convert wei... | python | {
"resource": ""
} |
q49866 | notification_push | train | def notification_push(dev_type, to, message=None, **kwargs):
"""
Send data from your server to your users' devices.
"""
key = {
'ANDROID': settings.GCM_ANDROID_APIKEY,
'IOS': settings.GCM_IOS_APIKEY
}
if not key[dev_type]:
raise ImproperlyConfigured(
"You hav... | python | {
"resource": ""
} |
q49867 | get_device_model | train | def get_device_model():
"""
Returns the Device model that is active in this project.
"""
try:
return apps.get_model(settings.GCM_DEVICE_MODEL)
except ValueError:
raise ImproperlyConfigured("GCM_DEVICE_MODEL must be of the form 'app_label.model_name'")
except LookupError:
... | python | {
"resource": ""
} |
q49868 | run_compare_gold_standard | train | def run_compare_gold_standard(in_prefix, in_type, out_prefix, base_dir,
options):
"""Compares with a gold standard data set (compare_gold_standard.
:param in_prefix: the prefix of the input files.
:param in_type: the type of the input files.
:param out_prefix: the output p... | python | {
"resource": ""
} |
q49869 | run_command | train | def run_command(command):
"""Run a command using subprocesses.
:param command: the command to run.
:type command: list
Tries to run a command. If it fails, raise a :py:class:`ProgramError`.
.. warning::
The variable ``command`` should be a list of strings (no other type).
"""
ou... | python | {
"resource": ""
} |
q49870 | count_markers_samples | train | def count_markers_samples(prefix, file_type):
"""Counts the number of markers and samples in plink file.
:param prefix: the prefix of the files.
:param file_type: the file type.
:type prefix: str
:type file_type: str
:returns: the number of markers and samples (in a tuple).
"""
# The... | python | {
"resource": ""
} |
q49871 | check_input_files | train | def check_input_files(prefix, the_type, required_type):
"""Check that the file is of a certain file type.
:param prefix: the prefix of the input files.
:param the_type: the type of the input files (bfile, tfile or file).
:param required_type: the required type of the input files (bfile, tfile or
... | python | {
"resource": ""
} |
q49872 | all_files_exist | train | def all_files_exist(file_list):
"""Check if all files exist.
:param file_list: the names of files to check.
:type file_list: list
:returns: ``True`` if all files exist, ``False`` otherwise.
"""
all_exist = True
for filename in file_list:
all_exist = all_exist and os.path.isfile(f... | python | {
"resource": ""
} |
q49873 | read_config_file | train | def read_config_file(filename):
"""Reads the configuration file.
:param filename: the name of the file containing the configuration.
:type filename: str
:returns: A tuple where the first element is a list of sections, and the
second element is a map containing the configuration (options... | python | {
"resource": ""
} |
q49874 | Authenticator.instance | train | def instance(cls, public_keys_dir):
'''Please avoid create multi instance'''
if public_keys_dir in cls._authenticators:
return cls._authenticators[public_keys_dir]
new_instance = cls(public_keys_dir)
cls._authenticators[public_keys_dir] = new_instance
return new_insta... | python | {
"resource": ""
} |
q49875 | SimpleRouter.get_urls | train | def get_urls(self):
"""
Returns a list of urls including all NestedSimpleRouter urls
"""
ret = super(SimpleRouter, self).get_urls()
for router in self.nested_routers:
ret.extend(router.get_urls())
return ret | python | {
"resource": ""
} |
q49876 | get_weld_obj_id | train | def get_weld_obj_id(weld_obj, data):
"""Helper method to update WeldObject with some data.
Parameters
----------
weld_obj : WeldObject
WeldObject to update.
data : numpy.ndarray or WeldObject or str
Data for which to get an id. If str, it is a placeholder or 'str' literal.
Retu... | python | {
"resource": ""
} |
q49877 | create_weld_object | train | def create_weld_object(data):
"""Helper method to create a WeldObject and update with data.
Parameters
----------
data : numpy.ndarray or WeldObject or str
Data to include in newly created object. If str, it is a placeholder or 'str' literal.
Returns
-------
(str, WeldObject)
... | python | {
"resource": ""
} |
q49878 | create_placeholder_weld_object | train | def create_placeholder_weld_object(data):
"""Helper method that creates a WeldObject that evaluates to itself.
Parameters
----------
data : numpy.ndarray or WeldObject or str
Data to wrap around. If str, it is a placeholder or 'str' literal.
Returns
-------
WeldObject
WeldO... | python | {
"resource": ""
} |
q49879 | _extract_placeholder_weld_objects_at_index | train | def _extract_placeholder_weld_objects_at_index(dependency_name, length, readable_text, index):
"""Helper method that creates a WeldObject for each component of dependency.
Parameters
----------
dependency_name : str
The name of the dependency evaluating to a tuple.
length : int
Numb... | python | {
"resource": ""
} |
q49880 | to_weld_literal | train | def to_weld_literal(scalar, weld_type):
"""Return scalar formatted for Weld.
Parameters
----------
scalar : {int, float, str, bool}
Scalar data to convert to weld literal.
weld_type : WeldType
Desired Weld type.
Returns
-------
str
String of the scalar to use in... | python | {
"resource": ""
} |
q49881 | weld_cast_scalar | train | def weld_cast_scalar(scalar, to_weld_type):
"""Returns the scalar casted to the request Weld type.
Parameters
----------
scalar : {int, float, WeldObject}
Input array.
to_weld_type : WeldType
Type of each element in the input array.
Returns
-------
WeldObject
Re... | python | {
"resource": ""
} |
q49882 | weld_cast_array | train | def weld_cast_array(array, weld_type, to_weld_type):
"""Cast array to a different type.
Parameters
----------
array : numpy.ndarray or WeldObject
Input data.
weld_type : WeldType
Type of each element in the input array.
to_weld_type : WeldType
Desired type.
Returns
... | python | {
"resource": ""
} |
q49883 | weld_arrays_to_vec_of_struct | train | def weld_arrays_to_vec_of_struct(arrays, weld_types):
"""Create a vector of structs from multiple vectors.
Parameters
----------
arrays : list of (numpy.ndarray or WeldObject)
Arrays to put in a struct.
weld_types : list of WeldType
The Weld types of the arrays in the same order.
... | python | {
"resource": ""
} |
q49884 | weld_vec_of_struct_to_struct_of_vec | train | def weld_vec_of_struct_to_struct_of_vec(vec_of_structs, weld_types):
"""Create a struct of vectors.
Parameters
----------
vec_of_structs : WeldObject
Encoding a vector of structs.
weld_types : list of WeldType
The Weld types of the arrays in the same order.
Returns
-------
... | python | {
"resource": ""
} |
q49885 | weld_select_from_struct | train | def weld_select_from_struct(struct_of_vec, index_to_select):
"""Select a single vector from the struct of vectors.
Parameters
----------
struct_of_vec : WeldObject
Encoding a struct of vectors.
index_to_select : int
Which vec to select from the struct.
Returns
-------
W... | python | {
"resource": ""
} |
q49886 | weld_data_to_dict | train | def weld_data_to_dict(keys, keys_weld_types, values, values_weld_types):
"""Adds the key-value pairs in a dictionary. Overlapping keys are max-ed.
Note this cannot be evaluated!
Parameters
----------
keys : list of (numpy.ndarray or WeldObject)
keys_weld_types : list of WeldType
values : n... | python | {
"resource": ""
} |
q49887 | Experiment.set | train | def set( self, params ):
"""Set the parameters for the experiment, returning the
now-configured experiment. Be sure to call this base method when overriding.
:param params: the parameters
:returns: The experiment"""
if self._parameters is not None:
self.deconfigure(... | python | {
"resource": ""
} |
q49888 | Experiment.results | train | def results( self ):
"""Return a complete results dict. Only really makes sense for
recently-executed experimental runs.
:returns: the results dict"""
return self.report(self.parameters(),
self.metadata(),
self.experimentalResults()) | python | {
"resource": ""
} |
q49889 | SetProperties | train | def SetProperties(has_props_cls, input_dict, include_immutable=True):
"""A helper method to set an ``HasProperties`` object's properties from a dictionary"""
props = has_props_cls()
if not isinstance(input_dict, (dict, collections.OrderedDict)):
raise RuntimeError('input_dict invalid: ', input_dict)... | python | {
"resource": ""
} |
q49890 | RasterSetReader.ReadTif | train | def ReadTif(tifFile):
"""Reads a tif file to a 2D NumPy array"""
img = Image.open(tifFile)
img = np.array(img)
return img | python | {
"resource": ""
} |
q49891 | RasterSetReader.GenerateBand | train | def GenerateBand(self, band, meta_only=False, cast=False):
"""Genreate a Band object given band metadata
Args:
band (dict): dictionary containing metadata for a given band
Return:
Band : the loaded Band onject"""
# Read the band data and add it to dictionary
... | python | {
"resource": ""
} |
q49892 | RasterSetReader.Read | train | def Read(self, meta_only=False, allowed=None, cast=False):
"""Read the ESPA XML metadata file"""
if allowed is not None and not isinstance(allowed, (list, tuple)):
raise RuntimeError('`allowed` must be a list of str names.')
meta = xmltodict.parse(
open(self.filename... | python | {
"resource": ""
} |
q49893 | java_version | train | def java_version():
"""Call java and return version information.
:return unicode: Java version string
"""
result = subprocess.check_output(
[c.JAVA, '-version'], stderr=subprocess.STDOUT
)
first_line = result.splitlines()[0]
return first_line.decode() | python | {
"resource": ""
} |
q49894 | epubcheck_help | train | def epubcheck_help():
"""Return epubcheck.jar commandline help text.
:return unicode: helptext from epubcheck.jar
"""
# tc = locale.getdefaultlocale()[1]
with open(os.devnull, "w") as devnull:
p = subprocess.Popen(
[c.JAVA, '-Duser.language=en', '-jar', c.EPUBCHECK, '-h'],
... | python | {
"resource": ""
} |
q49895 | generate_sample_json | train | def generate_sample_json():
"""Generate sample json data for testing"""
check = EpubCheck(samples.EPUB3_VALID)
with open(samples.RESULT_VALID, 'wb') as jsonfile:
jsonfile.write(check._stdout)
check = EpubCheck(samples.EPUB3_INVALID)
with open(samples.RESULT_INVALID, 'wb') as jsonfile:
... | python | {
"resource": ""
} |
q49896 | CleaverBackend.participate | train | def participate(self, identity, experiment_name, variant):
"""
Set the variant for a specific user and mark a participation for the
experiment.
Participation will *only* be marked for visitors who have been verified
as humans (to avoid skewing reports with requests from bots and... | python | {
"resource": ""
} |
q49897 | to_weld_vec | train | def to_weld_vec(weld_type, ndim):
"""Convert multi-dimensional data to WeldVec types.
Parameters
----------
weld_type : WeldType
WeldType of data.
ndim : int
Number of dimensions.
Returns
-------
WeldVec
WeldVec of 1 or more dimensions.
"""
for i in ran... | python | {
"resource": ""
} |
q49898 | to_shared_lib | train | def to_shared_lib(name):
"""Return library name depending on platform.
Parameters
----------
name : str
Name of library.
Returns
-------
str
Name of library with extension.
"""
if sys.platform.startswith('linux'):
return name + '.so'
elif sys.platform.s... | python | {
"resource": ""
} |
q49899 | check_type | train | def check_type(value: typing.Any, hint: typing.Optional[type]) -> bool:
"""Check given ``value``'s type.
:param value: given argument
:param hint: expected type of given ``value``.
as like :mod:`typing` interprets, :const:`None` is interpreted
as :class:`types.NoneType`
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.