INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Adds headers to the request
def with_headers(self, headers): '''Adds headers to the request Args: headers (dict): The headers to add the request headers Returns: The request builder instance in order to chain calls ''' copy = headers.copy() copy.update(self._headers) ...
Adds parameters to the request params
def with_params(self, params): '''Adds parameters to the request params Args: params (dict): The parameters to add to the request params Returns: The request builder instance in order to chain calls ''' copy = params.copy() copy.update(self._para...
Defines if the an exception should be thrown after the request is sent
def throw(self, exception_class, should_throw): '''Defines if the an exception should be thrown after the request is sent Args: exception_class (class): The class of the exception to instantiate should_throw (function): The predicate that should indicate if the exception ...
Run the command piping stderr to stdout. Sends output to stdout.: param cmd: The list for args to pass to the process
def run_command(cmd): """ Run the command, piping stderr to stdout. Sends output to stdout. :param cmd: The list for args to pass to the process """ try: process = subprocess.Popen( cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr...
Extract the source bundle: param bundle_path: path to the aource bundle *. tar. gz: param source_path: path to location where to extractall
def extract_source(bundle_path, source_path): """ Extract the source bundle :param bundle_path: path to the aource bundle *.tar.gz :param source_path: path to location where to extractall """ with tarfile.open(bundle_path, 'r:gz') as tf: tf.extractall(path=source_path) logger.debug("...
response is json or straight text.: param data:: return:
def printer(data): """ response is json or straight text. :param data: :return: """ data = str(data) # Get rid of unicode if not isinstance(data, str): output = json.dumps( data, sort_keys=True, indent=4, separators=(',', ': ') ...
Return a sequence containing the fields to be displayed on the changelist.
def get_list_display(self, request): """ Return a sequence containing the fields to be displayed on the changelist. """ list_display = [] for field_name in self.list_display: try: db_field = self.model._meta.get_field(field_name) ...
Spawns a tree of jobs to avoid overloading the number of jobs spawned by a single parent. This function is appropriate to use when batching samples greater than 1 000.
def map_job(job, func, inputs, *args): """ Spawns a tree of jobs to avoid overloading the number of jobs spawned by a single parent. This function is appropriate to use when batching samples greater than 1,000. :param JobFunctionWrappingJob job: passed automatically by Toil :param function func: Fu...
Runs GenotypeGVCFs on one or more gVCFs generated by HaplotypeCaller.
def gatk_genotype_gvcfs(job, gvcfs, ref, fai, ref_dict, annotations=None, emit_threshold=10.0, call_threshold=30.0, unsafe_mode=False): """ Runs GenotypeGVCFs on one or more gVCFs generated by...
Uses Oncotator to add cancer relevant variant annotations to a VCF file. Oncotator can accept other genome builds but the output VCF is based on hg19.
def run_oncotator(job, vcf_id, oncotator_db): """ Uses Oncotator to add cancer relevant variant annotations to a VCF file. Oncotator can accept other genome builds, but the output VCF is based on hg19. :param JobFunctionWrappingJob job: passed automatically by Toil :param str vcf_id: FileStoreID fo...
Sort here works by sorting by timestamp by default
def sort(self, f=lambda d: d["t"]): """Sort here works by sorting by timestamp by default""" list.sort(self, key=f) return self
Returns just the timestamp portion of the datapoints as a list. The timestamps are in python datetime s date format.
def t(self): """Returns just the timestamp portion of the datapoints as a list. The timestamps are in python datetime's date format.""" return list(map(lambda x: datetime.datetime.fromtimestamp(x["t"]), self.raw()))
Writes the data to the given file::
def writeJSON(self, filename): """Writes the data to the given file:: DatapointArray([{"t": unix timestamp, "d": data}]).writeJSON("myfile.json") The data can later be loaded using loadJSON. """ with open(filename, "w") as f: json.dump(self, f)
Adds the data from a JSON file. The file is expected to be in datapoint format::
def loadJSON(self, filename): """Adds the data from a JSON file. The file is expected to be in datapoint format:: d = DatapointArray().loadJSON("myfile.json") """ with open(filename, "r") as f: self.merge(json.load(f)) return self
Adds the data from a ConnectorDB export. If it is a stream export then the folder is the location of the export. If it is a device export then the folder is the export folder with the stream name as a subdirectory
def loadExport(self, folder): """Adds the data from a ConnectorDB export. If it is a stream export, then the folder is the location of the export. If it is a device export, then the folder is the export folder with the stream name as a subdirectory If it is a user export, you will use t...
Shifts all timestamps in the datapoint array by the given number of seconds. It is the same as the tshift pipescript transform.
def tshift(self, t): """Shifts all timestamps in the datapoint array by the given number of seconds. It is the same as the 'tshift' pipescript transform. Warning: The shift is performed in-place! This means that it modifies the underlying array:: d = DatapointArray([{"t":56,"d":1}]...
Gets the sum of the data portions of all datapoints within
def sum(self): """Gets the sum of the data portions of all datapoints within""" raw = self.raw() s = 0 for i in range(len(raw)): s += raw[i]["d"] return s
Start the event loop to collect data from the serial device.
def rfxcom(device): """Start the event loop to collect data from the serial device.""" # If the device isn't passed in, look for it in the config. if device is None: device = app.config.get('DEVICE') # If the device is *still* none, error. if device is None: print("The serial devic...
Create a new user.
def create_user(username): "Create a new user." password = prompt_pass("Enter password") user = User(username=username, password=password) db.session.add(user) db.session.commit()
Safely quotes an IRI in a way that is resilient to unicode and incorrect arguments ( checks for RFC 3987 compliance and falls back to percent encoding )
def to_iri(iri): """ Safely quotes an IRI in a way that is resilient to unicode and incorrect arguments (checks for RFC 3987 compliance and falls back to percent encoding) """ # First decode the IRI if needed (python 2) if sys.version_info[0] < 3: if not isinstance(iri, unicode): ...
Parse Visual Novel search pages.
async def parse_vn_results(soup): """ Parse Visual Novel search pages. :param soup: The BS4 class object :return: A list of dictionaries containing a name and id. """ soup = soup.find_all('td', class_='tc1') vns = [] for item in soup[1:]: vns.append({'name': item.string, 'id': ...
Parse Releases search pages.
async def parse_release_results(soup): """ Parse Releases search pages. :param soup: The BS4 class object :return: A list of dictionaries containing a release dictionary. This is the same as the one returned in get_novel. It contains a Date released, Platform, Ages group and Name. """ ...
Parse a page of producer or staff results
async def parse_prod_staff_results(soup): """ Parse a page of producer or staff results :param soup: The BS4 class object :return: A list of dictionaries containing a name and nationality. """ soup = soup.find_all('li') producers = [] for item in soup: producers.append({'nationa...
Parse a page of character results.
async def parse_character_results(soup): """ Parse a page of character results. :param soup: The BS4 class object :return: Returns a list of dictionaries containing a name, gender and list of dictionaries containing a game name/id pair for games they appeared in. """ soup = list(so...
Parse a page of tag or trait results. Same format.
async def parse_tag_results(soup): """ Parse a page of tag or trait results. Same format. :param soup: BS4 Class Object :return: A list of tags, Nothing else really useful there """ soup = soup.find_all('td', class_='tc3') tags = [] for item in soup: tags.append(item.a.string) ...
Parse a page of user results
async def parse_user_results(soup): """ Parse a page of user results :param soup: Bs4 Class object :return: A list of dictionaries containing a name and join date """ soup = list(soup.find_all('table', class_='stripe')[0].children)[1:] users = [] for item in soup: t_u = {'name':...
Creates a tarball from a group of files
def tarball_files(tar_name, file_paths, output_dir='.', prefix=''): """ Creates a tarball from a group of files :param str tar_name: Name of tarball :param list[str] file_paths: Absolute file paths to include in the tarball :param str output_dir: Output destination for tarball :param str prefix...
Applies a function to a set of files and an output directory.
def __forall_files(file_paths, output_dir, op): """ Applies a function to a set of files and an output directory. :param str output_dir: Output directory :param list[str] file_paths: Absolute file paths to move """ for file_path in file_paths: if not file_path.startswith('/'): ...
Job version of move_files for one file
def copy_file_job(job, name, file_id, output_dir): """ Job version of move_files for one file :param JobFunctionWrappingJob job: passed automatically by Toil :param str name: Name of output file (including extension) :param str file_id: FileStoreID of file :param str output_dir: Location to pla...
Combine the contents of separate tarballs into one. Subdirs within the tarball will be named the keys in ** fname_to_id
def consolidate_tarballs_job(job, fname_to_id): """ Combine the contents of separate tarballs into one. Subdirs within the tarball will be named the keys in **fname_to_id :param JobFunctionWrappingJob job: passed automatically by Toil :param dict[str,str] fname_to_id: Dictionary of the form: file-n...
Makes a Spark Submit style job submission line.
def _make_parameters(master_ip, default_parameters, memory, arguments, override_parameters): """ Makes a Spark Submit style job submission line. :param masterIP: The Spark leader IP address. :param default_parameters: Application specific Spark configuration parameters. :param memory: The memory to...
Invokes the Conductor container to copy files between S3 and HDFS and vice versa. Find Conductor at https:// github. com/ BD2KGenomics/ conductor.
def call_conductor(job, master_ip, src, dst, memory=None, override_parameters=None): """ Invokes the Conductor container to copy files between S3 and HDFS and vice versa. Find Conductor at https://github.com/BD2KGenomics/conductor. :param toil.Job.job job: The Toil Job calling this function :param ...
Invokes the ADAM container. Find ADAM at https:// github. com/ bigdatagenomics/ adam.
def call_adam(job, master_ip, arguments, memory=None, override_parameters=None, run_local=False, native_adam_path=None): """ Invokes the ADAM container. Find ADAM at https://github.com/bigdatagenomics/adam. :param toil.Job.job job: The Toil Job callin...
Augment a list of docker run arguments with those needed to map the notional Spark master address to the real one if they are different.
def docker_parameters(self, docker_parameters=None): """ Augment a list of "docker run" arguments with those needed to map the notional Spark master address to the real one, if they are different. """ if self != self.actual: add_host_option = '--add-host=spark-master...
Refresh reloads data from the server. It raises an error if it fails to get the object s metadata
def refresh(self): """Refresh reloads data from the server. It raises an error if it fails to get the object's metadata""" self.metadata = self.db.read(self.path).json()
Attempts to set the given properties of the object. An example of this is setting the nickname of the object:: cdb. set ( { nickname: My new nickname } ) note that there is a convenience property cdb. nickname that allows you to get/ set the nickname directly.
def set(self, property_dict): """Attempts to set the given properties of the object. An example of this is setting the nickname of the object:: cdb.set({"nickname": "My new nickname"}) note that there is a convenience property `cdb.nickname` that allows you to get/set the nic...
Calls MuTect to perform variant analysis
def run_mutect(job, normal_bam, normal_bai, tumor_bam, tumor_bai, ref, ref_dict, fai, cosmic, dbsnp): """ Calls MuTect to perform variant analysis :param JobFunctionWrappingJob job: passed automatically by Toil :param str normal_bam: Normal BAM FileStoreID :param str normal_bai: Normal BAM index Fi...
Calls Pindel to compute indels/ deletions
def run_pindel(job, normal_bam, normal_bai, tumor_bam, tumor_bai, ref, fai): """ Calls Pindel to compute indels / deletions :param JobFunctionWrappingJob job: Passed automatically by Toil :param str normal_bam: Normal BAM FileStoreID :param str normal_bai: Normal BAM index FileStoreID :param st...
Creates the device. Attempts to create private devices by default but if public is set to true creates public devices.
def create(self, public=False, **kwargs): """Creates the device. Attempts to create private devices by default, but if public is set to true, creates public devices. You can also set other default properties by passing in the relevant information. For example, setting a device with the ...
Returns the list of streams that belong to the device
def streams(self): """Returns the list of streams that belong to the device""" result = self.db.read(self.path, {"q": "ls"}) if result is None or result.json() is None: return [] streams = [] for s in result.json(): strm = self[s["name"]] strm...
Exports the device to the given directory. The directory can t exist. You can later import this device by running import_device on a user.
def export(self, directory): """Exports the device to the given directory. The directory can't exist. You can later import this device by running import_device on a user. """ if os.path.exists(directory): raise FileExistsError( "The device export directory al...
Imports a stream from the given directory. You export the Stream by using stream. export ()
def import_stream(self, directory): """Imports a stream from the given directory. You export the Stream by using stream.export()""" # read the stream's info with open(os.path.join(directory, "stream.json"), "r") as f: sdata = json.load(f) s = self[sdata["name"]] ...
Search vndb. org for a term and return matching results from type.
async def search_vndb(self, stype, term): """ Search vndb.org for a term and return matching results from type. :param stype: type to search for. Type should be one of: v - Visual Novels r - Releases p - Producers s - S...
If term is an ID will return that specific ID. If it s a string it will return the details of the first search result for that term. Returned Dictionary Has the following structure: Please note if it says list or dict it means the python types. Indentation indicates level. So English is [ Titles ] [ English ]
async def get_novel(self, term, hide_nsfw=False): """ If term is an ID will return that specific ID. If it's a string, it will return the details of the first search result for that term. Returned Dictionary Has the following structure: Please note, if it says list or dict, it means the ...
This is our parsing dispatcher
async def parse_search(self, stype, soup): """ This is our parsing dispatcher :param stype: Search type category :param soup: The beautifulsoup object that contains the parsed html """ if stype == 'v': return await parse_vn_results(soup) elif stype ==...
Adds the given stream to the query construction. Additionally you can choose the interpolator to use for this stream as well as a special name for the column in the returned dataset. If no column name is given the full stream path will be used.
def addStream(self, stream, interpolator="closest", t1=None, t2=None, dt=None, limit=None, i1=None, i2=None, transform=None,colname=None): """Adds the given stream to the query construction. Additionally, you can choose the interpolator to use for this stream, as well as a special name for the column in...
invalidates the device s current api key and generates a new one. Resets current auth to use the new apikey since the change would have future queries fail if they use the old api key.
def reset_apikey(self): """invalidates the device's current api key, and generates a new one. Resets current auth to use the new apikey, since the change would have future queries fail if they use the old api key.""" apikey = Device.reset_apikey(self) self.db.setauth(apikey) retu...
returns a dictionary of information about the database including the database version the transforms and the interpolators supported::
def info(self): """returns a dictionary of information about the database, including the database version, the transforms and the interpolators supported:: >>>cdb = connectordb.ConnectorDB(apikey) >>>cdb.info() { "version": "0.3.0", "t...
Returns the list of users in the database
def users(self): """Returns the list of users in the database""" result = self.db.read("", {"q": "ls"}) if result is None or result.json() is None: return [] users = [] for u in result.json(): usr = self(u["name"]) usr.metadata = u ...
Imports version 1 of ConnectorDB export. These exports can be generated by running user. export ( dir ) possibly on multiple users.
def import_users(self, directory): """Imports version 1 of ConnectorDB export. These exports can be generated by running user.export(dir), possibly on multiple users. """ exportInfoFile = os.path.join(directory, "connectordb.json") with open(exportInfoFile) as f: expo...
Use BWA to create reference index files
def run_bwa_index(job, ref_id): """ Use BWA to create reference index files :param JobFunctionWrappingJob job: passed automatically by Toil :param str ref_id: FileStoreID for the reference genome :return: FileStoreIDs for BWA index files :rtype: tuple(str, str, str, str, str) """ job.fi...
Returns the ConnectorDB object that the logger uses. Raises an error if Logger isn t able to connect
def connectordb(self): """Returns the ConnectorDB object that the logger uses. Raises an error if Logger isn't able to connect""" if self.__cdb is None: logging.debug("Logger: Connecting to " + self.serverurl) self.__cdb = ConnectorDB(self.apikey, url=self.serverurl) retu...
Adds the given stream to the logger. Requires an active connection to the ConnectorDB database.
def addStream(self, streamname, schema=None, **kwargs): """Adds the given stream to the logger. Requires an active connection to the ConnectorDB database. If a schema is not specified, loads the stream from the database. If a schema is specified, and the stream does not exist, creates the strea...
This function adds the given stream to the logger but does not check with a ConnectorDB database to make sure that the stream exists. Use at your own risk.
def addStream_force(self, streamname, schema=None): """This function adds the given stream to the logger, but does not check with a ConnectorDB database to make sure that the stream exists. Use at your own risk.""" c = self.database.cursor() c.execute("INSERT OR REPLACE INTO streams VAL...
Insert the datapoint into the logger for the given stream name. The logger caches the datapoint and eventually synchronizes it with ConnectorDB
def insert(self, streamname, value): """Insert the datapoint into the logger for the given stream name. The logger caches the datapoint and eventually synchronizes it with ConnectorDB""" if streamname not in self.streams: raise Exception("The stream '%s' was not found" % (streamname,...
Inserts data into the cache if the data is a dict of the form { streamname: [ { t: timestamp d: data... ] }
def insert_many(self, data_dict): """ Inserts data into the cache, if the data is a dict of the form {streamname: [{"t": timestamp,"d":data,...]}""" c = self.database.cursor() c.execute("BEGIN TRANSACTION;") try: for streamname in data_dict: if streamname not ...
Attempt to sync with the ConnectorDB server
def sync(self): """Attempt to sync with the ConnectorDB server""" logging.debug("Logger: Syncing...") failed = False try: # Get the connectordb object cdb = self.connectordb # Ping the database - most connection errors will happen here cdb...
Start the logger background synchronization service. This allows you to not need to worry about syncing with ConnectorDB - you just insert into the Logger and the Logger will by synced every syncperiod.
def start(self): """Start the logger background synchronization service. This allows you to not need to worry about syncing with ConnectorDB - you just insert into the Logger, and the Logger will by synced every syncperiod.""" with self.synclock: if self.syncthread is not No...
Stops the background synchronization thread
def stop(self): """Stops the background synchronization thread""" with self.synclock: if self.syncthread is not None: self.syncthread.cancel() self.syncthread = None
The data property allows the user to save settings/ data in the database so that there does not need to be extra code messing around with settings.
def data(self): """The data property allows the user to save settings/data in the database, so that there does not need to be extra code messing around with settings. Use this property to save things that can be converted to JSON inside the logger database, so that you don't have to mes...
Build a file path from * paths * and return the contents.
def read(*paths): """Build a file path from *paths* and return the contents.""" filename = os.path.join(*paths) with codecs.open(filename, mode='r', encoding='utf-8') as handle: return handle.read()
Downloads URL can pass in file:// http:// s3:// or ftp:// gnos:// cghub/ analysisID or gnos:/// analysisID If downloading S3 URLs the S3AM binary must be on the PATH
def download_url(job, url, work_dir='.', name=None, s3_key_path=None, cghub_key_path=None): """ Downloads URL, can pass in file://, http://, s3://, or ftp://, gnos://cghub/analysisID, or gnos:///analysisID If downloading S3 URLs, the S3AM binary must be on the PATH :param toil.job.Job job: Toil job tha...
Job version of download_url
def download_url_job(job, url, name=None, s3_key_path=None, cghub_key_path=None): """Job version of `download_url`""" work_dir = job.fileStore.getLocalTempDir() fpath = download_url(job=job, url=url, work_dir=work_dir, name=name, s3_key_path=s3_key_path, cghub_key_path=cghub_key_pat...
Uploads a file to s3 via S3AM S3AM binary must be on the PATH to use this function For SSE - C encryption: provide a path to a 32 - byte file
def s3am_upload(job, fpath, s3_dir, num_cores=1, s3_key_path=None): """ Uploads a file to s3 via S3AM S3AM binary must be on the PATH to use this function For SSE-C encryption: provide a path to a 32-byte file :param toil.job.Job job: Toil job that is calling this function :param str fpath: Pat...
Job version of s3am_upload
def s3am_upload_job(job, file_id, file_name, s3_dir, s3_key_path=None): """Job version of s3am_upload""" work_dir = job.fileStore.getLocalTempDir() fpath = job.fileStore.readGlobalFile(file_id, os.path.join(work_dir, file_name)) s3am_upload(job=job, fpath=fpath, s3_dir=s3_dir, num_cores=job.cores, s3_ke...
Run s3am with 3 retries
def _s3am_with_retry(job, num_cores, file_path, s3_url, mode='upload', s3_key_path=None): """ Run s3am with 3 retries :param toil.job.Job job: Toil job that is calling this function :param int num_cores: Number of cores to pass to upload/download slots :param str file_path: Full path to the file ...
Output the names to the given file
def labels(ontology, output, ols_base): """Output the names to the given file""" for label in get_labels(ontology=ontology, ols_base=ols_base): click.echo(label, file=output)
Output the parent - child relations to the given file
def tree(ontology, output, ols_base): """Output the parent-child relations to the given file""" for parent, child in get_hierarchy(ontology=ontology, ols_base=ols_base): click.echo('{}\t{}'.format(parent, child), file=output)
Function taken from MC3 Pipeline
def get_mean_insert_size(work_dir, bam_name): """Function taken from MC3 Pipeline""" cmd = "docker run --log-driver=none --rm -v {}:/data quay.io/ucsc_cgl/samtools " \ "view -f66 {}".format(work_dir, os.path.join(work_dir, bam_name)) process = subprocess.Popen(args=cmd, shell=True, stdout=subproce...
>>> list ( partitions ( [] 10 )) [] >>> list ( partitions ( [ 1 2 3 4 5 ] 1 )) [[ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ]] >>> list ( partitions ( [ 1 2 3 4 5 ] 2 )) [[ 1 2 ] [ 3 4 ] [ 5 ]] >>> list ( partitions ( [ 1 2 3 4 5 ] 5 )) [[ 1 2 3 4 5 ]]
def partitions(l, partition_size): """ >>> list(partitions([], 10)) [] >>> list(partitions([1,2,3,4,5], 1)) [[1], [2], [3], [4], [5]] >>> list(partitions([1,2,3,4,5], 2)) [[1, 2], [3, 4], [5]] >>> list(partitions([1,2,3,4,5], 5)) [[1, 2, 3, 4, 5]] :param list l: List to be parti...
For use with argparse s action argument. Allows setting a range for nargs. Example: nargs = + action = required_length ( 2 3 )
def required_length(nmin, nmax): """ For use with argparse's action argument. Allows setting a range for nargs. Example: nargs='+', action=required_length(2, 3) :param int nmin: Minimum number of arguments :param int nmax: Maximum number of arguments :return: RequiredLength object """ c...
Returns a string that represents the container ID of the current Docker container. If this function is invoked outside of a container a NotInsideContainerError is raised.
def current_docker_container_id(): """ Returns a string that represents the container ID of the current Docker container. If this function is invoked outside of a container a NotInsideContainerError is raised. >>> import subprocess >>> import sys >>> a = subprocess.check_output(['docker', 'run'...
Performs alignment of fastqs to bam via STAR
def run_star(job, r1_id, r2_id, star_index_url, wiggle=False, sort=True): """ Performs alignment of fastqs to bam via STAR --limitBAMsortRAM step added to deal with memory explosion when sorting certain samples. The value was chosen to complement the recommended amount of memory to have when running ST...
Runs BWA - Kit to align single or paired - end fastq files or realign SAM/ BAM files.
def run_bwakit(job, config, sort=True, trim=False, mark_secondary=False): """ Runs BWA-Kit to align single or paired-end fastq files or realign SAM/BAM files. :param JobFunctionWrappingJob job: Passed by Toil automatically :param Namespace config: A configuration object that holds strings as attributes...
query_maker takes the optional arguments and constructs a json query for a stream s datapoints using it:: # { t1: 5 transform: if $ > 5 } print query_maker ( t1 = 5 transform = if $ > 5 )
def query_maker(t1=None, t2=None, limit=None, i1=None, i2=None, transform=None, downlink=False): """query_maker takes the optional arguments and constructs a json query for a stream's datapoints using it:: #{"t1": 5, "transform": "if $ > 5"} print query_maker(t1=5,transform="if $ > 5") """ ...
Creates a stream given an optional JSON schema encoded as a python dict. You can also add other properties of the stream such as the icon datatype or description. Create accepts both a string schema and a dict - encoded schema.
def create(self, schema="{}", **kwargs): """Creates a stream given an optional JSON schema encoded as a python dict. You can also add other properties of the stream, such as the icon, datatype or description. Create accepts both a string schema and a dict-encoded schema.""" if isinstance...
given an array of datapoints inserts them to the stream. This is different from insert () because it requires an array of valid datapoints whereas insert only requires the data portion of the datapoint and fills out the rest::
def insert_array(self, datapoint_array, restamp=False): """given an array of datapoints, inserts them to the stream. This is different from insert(), because it requires an array of valid datapoints, whereas insert only requires the data portion of the datapoint, and fills out the rest:: ...
insert inserts one datapoint with the given data and appends it to the end of the stream::
def insert(self, data): """insert inserts one datapoint with the given data, and appends it to the end of the stream:: s = cdb["mystream"] s.create({"type": "string"}) s.insert("Hello World!") """ self.insert_array([{"d": data, "t": time.time()}], ...
Subscribes to the stream running the callback function each time datapoints are inserted into the given stream. There is an optional transform to the datapoints and a downlink parameter.::
def subscribe(self, callback, transform="", downlink=False): """Subscribes to the stream, running the callback function each time datapoints are inserted into the given stream. There is an optional transform to the datapoints, and a downlink parameter.:: s = cdb["mystream"] def...
Unsubscribes from a previously subscribed stream. Note that the same values of transform and downlink must be passed in order to do the correct unsubscribe::
def unsubscribe(self, transform="", downlink=False): """Unsubscribes from a previously subscribed stream. Note that the same values of transform and downlink must be passed in order to do the correct unsubscribe:: s.subscribe(callback,transform="if last") s.unsubscribe(transform...
Exports the stream to the given directory. The directory can t exist. You can later import this device by running import_stream on a device.
def export(self, directory): """Exports the stream to the given directory. The directory can't exist. You can later import this device by running import_stream on a device. """ if os.path.exists(directory): raise FileExistsError( "The stream export directory ...
sets the stream s schema. An empty schema is {}. The schemas allow you to set a specific data type. Both python dicts and strings are accepted.
def schema(self, schema): """sets the stream's schema. An empty schema is "{}". The schemas allow you to set a specific data type. Both python dicts and strings are accepted.""" if isinstance(schema, basestring): strschema = schema schema = json.loads(schema) els...
returns the device which owns the given stream
def device(self): """returns the device which owns the given stream""" splitted_path = self.path.split("/") return Device(self.db, splitted_path[0] + "/" + splitted_path[1])
Iterates over the labels of terms in the ontology
def get_labels(ontology, ols_base=None): """Iterates over the labels of terms in the ontology :param str ontology: The name of the ontology :param str ols_base: An optional, custom OLS base url :rtype: iter[str] """ client = OlsClient(ols_base=ols_base) return client.iter_labels(ontology)
Gets the metadata for a given ontology
def get_metadata(ontology, ols_base=None): """Gets the metadata for a given ontology :param str ontology: The name of the ontology :param str ols_base: An optional, custom OLS base url :return: The dictionary representing the JSON from the OLS :rtype: dict """ client = OlsClient(ols_base=ol...
Iterates over the parent - child relationships in an ontolog
def get_hierarchy(ontology, ols_base=None): """Iterates over the parent-child relationships in an ontolog :param str ontology: The name of the ontology :param str ols_base: An optional, custom OLS base url :rtype: iter[tuple[str,str]] """ client = OlsClient(ols_base=ols_base) return client....
Prepares and runs the pipeline. Note this method must be invoked both from inside a Docker container and while the docker daemon is reachable.
def run(cls, name, desc): """ Prepares and runs the pipeline. Note this method must be invoked both from inside a Docker container and while the docker daemon is reachable. :param str name: The name of the command to start the workflow. :param str desc: The description of the wo...
Populates an ArgumentParser object with arguments where each argument is a key from the given config_data dictionary.
def __populate_parser_from_config(self, arg_parser, config_data, prefix=''): """ Populates an ArgumentParser object with arguments where each argument is a key from the given config_data dictionary. :param str prefix: Prepends the key with this prefix delimited by a single '.' character...
Returns the config file contents as a string. The config file is generated and then deleted.
def __get_empty_config(self): """ Returns the config file contents as a string. The config file is generated and then deleted. """ self._generate_config() path = self._get_config_path() with open(path, 'r') as readable: contents = readable.read() os.re...
Returns the path of the mount point of the current container. If this method is invoked outside of a Docker container a NotInsideContainerError is raised. Likewise if the docker daemon is unreachable from inside the container a UserError is raised. This method is idempotent.
def _get_mount_path(self): """ Returns the path of the mount point of the current container. If this method is invoked outside of a Docker container a NotInsideContainerError is raised. Likewise if the docker daemon is unreachable from inside the container a UserError is raised. This met...
Add an argument to the given arg_parser with the given name.
def _add_option(self, arg_parser, name, *args, **kwargs): """ Add an argument to the given arg_parser with the given name. :param argparse.ArgumentParser arg_parser: :param str name: The name of the option. """ arg_parser.add_argument('--' + name, *args, **kwargs)
Creates and returns an ArgumentParser object prepopulated with no clean cores and restart arguments.
def _create_argument_parser(self): """ Creates and returns an ArgumentParser object prepopulated with 'no clean', 'cores' and 'restart' arguments. """ parser = argparse.ArgumentParser(description=self._desc, formatter_class=argparse.RawTex...
Creates and returns a list that represents a command for running the pipeline.
def _create_pipeline_command(self, args, workdir_path, config_path): """ Creates and returns a list that represents a command for running the pipeline. """ return ([self._name, 'run', os.path.join(workdir_path, 'jobStore'), '--config', config_path, '--wo...
setauth sets the authentication header for use in the session. It is for use when apikey is updated or something of the sort such that there is a seamless experience.
def setauth(self, user_or_apikey=None, user_password=None): """ setauth sets the authentication header for use in the session. It is for use when apikey is updated or something of the sort, such that there is a seamless experience. """ auth = None if user_or_apikey is not None: ...
Handles HTTP error codes for the given request
def handleresult(self, r): """Handles HTTP error codes for the given request Raises: AuthenticationError on the appropriate 4** errors ServerError if the response is not an ok (2**) Arguments: r -- The request result """ if r.status_code >= 4...
Attempts to ping the server using current credentials and responds with the path of the currently authenticated device
def ping(self): """Attempts to ping the server using current credentials, and responds with the path of the currently authenticated device""" return self.handleresult(self.r.get(self.url, params={"q": "this"})).text
Run the given query on the connection ( POST request to/ query )
def query(self, query_type, query=None): """Run the given query on the connection (POST request to /query)""" return self.handleresult(self.r.post(urljoin(self.url + "query/", query_type), data=json.dumps(q...
Send a POST CRUD API request to the given path using the given data which will be converted to json
def create(self, path, data=None): """Send a POST CRUD API request to the given path using the given data which will be converted to json""" return self.handleresult(self.r.post(urljoin(self.url + CRUD_PATH, path), ...
Read the result at the given path ( GET ) from the CRUD API using the optional params dictionary as url parameters.
def read(self, path, params=None): """Read the result at the given path (GET) from the CRUD API, using the optional params dictionary as url parameters.""" return self.handleresult(self.r.get(urljoin(self.url + CRUD_PATH, path), ...
Send an update request to the given path of the CRUD API with the given data dict which will be converted into json
def update(self, path, data=None): """Send an update request to the given path of the CRUD API, with the given data dict, which will be converted into json""" return self.handleresult(self.r.put(urljoin(self.url + CRUD_PATH, path), ...