_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q57400
QmedAnalysis._vec_b
train
def _vec_b(self, donor_catchments): """ Return vector ``b`` of model error covariances to estimate weights Methodology source: Kjeldsen, Jones and Morris, 2009, eqs 3 and 10 :param donor_catchments: Catchments to use as donors :type donor_catchments: list of :class:`Catchment` ...
python
{ "resource": "" }
q57401
QmedAnalysis._beta
train
def _beta(catchment): """ Return beta, the GLO scale parameter divided by loc parameter estimated using simple regression model Methodology source: Kjeldsen & Jones, 2009, table 2 :param catchment: Catchment to estimate beta for :type catchment: :class:`Catchment` :retu...
python
{ "resource": "" }
q57402
QmedAnalysis._matrix_sigma_eta
train
def _matrix_sigma_eta(self, donor_catchments): """ Return model error coveriance matrix Sigma eta Methodology source: Kjelsen, Jones & Morris 2014, eqs 2 and 3 :param donor_catchments: Catchments to use as donors :type donor_catchments: list of :class:`Catchment` :retur...
python
{ "resource": "" }
q57403
QmedAnalysis._matrix_sigma_eps
train
def _matrix_sigma_eps(self, donor_catchments): """ Return sampling error coveriance matrix Sigma eta Methodology source: Kjeldsen & Jones 2009, eq 9 :param donor_catchments: Catchments to use as donors :type donor_catchments: list of :class:`Catchment` :return: 2-Dimens...
python
{ "resource": "" }
q57404
QmedAnalysis._vec_alpha
train
def _vec_alpha(self, donor_catchments): """ Return vector alpha which is the weights for donor model errors Methodology source: Kjeldsen, Jones & Morris 2014, eq 10 :param donor_catchments: Catchments to use as donors :type donor_catchments: list of :class:`Catchment` :...
python
{ "resource": "" }
q57405
QmedAnalysis.find_donor_catchments
train
def find_donor_catchments(self, limit=6, dist_limit=500): """ Return a suitable donor catchment to improve a QMED estimate based on catchment descriptors alone. :param limit: maximum number of catchments to return. Default: 6. Set to `None` to return all available catchmen...
python
{ "resource": "" }
q57406
GrowthCurveAnalysis._var_and_skew
train
def _var_and_skew(self, catchments, as_rural=False): """ Calculate L-CV and L-SKEW from a single catchment or a pooled group of catchments. Methodology source: Science Report SC050050, para. 6.4.1-6.4.2 """ if not hasattr(catchments, '__getitem__'): # In case of a single catchm...
python
{ "resource": "" }
q57407
GrowthCurveAnalysis._l_cv_and_skew
train
def _l_cv_and_skew(self, catchment): """ Calculate L-CV and L-SKEW for a gauged catchment. Uses `lmoments3` library. Methodology source: Science Report SC050050, para. 6.7.5 """ z = self._dimensionless_flows(catchment) l1, l2, t3 = lm.lmom_ratios(z, nmom=3) retur...
python
{ "resource": "" }
q57408
GrowthCurveAnalysis._l_cv_weight
train
def _l_cv_weight(self, donor_catchment): """ Return L-CV weighting for a donor catchment. Methodology source: Science Report SC050050, eqn. 6.18 and 6.22a """ try: dist = donor_catchment.similarity_dist except AttributeError: dist = self._similari...
python
{ "resource": "" }
q57409
GrowthCurveAnalysis._l_cv_weight_factor
train
def _l_cv_weight_factor(self): """ Return multiplier for L-CV weightings in case of enhanced single site analysis. Methodology source: Science Report SC050050, eqn. 6.15a and 6.15b """ b = 0.0047 * sqrt(0) + 0.0023 / 2 c = 0.02609 / (self.catchment.record_length - 1) ...
python
{ "resource": "" }
q57410
GrowthCurveAnalysis._l_skew_weight
train
def _l_skew_weight(self, donor_catchment): """ Return L-SKEW weighting for donor catchment. Methodology source: Science Report SC050050, eqn. 6.19 and 6.22b """ try: dist = donor_catchment.similarity_dist except AttributeError: dist = self._simila...
python
{ "resource": "" }
q57411
GrowthCurveAnalysis._growth_curve_single_site
train
def _growth_curve_single_site(self, distr='glo'): """ Return flood growth curve function based on `amax_records` from the subject catchment only. :return: Inverse cumulative distribution function with one parameter `aep` (annual exceedance probability) :type: :class:`.GrowthCurve` ...
python
{ "resource": "" }
q57412
GrowthCurveAnalysis._growth_curve_pooling_group
train
def _growth_curve_pooling_group(self, distr='glo', as_rural=False): """ Return flood growth curve function based on `amax_records` from a pooling group. :return: Inverse cumulative distribution function with one parameter `aep` (annual exceedance probability) :type: :class:`.GrowthCurve...
python
{ "resource": "" }
q57413
VersionsCheck.process
train
def process(self, document): """Logging versions of required tools.""" content = json.dumps(document) versions = {} versions.update({'Spline': Version(VERSION)}) versions.update(self.get_version("Bash", self.BASH_VERSION)) if content.find('"docker(container)":') >= 0 or...
python
{ "resource": "" }
q57414
VersionsCheck.get_version
train
def get_version(tool_name, tool_command): """ Get name and version of a tool defined by given command. Args: tool_name (str): name of the tool. tool_command (str): Bash one line command to get the version of the tool. Returns: dict: tool name and ver...
python
{ "resource": "" }
q57415
VersionsReport.process
train
def process(self, versions): """Logging version sorted ascending by tool name.""" for tool_name in sorted(versions.keys()): version = versions[tool_name] self._log("Using tool '%s', %s" % (tool_name, version))
python
{ "resource": "" }
q57416
Dispatcher.register_event
train
def register_event(self, *names): """Registers new events after instance creation Args: *names (str): Name or names of the events to register """ for name in names: if name in self.__events: continue self.__events[name] = Event(name)
python
{ "resource": "" }
q57417
Dispatcher.emit
train
def emit(self, name, *args, **kwargs): """Dispatches an event to any subscribed listeners Note: If a listener returns :obj:`False`, the event will stop dispatching to other listeners. Any other return value is ignored. Args: name (str): The name of the :clas...
python
{ "resource": "" }
q57418
Dispatcher.get_dispatcher_event
train
def get_dispatcher_event(self, name): """Retrieves an Event object by name Args: name (str): The name of the :class:`Event` or :class:`~pydispatch.properties.Property` object to retrieve Returns: The :class:`Event` instance for the event or property defi...
python
{ "resource": "" }
q57419
Dispatcher.emission_lock
train
def emission_lock(self, name): """Holds emission of events and dispatches the last event on release The context manager returned will store the last event data called by :meth:`emit` and prevent callbacks until it exits. On exit, it will dispatch the last event captured (if any):: ...
python
{ "resource": "" }
q57420
TEST
train
def TEST(fname): """ Test function to step through all functions in order to try and identify all features on a map This test function should be placed in a main section later """ #fname = os.path.join(os.getcwd(), '..','..', # os.path.join(os.path.getcwd(), ' m = MapObject(fname, os.p...
python
{ "resource": "" }
q57421
DataTable.describe_contents
train
def describe_contents(self): """ describes various contents of data table """ print('======================================================================') print(self) print('Table = ', str(len(self.header)) + ' cols x ' + str(len(self.arr)) + ' rows') print('HEADER = ', self...
python
{ "resource": "" }
q57422
DataTable.get_distinct_values_from_cols
train
def get_distinct_values_from_cols(self, l_col_list): """ returns the list of distinct combinations in a dataset based on the columns in the list. Note that this is currently implemented as MAX permutations of the combo so it is not guarenteed to have values in each case. ...
python
{ "resource": "" }
q57423
DataTable.select_where
train
def select_where(self, where_col_list, where_value_list, col_name=''): """ selects rows from the array where col_list == val_list """ res = [] # list of rows to be returned col_ids = [] # ids of the columns to check #print('select_where : arr = ', len(self.ar...
python
{ "resource": "" }
q57424
DataTable.update_where
train
def update_where(self, col, value, where_col_list, where_value_list): """ updates the array to set cell = value where col_list == val_list """ if type(col) is str: col_ndx = self.get_col_by_name(col) else: col_ndx = col #print('col_ndx = ', col_nd...
python
{ "resource": "" }
q57425
DataTable.percentile
train
def percentile(self, lst_data, percent , key=lambda x:x): """ calculates the 'num' percentile of the items in the list """ new_list = sorted(lst_data) #print('new list = ' , new_list) #n = float(len(lst_data)) k = (len(new_list)-1) * percent f = math.floor(k) c = ...
python
{ "resource": "" }
q57426
DataTable.save
train
def save(self, filename, content): """ default is to save a file from list of lines """ with open(filename, "w") as f: if hasattr(content, '__iter__'): f.write('\n'.join([row for row in content])) else: print('WRINGI CONTWETESWREWR'...
python
{ "resource": "" }
q57427
DataTable.save_csv
train
def save_csv(self, filename, write_header_separately=True): """ save the default array as a CSV file """ txt = '' #print("SAVING arr = ", self.arr) with open(filename, "w") as f: if write_header_separately: f.write(','.join([c for c in...
python
{ "resource": "" }
q57428
DataTable.drop
train
def drop(self, fname): """ drop the table, view or delete the file """ if self.dataset_type == 'file': import os try: os.remove(fname) except Exception as ex: print('cant drop file "' + fname + '" : ' + str(ex))
python
{ "resource": "" }
q57429
DataTable.get_col_data_by_name
train
def get_col_data_by_name(self, col_name, WHERE_Clause=''): """ returns the values of col_name according to where """ #print('get_col_data_by_name: col_name = ', col_name, ' WHERE = ', WHERE_Clause) col_key = self.get_col_by_name(col_name) if col_key is None: print('get_col_da...
python
{ "resource": "" }
q57430
DataTable.format_rst
train
def format_rst(self): """ return table in RST format """ res = '' num_cols = len(self.header) col_width = 25 for _ in range(num_cols): res += ''.join(['=' for _ in range(col_width - 1)]) + ' ' res += '\n' for c in self.header: ...
python
{ "resource": "" }
q57431
getHomoloGene
train
def getHomoloGene(taxfile="build_inputs/taxid_taxname",\ genefile="homologene.data",\ proteinsfile="build_inputs/all_proteins.data",\ proteinsclusterfile="build_inputs/proteins_for_clustering.data",\ baseURL="http://ftp.ncbi.nih.gov/pub/HomoloGene/...
python
{ "resource": "" }
q57432
getFasta
train
def getFasta(opened_file, sequence_name): """ Retrieves a sequence from an opened multifasta file :param opened_file: an opened multifasta file eg. opened_file=open("/path/to/file.fa",'r+') :param sequence_name: the name of the sequence to be retrieved eg. for '>2 dna:chromosome chromosome:GRCm38:2:1:1...
python
{ "resource": "" }
q57433
writeFasta
train
def writeFasta(sequence, sequence_name, output_file): """ Writes a fasta sequence into a file. :param sequence: a string with the sequence to be written :param sequence_name: name of the the fasta sequence :param output_file: /path/to/file.fa to be written :returns: nothing """ i=0 ...
python
{ "resource": "" }
q57434
rewriteFasta
train
def rewriteFasta(sequence, sequence_name, fasta_in, fasta_out): """ Rewrites a specific sequence in a multifasta file while keeping the sequence header. :param sequence: a string with the sequence to be written :param sequence_name: the name of the sequence to be retrieved eg. for '>2 dna:chromosome ch...
python
{ "resource": "" }
q57435
Toolbox._get_tool_str
train
def _get_tool_str(self, tool): """ get a string representation of the tool """ res = tool['file'] try: res += '.' + tool['function'] except Exception as ex: print('Warning - no function defined for tool ' + str(tool)) res += '\n' r...
python
{ "resource": "" }
q57436
Toolbox.get_tool_by_name
train
def get_tool_by_name(self, nme): """ get the tool object by name or file """ for t in self.lstTools: if 'name' in t: if t['name'] == nme: return t if 'file' in t: if t['file'] == nme: return t...
python
{ "resource": "" }
q57437
Toolbox.save
train
def save(self, fname=''): """ Save the list of tools to AIKIF core and optionally to local file fname """ if fname != '': with open(fname, 'w') as f: for t in self.lstTools: self.verify(t) f.write(self.tool_as_string(t))
python
{ "resource": "" }
q57438
Toolbox.verify
train
def verify(self, tool): """ check that the tool exists """ if os.path.isfile(tool['file']): print('Toolbox: program exists = TOK :: ' + tool['file']) return True else: print('Toolbox: program exists = FAIL :: ' + tool['file']) retu...
python
{ "resource": "" }
q57439
Toolbox.run
train
def run(self, tool, args, new_import_path=''): """ import the tool and call the function, passing the args. """ if new_import_path != '': #print('APPENDING PATH = ', new_import_path) sys.path.append(new_import_path) #if silent == 'N': prin...
python
{ "resource": "" }
q57440
main
train
def main(**kwargs): """The Pipeline tool.""" options = ApplicationOptions(**kwargs) Event.configure(is_logging_enabled=options.event_logging) application = Application(options) application.run(options.definition)
python
{ "resource": "" }
q57441
Application.setup_logging
train
def setup_logging(self): """Setup of application logging.""" is_custom_logging = len(self.options.logging_config) > 0 is_custom_logging = is_custom_logging and os.path.isfile(self.options.logging_config) is_custom_logging = is_custom_logging and not self.options.dry_run if is_cu...
python
{ "resource": "" }
q57442
Application.validate_document
train
def validate_document(self, definition): """ Validate given pipeline document. The method is trying to load, parse and validate the spline document. The validator verifies the Python structure B{not} the file format. Args: definition (str): path and filename of a ya...
python
{ "resource": "" }
q57443
Application.run_matrix
train
def run_matrix(self, matrix_definition, document): """ Running pipeline via a matrix. Args: matrix_definition (dict): one concrete matrix item. document (dict): spline document (complete) as loaded from yaml file. """ matrix = Matrix(matrix_definition, 'm...
python
{ "resource": "" }
q57444
Application.shutdown
train
def shutdown(self, collector, success): """Shutdown of the application.""" self.event.delegate(success) if collector is not None: collector.queue.put(None) collector.join() if not success: sys.exit(1)
python
{ "resource": "" }
q57445
Application.provide_temporary_scripts_path
train
def provide_temporary_scripts_path(self): """When configured trying to ensure that path does exist.""" if len(self.options.temporary_scripts_path) > 0: if os.path.isfile(self.options.temporary_scripts_path): self.logger.error("Error: configured script path seems to be a file!...
python
{ "resource": "" }
q57446
Application.create_and_run_collector
train
def create_and_run_collector(document, options): """Create and run collector process for report data.""" collector = None if not options.report == 'off': collector = Collector() collector.store.configure(document) Event.configure(collector_queue=collector.queu...
python
{ "resource": "" }
q57447
docker_environment
train
def docker_environment(env): """ Transform dictionary of environment variables into Docker -e parameters. >>> result = docker_environment({'param1': 'val1', 'param2': 'val2'}) >>> result in ['-e "param1=val1" -e "param2=val2"', '-e "param2=val2" -e "param1=val1"'] True """ return ' '.join( ...
python
{ "resource": "" }
q57448
_retrieve_download_url
train
def _retrieve_download_url(): """ Retrieves download location for FEH data zip file from hosted json configuration file. :return: URL for FEH data file :rtype: str """ try: # Try to obtain the url from the Open Hydrology json config file. with urlopen(config['nrfa']['oh_json_url...
python
{ "resource": "" }
q57449
update_available
train
def update_available(after_days=1): """ Check whether updated NRFA data is available. :param after_days: Only check if not checked previously since a certain number of days ago :type after_days: float :return: `True` if update available, `False` if not, `None` if remote location cannot be reached. ...
python
{ "resource": "" }
q57450
download_data
train
def download_data(): """ Downloads complete station dataset including catchment descriptors and amax records. And saves it into a cache folder. """ with urlopen(_retrieve_download_url()) as f: with open(os.path.join(CACHE_FOLDER, CACHE_ZIP), "wb") as local_file: local_file.write(...
python
{ "resource": "" }
q57451
_update_nrfa_metadata
train
def _update_nrfa_metadata(remote_config): """ Save NRFA metadata to local config file using retrieved config data :param remote_config: Downloaded JSON data, not a ConfigParser object! """ config['nrfa']['oh_json_url'] = remote_config['nrfa_oh_json_url'] config['nrfa']['version'] = remote_confi...
python
{ "resource": "" }
q57452
nrfa_metadata
train
def nrfa_metadata(): """ Return metadata on the NRFA data. Returned metadata is a dict with the following elements: - `url`: string with NRFA data download URL - `version`: string with NRFA version number, e.g. '3.3.4' - `published_on`: datetime of data release/publication (only month and year...
python
{ "resource": "" }
q57453
unzip_data
train
def unzip_data(): """ Extract all files from downloaded FEH data zip file. """ with ZipFile(os.path.join(CACHE_FOLDER, CACHE_ZIP), 'r') as zf: zf.extractall(path=CACHE_FOLDER)
python
{ "resource": "" }
q57454
get_xml_stats
train
def get_xml_stats(fname): """ return a dictionary of statistics about an XML file including size in bytes, num lines, number of elements, count by elements """ f = mod_file.TextFile(fname) res = {} res['shortname'] = f.name res['folder'] = f.path res['filesize'] = str(f.size) + ...
python
{ "resource": "" }
q57455
make_random_xml_file
train
def make_random_xml_file(fname, num_elements=200, depth=3): """ makes a random xml file mainly for testing the xml_split """ with open(fname, 'w') as f: f.write('<?xml version="1.0" ?>\n<random>\n') for dep_num, _ in enumerate(range(1,depth)): f.write(' <depth>\n <content>\n...
python
{ "resource": "" }
q57456
organismsKEGG
train
def organismsKEGG(): """ Lists all organisms present in the KEGG database. :returns: a dataframe containing one organism per row. """ organisms=urlopen("http://rest.kegg.jp/list/organism").read() organisms=organisms.split("\n") #for o in organisms: # print o # sys.stdout.flus...
python
{ "resource": "" }
q57457
databasesKEGG
train
def databasesKEGG(organism,ens_ids): """ Finds KEGG database identifiers for a respective organism given example ensembl ids. :param organism: an organism as listed in organismsKEGG() :param ens_ids: a list of ensenbl ids of the respective organism :returns: nothing if no database was found, or a...
python
{ "resource": "" }
q57458
ensembl_to_kegg
train
def ensembl_to_kegg(organism,kegg_db): """ Looks up KEGG mappings of KEGG ids to ensembl ids :param organism: an organisms as listed in organismsKEGG() :param kegg_db: a matching KEGG db as reported in databasesKEGG :returns: a Pandas dataframe of with 'KEGGid' and 'ENSid'. """ print("KEG...
python
{ "resource": "" }
q57459
ecs_idsKEGG
train
def ecs_idsKEGG(organism): """ Uses KEGG to retrieve all ids and respective ecs for a given KEGG organism :param organism: an organisms as listed in organismsKEGG() :returns: a Pandas dataframe of with 'ec' and 'KEGGid'. """ kegg_ec=urlopen("http://rest.kegg.jp/link/"+organism+"/enzyme").read...
python
{ "resource": "" }
q57460
idsKEGG
train
def idsKEGG(organism): """ Uses KEGG to retrieve all ids for a given KEGG organism :param organism: an organism as listed in organismsKEGG() :returns: a Pandas dataframe of with 'gene_name' and 'KEGGid'. """ ORG=urlopen("http://rest.kegg.jp/list/"+organism).read() ORG=ORG.split("\n") ...
python
{ "resource": "" }
q57461
biomaRtTOkegg
train
def biomaRtTOkegg(df): """ Transforms a pandas dataframe with the columns 'ensembl_gene_id','kegg_enzyme' to dataframe ready for use in ... :param df: a pandas dataframe with the following columns: 'ensembl_gene_id','kegg_enzyme' :returns: a pandas dataframe with the following columns: 'ensembl_ge...
python
{ "resource": "" }
q57462
expKEGG
train
def expKEGG(organism,names_KEGGids): """ Gets all KEGG pathways for an organism :param organism: an organism as listed in organismsKEGG() :param names_KEGGids: a Pandas dataframe with the columns 'gene_name': and 'KEGGid' as reported from idsKEGG(organism) (or a subset of it). :returns df: a Pand...
python
{ "resource": "" }
q57463
RdatabasesBM
train
def RdatabasesBM(host=rbiomart_host): """ Lists BioMart databases through a RPY2 connection. :param host: address of the host server, default='www.ensembl.org' :returns: nothing """ biomaRt = importr("biomaRt") print(biomaRt.listMarts(host=host))
python
{ "resource": "" }
q57464
RdatasetsBM
train
def RdatasetsBM(database,host=rbiomart_host): """ Lists BioMart datasets through a RPY2 connection. :param database: a database listed in RdatabasesBM() :param host: address of the host server, default='www.ensembl.org' :returns: nothing """ biomaRt = importr("biomaRt") ensemblMart=bi...
python
{ "resource": "" }
q57465
RfiltersBM
train
def RfiltersBM(dataset,database,host=rbiomart_host): """ Lists BioMart filters through a RPY2 connection. :param dataset: a dataset listed in RdatasetsBM() :param database: a database listed in RdatabasesBM() :param host: address of the host server, default='www.ensembl.org' :returns: nothing ...
python
{ "resource": "" }
q57466
RattributesBM
train
def RattributesBM(dataset,database,host=rbiomart_host): """ Lists BioMart attributes through a RPY2 connection. :param dataset: a dataset listed in RdatasetsBM() :param database: a database listed in RdatabasesBM() :param host: address of the host server, default='www.ensembl.org' :returns: no...
python
{ "resource": "" }
q57467
get_list_of_applications
train
def get_list_of_applications(): """ Get list of applications """ apps = mod_prg.Programs('Applications', 'C:\\apps') fl = mod_fl.FileList(['C:\\apps'], ['*.exe'], ["\\bk\\"]) for f in fl.get_list(): apps.add(f, 'autogenerated list') apps.list() apps.save()
python
{ "resource": "" }
q57468
WTFormsDynamicFields.add_field
train
def add_field(self, name, label, field_type, *args, **kwargs): """ Add the field to the internal configuration dictionary. """ if name in self._dyn_fields: raise AttributeError('Field already added to the form.') else: self._dyn_fields[name] = {'label': label, 'type': fie...
python
{ "resource": "" }
q57469
WTFormsDynamicFields.add_validator
train
def add_validator(self, name, validator, *args, **kwargs): """ Add the validator to the internal configuration dictionary. :param name: The field machine name to apply the validator on :param validator: The WTForms validator object The rest are optional arguments...
python
{ "resource": "" }
q57470
WTFormsDynamicFields.process
train
def process(self, form, post): """ Process the given WTForm Form object. Itterate over the POST values and check each field against the configuration that was made. For each field that is valid, check all the validator parameters for possible %field% replacement, then bind ...
python
{ "resource": "" }
q57471
GetBEDnarrowPeakgz
train
def GetBEDnarrowPeakgz(URL_or_PATH_TO_file): """ Reads a gz compressed BED narrow peak file from a web address or local file :param URL_or_PATH_TO_file: web address of path to local file :returns: a Pandas dataframe """ if os.path.isfile(URL_or_PATH_TO_file): response=open(URL_or_PATH...
python
{ "resource": "" }
q57472
dfTObedtool
train
def dfTObedtool(df): """ Transforms a pandas dataframe into a bedtool :param df: Pandas dataframe :returns: a bedtool """ df=df.astype(str) df=df.drop_duplicates() df=df.values.tolist() df=["\t".join(s) for s in df ] df="\n".join(df) df=BedTool(df, from_string=True) re...
python
{ "resource": "" }
q57473
Event.configure
train
def configure(**kwargs): """Global configuration for event handling.""" for key in kwargs: if key == 'is_logging_enabled': Event.is_logging_enabled = kwargs[key] elif key == 'collector_queue': Event.collector_queue = kwargs[key] else: ...
python
{ "resource": "" }
q57474
Event.failed
train
def failed(self, **kwargs): """Finish event as failed with optional additional information.""" self.finished = datetime.now() self.status = 'failed' self.information.update(kwargs) self.logger.info("Failed - took %f seconds.", self.duration()) self.update_report_collector...
python
{ "resource": "" }
q57475
Event.update_report_collector
train
def update_report_collector(self, timestamp): """Updating report collector for pipeline details.""" report_enabled = 'report' in self.information and self.information['report'] == 'html' report_enabled = report_enabled and 'stage' in self.information report_enabled = report_enabled and E...
python
{ "resource": "" }
q57476
count_lines_in_file
train
def count_lines_in_file(src_file ): """ test function. """ tot = 0 res = '' try: with open(src_file, 'r') as f: for line in f: tot += 1 res = str(tot) + ' recs read' except: res = 'ERROR -couldnt open file' return res
python
{ "resource": "" }
q57477
load_txt_to_sql
train
def load_txt_to_sql(tbl_name, src_file_and_path, src_file, op_folder): """ creates a SQL loader script to load a text file into a database and then executes it. Note that src_file is """ if op_folder == '': pth = '' else: pth = op_folder + os.sep fname_create_script...
python
{ "resource": "" }
q57478
anext
train
async def anext(*args): """Return the next item from an async iterator. Args: iterable: An async iterable. default: An optional default value to return if the iterable is empty. Return: The next value of the iterable. Raises: TypeError: The iterable given is not async....
python
{ "resource": "" }
q57479
repeat
train
def repeat(obj, times=None): """Make an iterator that returns object over and over again.""" if times is None: return AsyncIterWrapper(sync_itertools.repeat(obj)) return AsyncIterWrapper(sync_itertools.repeat(obj, times))
python
{ "resource": "" }
q57480
_async_callable
train
def _async_callable(func): """Ensure the callable is an async def.""" if isinstance(func, types.CoroutineType): return func @functools.wraps(func) async def _async_def_wrapper(*args, **kwargs): """Wrap a a sync callable in an async def.""" return func(*args, **kwargs) retu...
python
{ "resource": "" }
q57481
tee
train
def tee(iterable, n=2): """Return n independent iterators from a single iterable. Once tee() has made a split, the original iterable should not be used anywhere else; otherwise, the iterable could get advanced without the tee objects being informed. This itertool may require significant auxiliary ...
python
{ "resource": "" }
q57482
Property._on_change
train
def _on_change(self, obj, old, value, **kwargs): """Called internally to emit changes from the instance object The keyword arguments here will be passed to callbacks through the instance object's :meth:`~pydispatch.dispatch.Dispatcher.emit` method. Keyword Args: property: T...
python
{ "resource": "" }
q57483
FehFileParser.parse_str
train
def parse_str(self, s): """ Parse string and return relevant object :param s: string to parse :type s: str :return: Parsed object """ self.object = self.parsed_class() in_section = None # Holds name of FEH file section while traversing through file. ...
python
{ "resource": "" }
q57484
FehFileParser.parse
train
def parse(self, file_name): """ Parse entire file and return relevant object. :param file_name: File path :type file_name: str :return: Parsed object """ self.object = self.parsed_class() with open(file_name, encoding='utf-8') as f: self.parse...
python
{ "resource": "" }
q57485
FinitePage.has_next
train
def has_next(self): """ Checks for one more item than last on this page. """ try: next_item = self.paginator.object_list[self.paginator.per_page] except IndexError: return False return True
python
{ "resource": "" }
q57486
parse_miss_cann
train
def parse_miss_cann(node, m, c): """ extracts names from the node to get counts of miss + cann on both sides """ if node[2]: m1 = node[0] m2 = m-node[0] c1 = node[1] c2 = c-node[1] else: m1=m-node[0] m2=node[0] c1=c-node[1] c2=node...
python
{ "resource": "" }
q57487
solve
train
def solve(m,c): """ run the algorithm to find the path list """ G={ (m,c,1):[] } frontier=[ (m,c,1) ] # 1 as boat starts on left bank while len(frontier) > 0: hold=list(frontier) for node in hold: newnode=[] frontier.remove(node) newnode.exte...
python
{ "resource": "" }
q57488
SQLCodeGenerator.create_script_fact
train
def create_script_fact(self): """ appends the CREATE TABLE, index etc to self.ddl_text """ self.ddl_text += '---------------------------------------------\n' self.ddl_text += '-- CREATE Fact Table - ' + self.fact_table + '\n' self.ddl_text += '----------------------------...
python
{ "resource": "" }
q57489
SQLCodeGenerator.create_script_staging_table
train
def create_script_staging_table(self, output_table, col_list): """ appends the CREATE TABLE, index etc to another table """ self.ddl_text += '---------------------------------------------\n' self.ddl_text += '-- CREATE Staging Table - ' + output_table + '\n' self.ddl_text...
python
{ "resource": "" }
q57490
distinct_values
train
def distinct_values(t_old, t_new): """ for all columns, check which values are not in the other table """ res = [] res.append([' -- NOT IN check -- ']) for new_col in t_new.header: dist_new = t_new.get_distinct_values_from_cols([new_col]) #print('NEW Distinct values for '...
python
{ "resource": "" }
q57491
aikif_web_menu
train
def aikif_web_menu(cur=''): """ returns the web page header containing standard AIKIF top level web menu """ pgeHdg = '' pgeBlurb = '' if cur == '': cur = 'Home' txt = get_header(cur) #"<div id=top_menu>" txt += '<div id = "container">\n' txt += ' <div id = "header">\n' txt +=...
python
{ "resource": "" }
q57492
main
train
def main(): """ This generates the research document based on the results of the various programs and includes RST imports for introduction and summary """ print("Generating research notes...") if os.path.exists(fname): os.remove(fname) append_rst('===============================...
python
{ "resource": "" }
q57493
RawData.find
train
def find(self, txt): """ returns a list of records containing text """ result = [] for d in self.data: if txt in d: result.append(d) return result
python
{ "resource": "" }
q57494
CollectorUpdate.schema_complete
train
def schema_complete(): """Schema for data in CollectorUpdate.""" return Schema({ 'stage': And(str, len), 'timestamp': int, 'status': And(str, lambda s: s in ['started', 'succeeded', 'failed']), # optional matrix Optional('matrix', default='defa...
python
{ "resource": "" }
q57495
CollectorStage.schema_event_items
train
def schema_event_items(): """Schema for event items.""" return { 'timestamp': And(int, lambda n: n > 0), Optional('information', default={}): { Optional(Regex(r'([a-z][_a-z]*)')): object } }
python
{ "resource": "" }
q57496
CollectorStage.schema_complete
train
def schema_complete(): """Schema for data in CollectorStage.""" return Schema({ 'stage': And(str, len), 'status': And(str, lambda s: s in ['started', 'succeeded', 'failed']), Optional('events', default=[]): And(len, [CollectorStage.schema_event_items()]) })
python
{ "resource": "" }
q57497
CollectorStage.add
train
def add(self, timestamp, information): """ Add event information. Args: timestamp (int): event timestamp. information (dict): event information. Raises: RuntimeError: when validation of parameters has failed. """ try: item...
python
{ "resource": "" }
q57498
CollectorStage.duration
train
def duration(self): """ Calculate how long the stage took. Returns: float: (current) duration of the stage """ duration = 0.0 if len(self.events) > 0: first = datetime.fromtimestamp(self.events[0]['timestamp']) last = datetime.fromtime...
python
{ "resource": "" }
q57499
Store.count_stages
train
def count_stages(self, matrix_name): """ Number of registered stages for given matrix name. Parameters: matrix_name (str): name of the matrix Returns: int: number of reported stages for given matrix name. """ return len(self.data[matrix_name]) if...
python
{ "resource": "" }