code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
self._pre_save() self._collection.replace_one({ID_KEY: self[ID_KEY]}, dict(self))
def save(self)
Saves the current state of the DatabaseObject to the database. Fills in missing values from defaults before saving. NOTE: The actual operation here is to overwrite the entry in the database with the same ID_KEY. WARNING: While the save operation itself is atomic, it is...
8.852636
7.028806
1.259479
old_id = dict.__getitem__(self, ID_KEY) dict.__setitem__(self, ID_KEY, new_id) self._collection.save(self) self._collection.remove({ID_KEY: old_id})
def rename(self, new_id)
Renames the DatabaseObject to have ID_KEY new_id. This is the only way allowed by DatabaseObject to change the ID_KEY of an object. Trying to modify ID_KEY in the dictionary will raise an exception. @param new_id: the new value for ID_KEY NOTE: This is actually a creat...
3.686558
3.183069
1.158177
self._collection.remove({ID_KEY: self[ID_KEY]}) dict.clear(self)
def remove(self)
Deletes the object from the database WARNING: This cannot be undone. Be really careful when deleting programatically. It is recommended to backup your database before applying specific deletes. If your application uses deletes regularly, it is strongly recommended that you ha...
13.044042
14.362791
0.908183
data = dict(self) data.update(attribute_overrides) if new_id is not None: data[ID_KEY] = new_id return self.create(data, path=self.PATH) else: del data[ID_KEY] return self.create(data, random_id=True, path=self.PATH)
def copy(self, new_id=None, attribute_overrides={})
Copies the DatabaseObject under the ID_KEY new_id. @param new_id: the value for ID_KEY of the copy; if this is none, creates the new object with a random ID_KEY @param attribute_overrides: dictionary of attribute names -> values that you would like to override with.
3.240547
3.08227
1.051351
if update_dict is None: update_dict = kwargs if raw: self._collection.update_one({ID_KEY: self[ID_KEY]}, update_dict) new_data = self._collection.find_one({ID_KEY: self[ID_KEY]}) dict.clear(self) dict.update(self, new_data) els...
def update(self, update_dict=None, raw=False, **kwargs)
Applies updates both to the database object and to the database via the mongo update method with the $set argument. Use the `raw` keyword to perform an arbitrary mongo update query. WARNING: Raw updates do not perform type checking. WARNING: While the update operation ...
2.365989
2.635444
0.897757
update_dict = json.loads(json_str, cls=MongoliaJSONDecoder, encoding="utf-8") # Remove ID_KEY since it can't be part of a mongo update operation if ID_KEY in update_dict: del update_dict[ID_KEY] # Remove all keys in the exclude list from the update f...
def json_update(self, json_str, exclude=[], ignore_non_defaults=True)
Updates a database object based on a json object. The intent of this method is to allow passing json to an interface which then subsequently manipulates the object and then sends back an update. Mongolia will also automatically convert any json values that were initially conver...
3.070065
2.521507
1.217552
update_dict = json.loads(json_str, cls=MongoliaJSONDecoder, encoding="utf-8") update_dict = dict((k, v) for k, v in update_dict.items() if k in fields_to_update and k != ID_KEY) self.update(update_dict)
def json_update_fields(self, json_str, fields_to_update)
Updates the specified fields of a database object based on a json object. The intent of this method is to allow passing json to an interface which then subsequently manipulates the object and then sends back an update for specific fields of the object. Mongolia will also automat...
3.439988
3.309739
1.039353
# generate temp filename for output params["-w"] = "/tmp/" params["-n"] = get_tmp_filename().split("/")[-1] params["-m"] = raxml_model params["-p"] = randint(1,100000) ih = '_input_as_multiline_string' seqs, align_map = align_obj.toPhylip() #print params["-n"] # set up comman...
def raxml_alignment(align_obj, raxml_model="GTRCAT", params={}, SuppressStderr=True, SuppressStdout=True)
Run raxml on alignment object align_obj: Alignment object params: you can set any params except -w and -n returns: tuple (phylonode, parsimonyphylonode, log likelihood, total exec time)
4.577864
4.144874
1.104464
if best_tree: raise NotImplementedError if '-m' not in params: if moltype == DNA or moltype == RNA: #params["-m"] = 'GTRMIX' # in version 7.2.3, GTRMIX is no longer supported but says GTRCAT # behaves like GTRMIX (http://www.phylo.org/tools/raxmlhpc2.htm...
def build_tree_from_alignment(aln, moltype=DNA, best_tree=False, params={})
Returns a tree from Alignment object aln. aln: an xxx.Alignment object, or data that can be used to build one. moltype: cogent.core.moltype.MolType object best_tree: best_tree suppport is currently not implemented params: dict of parameters to pass in to the RAxML app controller. The result wil...
5.144184
4.961929
1.036731
ih = '_input_as_multiline_string' raxml_app = Raxml(params=params, InputHandler=ih, WorkingDir=None, SuppressStderr=False, SuppressStdout=False, HALT_EXEC=False) raxml_result = raxml_app(seq...
def insert_sequences_into_tree(seqs, moltype, params={}, write_log=True)
Insert sequences into Tree. aln: an xxx.Alignment object, or data that can be used to build one. moltype: cogent.core.moltype.MolType object params: dict of parameters to pass in to the RAxML app controller. The result will be a tree.
8.483934
8.282895
1.024272
outfile_name = self._absolute(outfile_name) outparts = outfile_name.split("/") outparts[-1] = self._out_format % (out_type, outparts[-1] ) return '/'.join(outparts)
def _format_output(self, outfile_name, out_type)
Prepend proper output prefix to output filename
5.115214
4.297714
1.190217
out_filenames = [] if self.Parameters['-n'].isOn(): out_name = str(self.Parameters['-n'].Value) walk_root = self.WorkingDir if self.Parameters['-w'].isOn(): walk_root = str(self.Parameters['-w'].Value) for tup in walk(walk_root): ...
def _checkpoint_out_filenames(self)
RAxML generates a crapload of checkpoint files so need to walk directory to collect names of all of them.
3.733499
3.341921
1.117172
try: raise ApplicationError, \ 'RAxML failed to produce an output file due to the following error: \n\n%s ' \ % err.read() except: raise ApplicationError,\ 'RAxML failed to run properly.'
def _handle_app_result_build_failure(self,out,err,exit_status,result_paths)
Catch the error when files are not produced
7.739827
7.777828
0.995114
data = None if not self.connected: raise ConnectionError('Queue is not connected') try: data = self.rdb.keys("retaskqueue-*") except redis.exceptions.ConnectionError as err: raise ConnectionError(str(err)) return [name[12:] for name ...
def names(self)
Returns a list of queues available, ``None`` if no such queues found. Remember this will only shows queues with at least one item enqueued.
6.358806
5.528826
1.150119
if not self.connected: raise ConnectionError('Queue is not connected') try: length = self.rdb.llen(self._name) except redis.exceptions.ConnectionError as err: raise ConnectionError(str(err)) return length
def length(self)
Gives the length of the queue. Returns ``None`` if the queue is not connected. If the queue is not connected then it will raise :class:`retask.ConnectionError`.
4.321104
3.144878
1.374013
config = self.config self.rdb = redis.Redis(config['host'], config['port'], config['db'],\ config['password']) try: info = self.rdb.info() self.connected = True except redis.ConnectionError: return False ...
def connect(self)
Creates the connection with the redis server. Return ``True`` if the connection works, else returns ``False``. It does not take any arguments. :return: ``Boolean`` value .. note:: After creating the ``Queue`` object the user should call the ``connect`` method to ...
3.952637
4.363527
0.905835
if not self.connected: raise ConnectionError('Queue is not connected') data = self.rdb.brpop(self._name, wait_time) if data: task = Task() task.__dict__ = json.loads(data[1]) return task else: return False
def wait(self, wait_time=0)
Returns a :class:`~retask.task.Task` object from the queue. Returns ``False`` if it timeouts. :arg wait_time: Time in seconds to wait, default is infinite. :return: :class:`~retask.task.Task` object from the queue or False if it timeouts. .. doctest:: >>> from retask import Queue ...
4.461095
3.833769
1.163632
if not self.connected: raise ConnectionError('Queue is not connected') if self.rdb.llen(self._name) == 0: return None data = self.rdb.rpop(self._name) if not data: return None if isinstance(data, six.binary_type): data = ...
def dequeue(self)
Returns a :class:`~retask.task.Task` object from the queue. Returns ``None`` if the queue is empty. :return: :class:`~retask.task.Task` object from the queue If the queue is not connected then it will raise :class:`retask.ConnectionError` .. doctest:: >>> from reta...
3.107714
2.890864
1.075012
if not self.connected: raise ConnectionError('Queue is not connected') try: #We can set the value to the queue job = Job(self.rdb) task.urn = job.urn text = json.dumps(task.__dict__) self.rdb.lpush(self._name, text) ...
def enqueue(self, task)
Enqueues the given :class:`~retask.task.Task` object to the queue and returns a :class:`~retask.queue.Job` object. :arg task: ::class:`~retask.task.Task` object :return: :class:`~retask.queue.Job` object If the queue is not connected then it will raise :class:`retask.Connectio...
7.447336
8.830265
0.843388
self.rdb.lpush(task.urn, json.dumps(result)) self.rdb.expire(task.urn, expire)
def send(self, task, result, expire=60)
Sends the result back to the producer. This should be called if only you want to return the result in async manner. :arg task: ::class:`~retask.task.Task` object :arg result: Result data to be send back. Should be in JSON serializable. :arg expire: Time in seconds after the key expires....
4.427165
5.402049
0.819534
if not self.connected: raise ConnectionError('Queue is not connected') data = self.rdb.lrange(self._name, 0, -1) for i, datum in enumerate(data): if datum.find(str(obj)) != -1: return i return -1
def find(self, obj)
Returns the index of the given object in the queue, it might be string which will be searched inside each task. :arg obj: object we are looking :return: -1 if the object is not found or else the location of the task
4.090138
3.833694
1.066892
if self.__result: return self.__result data = self.rdb.rpop(self.urn) if data: self.rdb.delete(self.urn) data = json.loads(data) self.__result = data return data else: return None
def result(self)
Returns the result from the worker for this job. This is used to pass result in async way.
3.863186
3.468047
1.113937
if self.__result: return True data = self.rdb.brpop(self.urn, wait_time) if data: self.rdb.delete(self.urn) data = json.loads(data[1]) self.__result = data return True else: return False
def wait(self, wait_time=0)
Blocking call to check if the worker returns the result. One can use job.result after this call returns ``True``. :arg wait_time: Time in seconds to wait, default is infinite. :return: `True` or `False`. .. note:: This is a blocking call, you can specity wait_time argumen...
4.161642
4.456478
0.933841
self.prune_sent() if not self.send_queue.empty() or len(self.sent) > 0: return True return False
def messages_in_flight(self)
Returns True if there are messages waiting to be sent or that we're still waiting to see if errors occur for.
6.210162
5.021782
1.236645
if not self.alive: raise ConnectionDeadException() if not self.useable: raise ConnectionDeadException() seq = self._nextSeq() if seq >= PushConnection.MAX_PUSHES_PER_CONNECTION: # IDs are 4 byte so rather than worry about wrapping IDs, just m...
def _reallysend(self, payload, token, expiration=None, priority=None, identifier=None)
Args: payload (dict): The payload dictionary of the push to send descriptor (any): Opaque variable that is passed back to the pushbaby on failure
4.621766
4.676352
0.988327
connection_string = connection_string or self.settings["db"] if not hasattr(self, "_db_conns"): self._db_conns = {} if not connection_string in self._db_conns: self._db_conns[connection_string] = oz.sqlalchemy.session(connection_string=connection_string) ...
def db(self, connection_string=None)
Gets the SQLALchemy session for this request
2.824382
2.496755
1.131221
if hasattr(self, "_db_conns"): try: if self.get_status() >= 200 and self.get_status() <= 399: for db_conn in self._db_conns.values(): db_conn.commit() else: for db_conn in self._db_conns.values(...
def _sqlalchemy_on_finish(self)
Closes the sqlalchemy transaction. Rolls back if an error occurred.
2.461642
2.242163
1.097887
if hasattr(self, "_db_conns"): try: for db_conn in self._db_conns.values(): db_conn.rollback() except: tornado.log.app_log.warning("Error occurred during database transaction cleanup: %s", str(sys.exc_info()[0])) ...
def _sqlalchemy_on_connection_close(self)
Rollsback and closes the active session, since the client disconnected before the request could be completed.
2.797184
2.576263
1.085753
''' Context manager to temporarily override settings ''' from omnic import singletons singletons.settings.use_settings_dict(kwargs) yield singletons.settings.use_previous_settings()
def use_settings(**kwargs)
Context manager to temporarily override settings
10.199197
9.339373
1.092064
"Add ssh key to gitlab if necessary" try: with open(self.args.ssh_public_key) as f: public_key = f.read().strip() except: log.debug("No key found in {}".format(self.args.ssh_public_key)) return None g = self.gitlab url = g['url'...
def add_key(self)
Add ssh key to gitlab if necessary
3.381182
3.100397
1.090564
"Create project in gitlab if it does not exist" g = self.gitlab url = g['url'] + "/projects/" + g['repo'] query = {'private_token': g['token']} if (requests.get(url, params=query).status_code == requests.codes.ok): log.debug("project " + url + " already exists") ...
def add_project(self)
Create project in gitlab if it does not exist
2.956532
2.711565
1.090341
"Unprotect branches of the GitLab project" g = self.gitlab url = g['url'] + "/projects/" + g['repo'] + "/repository/branches" query = {'private_token': g['token']} unprotected = 0 r = requests.get(url, params=query) r.raise_for_status() for branch in r.jso...
def unprotect_branches(self)
Unprotect branches of the GitLab project
2.869493
2.699049
1.06315
"Log the payload that cannot be parsed" try: return json.loads(payload) except ValueError as e: log.error("unable to json.loads(" + payload + ")") raise e
def json_loads(payload)
Log the payload that cannot be parsed
6.745872
4.01723
1.679235
"https://developer.github.com/v3/pulls/#list-pull-requests" g = self.github query = {'state': 'all'} if self.args.github_token: query['access_token'] = g['token'] def f(pull): if self.args.ignore_closed: return (pull['state'] == 'opened' o...
def get_pull_requests(self)
https://developer.github.com/v3/pulls/#list-pull-requests
3.534369
3.357235
1.052762
"http://doc.gitlab.com/ce/api/merge_requests.html" g = self.gitlab merges = self.get(g['url'] + "/projects/" + g['repo'] + "/merge_requests", {'private_token': g['token'], 'state': 'all'}, cache=False) return ...
def get_merge_requests(self)
http://doc.gitlab.com/ce/api/merge_requests.html
5.309724
4.477252
1.185934
dims_out = {} idx = {} yn = slice( np.nonzero(dims['lat'] <= lat.min())[0].max(), np.nonzero(dims['lat'] >= lat.max())[0].min() + 1) dims_out['lat'] = np.atleast_1d(dims['lat'][yn]) idx['yn'] = yn lon_ext = np.array( (dims['lon'] - 2*360).tolist() +...
def cropIndices(dims, lat, lon, depth=None, doy=None)
Return the indices to crop dataset Assuming that the dataset have the dimensions given by dims, this function return the indices to conform with the given coordinates (lat, lon, ...)
2.585706
2.620341
0.986782
if self.Parameters['-1'].isOn(): unassembled_reads1 = self._absolute( str(self.Parameters['-1'].Value)) else: raise ValueError("No reads1 (flag: -1) output path specified") return unassembled_reads1
def _unassembled_reads1_out_file_name(self)
Checks file name is set for reads1 output. Returns absolute path.
7.545206
6.297296
1.198166
if self.Parameters['-2'].isOn(): unassembled_reads2 = self._absolute( str(self.Parameters['-2'].Value)) else: raise ValueError("No reads2 (flag -2) output path specified") return unassembled_reads2
def _unassembled_reads2_out_file_name(self)
Checks if file name is set for reads2 output. Returns absolute path.
7.460478
6.04408
1.234345
if self.Parameters['-3'].isOn(): discarded_reads1 = self._absolute(str(self.Parameters['-3'].Value)) else: raise ValueError( "No discarded-reads1 (flag -3) output path specified") return discarded_reads1
def _discarded_reads1_out_file_name(self)
Checks if file name is set for discarded reads1 output. Returns absolute path.
8.256612
7.121877
1.159331
if self.Parameters['-4'].isOn(): discarded_reads2 = self._absolute(str(self.Parameters['-4'].Value)) else: raise ValueError( "No discarded-reads2 (flag -4) output path specified") return discarded_reads2
def _discarded_reads2_out_file_name(self)
Checks if file name is set for discarded reads2 output. Returns absolute path.
8.277072
7.135963
1.15991
if self.Parameters['-s'].isOn(): assembled_reads = self._absolute(str(self.Parameters['-s'].Value)) else: raise ValueError( "No assembled-reads (flag -s) output path specified") return assembled_reads
def _assembled_out_file_name(self)
Checks file name is set for assembled output. Returns absolute path.
9.543858
8.567381
1.113976
if self.Parameters['-E'].isOn(): pretty_alignment = self._absolute(str(self.Parameters['-E'].Value)) else: raise ValueError( "No pretty-=alignment (flag -E) output path specified") return pretty_alignment
def _pretty_alignment_out_file_name(self)
Checks file name is set for pretty alignment output. Returns absolute path.
14.887969
11.782901
1.263523
result = {} # Always output: result['UnassembledReads1'] = ResultPath(Path= self._unassembled_reads1_out_file_name( ), IsWritten=True) ...
def _get_result_paths(self, data)
Captures SeqPrep output.
2.710992
2.651582
1.022406
files = [] for doc_trans in document.translations.all(): if doc_trans.filer_file is not None and \ doc_trans.filer_file not in files: doc_trans.filer_file.language = doc_trans.language_code files.append(doc_trans.filer_file) return files
def get_files_for_document(document)
Returns the available files for all languages. In case the file is already present in another language, it does not re-add it again.
2.940289
3.059794
0.960943
req = context.get('request') qs = Document.objects.published(req).filter(is_on_front_page=True) return qs
def get_frontpage_documents(context)
Returns the library favs that should be shown on the front page.
5.380025
4.932328
1.090768
c = list(comps) if is_vowel(char): if not c[2]: pos = 1 else: pos = 2 else: if not c[2] and not c[1]: pos = 0 else: pos = 2 c[pos] += char return c
def append_comps(comps, char)
Append a character to `comps` following this rule: a vowel is added to the vowel part if there is no last consonant, else to the last consonant part; a consonant is added to the first consonant part if there is no vowel, and to the last consonant part if the vowel part is not empty. >>> transform(['', ...
3.398259
4.023671
0.844567
def atomic_separate(string, last_chars, last_is_vowel): if string == "" or (last_is_vowel != is_vowel(string[-1])): return (string, last_chars) else: return atomic_separate(string[:-1], string[-1] + last_chars, last_is_vowel) head,...
def separate(string)
Separate a string into smaller parts: first consonant (or head), vowel, last consonant (if any). >>> separate('tuong') ['t','uo','ng'] >>> separate('ohmyfkinggod') ['ohmyfkingg','o','d']
3.148595
3.197527
0.984697
# Check sequence file exists if not exists(seq_path): raise ValueError("%s does not exist" % seq_path) # Instantiate the object swarm = Swarm(HALT_EXEC=HALT_EXEC) # Set the resolution if d > 0: swarm.Parameters['-d'].on(d) else: raise ValueError("Resolution -d...
def swarm_denovo_cluster(seq_path, d=1, threads=1, HALT_EXEC=False)
Function : launch the Swarm de novo OTU picker Parameters: seq_path, filepath to reads d, resolution threads, number of threads to use Return : clusters, list of lists
4.554807
4.350113
1.047055
swarm_breaker_command = ["swarm_breaker.py", "-f", seq_path, "-s", self.Parameters['-o'].Value, "-d", str...
def _swarm_breaker(self, seq_path)
Input : seq_path, a filepath to de-replicated input FASTA reads Method: using swarm_breaker.py, break chains of amplicons based on abundance information. Abundance is stored after the final underscore '_' in...
4.109447
3.908073
1.051528
# creating mapping for de-replicated reads seqs_to_cluster, exact_match_id_map =\ self._prefilter_exact_matches(parse_fasta(seq_path)) # create temporary file for storing the de-replicated reads fd, unique_seqs_fp = mkstemp( prefix='SwarmExactMatchFilter...
def _apply_identical_sequences_prefilter(self, seq_path)
Input : seq_path, a filepath to input FASTA reads Method: prepares and writes de-replicated reads to a temporary FASTA file, calls parent method to do the actual de-replication Return: exact_match_id_map, a dictionary storing ...
3.777708
2.924532
1.291731
results = [] for cluster in clusters: full_cluster = [] for seq_id in cluster: full_cluster += filter_map[seq_id] results.append(full_cluster) return results
def _map_filtered_clusters_to_full_clusters(self, clusters, filter_map)
Input: clusters, a list of cluster lists filter_map, the seq_id in each clusters is the key to the filter_map containing all seq_ids with duplicate FASTA sequences Output: an extended list of...
2.473369
2.195889
1.126363
# Swarm OTU map (mandatory output) return {'OtuMap': ResultPath(Path=self.Parameters['-o'].Value, IsWritten=True)}
def _get_result_paths(self, data)
Set the result paths
40.625908
38.500721
1.055199
return CONNECTION.connect(host=host, port=port, connect=connect, **kwargs)
def connect_to_database(host=None, port=None, connect=False, **kwargs)
Explicitly begins a database connection for the application (if this function is not called, a connection is created when it is first needed). Takes arguments identical to pymongo.MongoClient.__init__ @param host: the hostname to connect to @param port: the port to connect to @param connec...
4.726888
7.500535
0.630207
return CONNECTION.authenticate(username, password, db=db)
def authenticate_connection(username, password, db=None)
Authenticates the current database connection with the passed username and password. If the database connection uses all default parameters, this can be called without connect_to_database. Otherwise, it should be preceded by a connect_to_database call. @param username: the username with which you...
8.852925
24.566906
0.36036
return CONNECTION.add_user(name, password=password, read_only=read_only, db=db, **kwargs)
def add_user(name, password=None, read_only=None, db=None, **kwargs)
Adds a user that can be used for authentication. @param name: the name of the user to create @param passowrd: the password of the user to create. Can not be used with the userSource argument. @param read_only: if True the user will be read only @param db: the database the user is authentica...
3.034574
4.259423
0.712438
return CONNECTION.add_user( name, password=password, roles=["userAdminAnyDatabase", "readWriteAnyDatabase", "root", "backup", "restore"], **kwargs )
def add_superuser(name, password, **kwargs)
Adds a user with userAdminAnyDatabase role to mongo. @param name: the name of the user to create @param passowrd: the password of the user to create. Can not be used with the userSource argument. @param **kwargs: forwarded to pymongo.database.add_user
9.257017
7.9691
1.161614
if db is None: return CONNECTION.get_connection().database_names() return CONNECTION.get_connection()[db].collection_names()
def list_database(db=None)
Lists the names of either the databases on the machine or the collections of a particular database @param db: the database for which to list the collection names; if db is None, then it lists all databases instead the contents of the database with the name passed in db
5.429667
5.98086
0.907841
try: self.__connection = MongoClient(host=host, port=port, connect=connect, **kwargs) except (AutoReconnect, ConnectionFailure, ServerSelectionTimeoutError): raise DatabaseIsDownError("No mongod process is running.")
def connect(self, host=None, port=None, connect=False, **kwargs)
Explicitly creates the MongoClient; this method must be used in order to specify a non-default host or port to the MongoClient. Takes arguments identical to MongoClient.__init__
4.530425
4.139681
1.09439
if db is None: return self.get_connection().admin.authenticate(username, password) return self.get_connection()[db].authenticate(username, password)
def authenticate(self, username, password, db=None)
Authenticates the MongoClient with the passed username and password
3.390102
2.79269
1.21392
if db is None: return self.get_connection().admin.add_user( name, password=password, read_only=read_only, **kwargs) return self.get_connection()[db].add_user( name, password=password, read_only=read_only, **kwargs)
def add_user(self, name, password=None, read_only=None, db=None, **kwargs)
Adds a user that can be used for authentication
2.298922
2.368397
0.970666
''' Function which takes a dictionary (Mapping) object as input and returns return back a metrique object. Special meta property are added to each object:: _oid: ... _start: ... ... FIXME ''' # NOTE: we completely ignore incoming 'id' keys! # id is RESERVED a...
def metrique_object(_oid, _id=None, _hash=None, _start=None, _end=None, _e=None, _v=None, id=None, __v__=None, **kwargs)
Function which takes a dictionary (Mapping) object as input and returns return back a metrique object. Special meta property are added to each object:: _oid: ... _start: ... ... FIXME
7.536533
5.464307
1.37923
''' also possible to define some function that takes current value and creates a new value from it ''' variants = schema.get('variants') obj = {} if variants: for _key, func in variants.iteritems(): _value = func(value, self.store) ...
def _add_variants(self, key, value, schema)
also possible to define some function that takes current value and creates a new value from it
7.24411
3.545289
2.043306
' apply type to all values in the list ' if value is None: # normalize null containers to empty list return [] elif not isinstance(value, list): raise ValueError("expected list type, got: %s" % type(value)) else: return sorted(self._type_si...
def _type_container(self, value, _type)
apply type to all values in the list
5.578816
4.350758
1.282263
' apply type to the single value ' if value is None or _type in (None, NoneType): # don't convert null values # default type is the original type if none set pass elif isinstance(value, _type): # or values already of correct type # normalize all d...
def _type_single(self, value, _type)
apply type to the single value
5.284269
4.966986
1.063878
''' flush objects stored in self.container or those passed in''' batch_size = batch_size or self.config.get('batch_size') # if we're flushing these from self.store, we'll want to # pop them later. if objects: from_store = False else: from_store = T...
def flush(self, objects=None, batch_size=None, **kwargs)
flush objects stored in self.container or those passed in
4.890605
4.636189
1.054876
''' Run a query on the given cube and return only the count of resulting matches. :param query: The query in pql :param date: date (metrique date range) that should be queried If date==None then the most recent versions of the objects will...
def count(self, query=None, date=None)
Run a query on the given cube and return only the count of resulting matches. :param query: The query in pql :param date: date (metrique date range) that should be queried If date==None then the most recent versions of the objects will be queried. ...
11.802224
1.767343
6.677948
''' Build a new index on a cube. Examples: + index('field_name') :param fields: A single field or a list of (key, direction) pairs :param name: (optional) Custom name to use for this index :param collection: cube name :param owner: username of cube o...
def index(self, fields, name=None, **kwargs)
Build a new index on a cube. Examples: + index('field_name') :param fields: A single field or a list of (key, direction) pairs :param name: (optional) Custom name to use for this index :param collection: cube name :param owner: username of cube owner
7.75135
1.892358
4.096133
''' Give cube access rights to another user ''' return self.proxy.share(table=self.name, with_user=with_user, roles=roles)
def share(self, with_user, roles=None)
Give cube access rights to another user
10.323997
5.216326
1.97917
if fasta_path is None: raise ValueError("Error: path to fasta reference " "sequences must exist.") fasta_dir, fasta_filename = split(fasta_path) if not output_dir: output_dir = fasta_dir or '.' # Will cd to this directory, so just pass the filename ...
def build_database_sortmerna(fasta_path, max_pos=None, output_dir=None, temp_dir=tempfile.gettempdir(), HALT_EXEC=False)
Build sortmerna db from fasta_path; return db name and list of files created Parameters ---------- fasta_path : string path to fasta file of sequences to build database. max_pos : integer, optional maximum positions to store per seed in index ...
5.725166
5.052714
1.133087
# Instantiate the object smr = Sortmerna(HALT_EXEC=HALT_EXEC) # Set input query sequences path if seq_path is not None: smr.Parameters['--reads'].on(seq_path) else: raise ValueError("Error: a read file is mandatory input.") # Set the input reference sequence + indexed dat...
def sortmerna_ref_cluster(seq_path=None, sortmerna_db=None, refseqs_fp=None, result_path=None, tabular=False, max_e_value=1, similarity=0.97, ...
Launch sortmerna OTU picker Parameters ---------- seq_path : str filepath to query sequences. sortmerna_db : str indexed reference database. refseqs_fp : str filepath of reference sequences. result_path : str filepath to ou...
4.236089
3.973178
1.066171
if not (blast_format or output_sam): raise ValueError("Either Blast or SAM output alignment " "format must be chosen.") if (best and num_alignments): raise ValueError("Only one of --best or --num_alignments " "options must be chosen.") ...
def sortmerna_map(seq_path, output_dir, refseqs_fp, sortmerna_db, e_value=1, threads=1, best=None, num_alignments=None, HALT_EXEC=False, output_sam=False, ...
Launch sortmerna mapper Parameters ---------- seq_path : str filepath to reads. output_dir : str dirpath to sortmerna output. refseqs_fp : str filepath of reference sequences. sortmerna_db : str indexed reference database. ...
3.373127
2.926519
1.152607
# get the filepath of the indexed database (after comma) # /path/to/refseqs.fasta,/path/to/refseqs.idx # ^------------------^ db_name = (self.Parameters['--ref'].Value).split(',')[1] result = {} extensions = ['bursttrie', 'kmer', 'pos', 's...
def _get_result_paths(self, data)
Build the dict of result filepaths
7.896637
7.465699
1.057722
result = {} # get the file extension of the reads file (sortmerna # internally outputs all results with this extension) fileExtension = splitext(self.Parameters['--reads'].Value)[1] # at this point the parameter --aligned should be set as # sortmerna will not ...
def _get_result_paths(self, data)
Set the result paths
3.771643
3.701636
1.018912
''' Returns a color to use. :param integer/string color: Color for the plot. Can be an index for the color from COLORS or a key(string) from CNAMES. ''' if color is None: color = self.counter if isinstance(color, str): colo...
def get_color(self, color)
Returns a color to use. :param integer/string color: Color for the plot. Can be an index for the color from COLORS or a key(string) from CNAMES.
6.849884
2.348744
2.916403
''' Wrapper around plot. :param pandas.Series series: The series to be plotted, all values must be positive if stacked is True. :param string label: The label for the series. :param integer/string color: Color for the plot. Can be ...
def plot(self, series, label='', color=None, style=None)
Wrapper around plot. :param pandas.Series series: The series to be plotted, all values must be positive if stacked is True. :param string label: The label for the series. :param integer/string color: Color for the plot. Can be an index for the col...
4.702775
2.12135
2.216879
''' Plots all the series from the list. The assumption is that all of the series share the same index. :param list series_list: A list of series which should be plotted :param list label_list: A list of labels corresponding to the series :params l...
def plots(self, series_list, label_list, colors=None)
Plots all the series from the list. The assumption is that all of the series share the same index. :param list series_list: A list of series which should be plotted :param list label_list: A list of labels corresponding to the series :params list list_of_colors: ...
3.161713
1.554561
2.03383
''' Creates a vertical line in the plot. :param x: The x coordinate of the line. Should be in the same units as the x-axis. :param string label: The label to be displayed. :param y: May be 'top', 'bottom' or int. The y ...
def line(self, x, label=None, y='bottom', color='grey', ax=None, **kwargs)
Creates a vertical line in the plot. :param x: The x coordinate of the line. Should be in the same units as the x-axis. :param string label: The label to be displayed. :param y: May be 'top', 'bottom' or int. The y coordinate of the te...
2.874061
1.836352
1.565093
''' Creates vertical lines in the plot. :param lines_dict: A dictionary of label, x-coordinate pairs. :param y: May be 'top', 'bottom' or int. The y coordinate of the text-labels. :param color color: The color of the lines. ...
def lines(self, lines_dict, y='bottom', color='grey', **kwargs)
Creates vertical lines in the plot. :param lines_dict: A dictionary of label, x-coordinate pairs. :param y: May be 'top', 'bottom' or int. The y coordinate of the text-labels. :param color color: The color of the lines.
4.361478
1.662677
2.623166
''' :param pandas.Series series: The series to be plotted, all values must be positive if stacked is True. :param pandas.Series series_diff: The series representing the diff that will be plotted in the bottom part. :param string label: ...
def plot(self, series, series_diff=None, label='', color=None, style=None)
:param pandas.Series series: The series to be plotted, all values must be positive if stacked is True. :param pandas.Series series_diff: The series representing the diff that will be plotted in the bottom part. :param string label: The label fo...
3.542131
1.905188
1.859202
''' Creates a vertical line in the plot. :param x: The x coordinate of the line. Should be in the same units as the x-axis. :param string label: The label to be displayed. :param y: May be 'top', 'bottom' or int. The y ...
def line(self, x, label=None, y='bottom', color='grey', **kwargs)
Creates a vertical line in the plot. :param x: The x coordinate of the line. Should be in the same units as the x-axis. :param string label: The label to be displayed. :param y: May be 'top', 'bottom' or int. The y coordinate of the te...
3.881948
1.865259
2.081185
language = getattr(request, 'LANGUAGE_CODE', get_language()) if not language: return self.model.objects.none() qs = self.get_queryset() qs = qs.filter( translations__is_published=True, translations__language_code=language, ) #...
def published(self, request=None)
Returns the published documents in the current language. :param request: A Request instance.
3.340371
3.605781
0.926393
self.log.debug("Formatting URLs to request") items = list() for i in range(0, self.limit, 10): query = '"%s" %s' % (self.domain, self.modifier) url = self.host + "/search?q=" + query + "&first=" + str(i) items.append(url) self.log.debug("URLs ...
def _format(self)
Format search queries to perform in bulk. Build up the URLs to call for the search engine. These will be ran through a bulk processor and returned to a detailer.
5.06207
4.594957
1.101658
self.log.debug("Processing search results") items = list() for response in responses: try: soup = BeautifulSoup(response.content, 'html.parser', from_encoding="iso-8859-1") except: continue ...
def _process(self, responses)
Process search engine results for detailed analysis. Search engine result pages (SERPs) come back with each request and will need to be extracted in order to crawl the actual hits.
3.636135
3.327979
1.092596
responses = self._request_bulk(urls) for response in responses: try: soup = BeautifulSoup(response.content, 'html.parser', from_encoding="iso-8859-1") text = soup.get_text() except Exception: ...
def _fetch(self, urls)
Perform bulk collection of data and return the content. Gathering responses is handled by the base class and uses futures to speed up the processing. Response data is saved inside a local variable to be used later in extraction.
4.709848
4.281441
1.100061
self.log.debug("Extracting emails from text content") for item in self.data: emails = extract_emails(item, self.domain, self.fuzzy) self.results.extend(emails) self.log.debug("Email extraction completed") return list(set(self.results))
def _extract(self)
Extract email addresses from results. Text content from all crawled pages are ran through a simple email extractor. Data is cleaned prior to running pattern expressions.
5.052043
4.278845
1.180703
requests = self._format() serps = self._fetch(requests) urls = self._process(serps) details = self._fetch(urls) emails = self._extract() return {'emails': emails, 'processed': len(self.data)}
def search(self)
Run the full search process. Simple public method to abstract the steps needed to produce a full search using the engine.
10.12967
9.308702
1.088194
exec_fp = None if env_var in os.environ: paths = os.environ[env_var] for path in paths.split(os.pathsep): curr_exec_fp = os.path.join(path, executable_name) if os.access(curr_exec_fp, os.X_OK): exec_fp = curr_exec_fp break retu...
def which(executable_name, env_var='PATH')
Equivalent to ``which executable_name`` in a *nix environment. Will return ``None`` if ``executable_name`` cannot be found in ``env_var`` or if ``env_var`` is not set. Otherwise will return the first match in ``env_var``. Note: this function will likely not work on Windows. Code taken and modifie...
1.960372
2.236457
0.876553
# Make sure we have input(s) and output if not PathsToInputs: raise ValueError("No input file(s) specified.") if not PathToOutput: raise ValueError("No output file specified.") if not isinstance(PathsToInputs, list): PathsToInputs = [PathsToInputs] # PathToBin and Path...
def cmdline_generator(param_iter, PathToBin=None, PathToCmd=None, PathsToInputs=None, PathToOutput=None, PathToStderr='/dev/null', PathToStdout='/dev/null', UniqueOutputs=False, InputParam=None, OutputParam=None)
Generates command lines that can be used in a cluster environment param_iter : ParameterIterBase subclass instance PathToBin : Absolute location primary command (i.e. Python) PathToCmd : Absolute location of the command PathsToInputs : Absolute location(s) of input file(s) PathToOutput : Absolute l...
2.606588
2.591645
1.005766
# check not none if not tmp_dir: tmp_dir = "" # if not current directory, append "/" if not already on path elif not tmp_dir.endswith("/"): tmp_dir += "/" chars = "abcdefghigklmnopqrstuvwxyz" picks = chars + chars.upper() + "0123456790" return result_constructor(tmp_dir...
def get_tmp_filename(tmp_dir=gettempdir(), prefix="tmp", suffix=".txt", result_constructor=FilePath)
Generate a temporary filename and return as a FilePath object tmp_dir: the directory to house the tmp_filename prefix: string to append to beginning of filename Note: It is very useful to have prefix be descriptive of the process which is creating the temporary file. For example...
5.022237
5.235968
0.95918
if isinstance(seqs, str): if '\n' in seqs: # can't be a filename... return '_input_as_multiline_string' else: # assume it was a filename return '_input_as_string' if isinstance(seqs, list) and len(seqs) and isinstance(seqs[0], tuple): return '_input_as_seq...
def guess_input_handler(seqs, add_seq_names=False)
Returns the name of the input handler for seqs.
3.802835
3.622051
1.049912
file_keys = self.file_keys for item in file_keys: if self[item] is not None: self[item].close() remove(self[item].name) # remove input handler temp files if hasattr(self, "_input_filename"): remove(self._input_filename)
def cleanUp(self)
Delete files that are written by CommandLineApplication from disk WARNING: after cleanUp() you may still have access to part of your result data, but you should be aware that if the file size exceeds the size of the buffer you will only have part of the file....
5.181102
4.829241
1.072861
filename = self._input_filename = \ FilePath(self.getTmpFilename(self.TmpDir)) data_file = open(filename, 'w') data_file.write(data) data_file.close() return filename
def _input_as_multiline_string(self, data)
Write a multiline string to a temp file and return the filename. data: a multiline string to be written to a file. * Note: the result will be the filename as a FilePath object (which is a string subclass).
5.253519
4.508249
1.165313
filename = self._input_filename = \ FilePath(self.getTmpFilename(self.TmpDir)) filename = FilePath(filename) data_file = open(filename, 'w') data_to_file = '\n'.join([str(d).strip('\n') for d in data]) data_file.write(data_to_file) data_file.close() ...
def _input_as_lines(self, data)
Write a seq of lines to a temp file and return the filename string data: a sequence to be written to a file, each element of the sequence will compose a line in the file * Note: the result will be the filename as a FilePath object (which is a string subclass). ...
4.412647
3.881009
1.136985
return self._command_delimiter.join( map(str, map(self._input_as_path, data)))
def _input_as_paths(self, data)
Return data as a space delimited string with each path quoted data: paths or filenames, most likely as a list of strings
7.971268
8.191476
0.973117
path = FilePath(path) if isabs(path): return path else: # these are both Path objects, so joining with + is acceptable return self.WorkingDir + path
def _absolute(self, path)
Convert a filename to an absolute path
11.993939
11.131772
1.077451
command_parts = [] # Append a change directory to the beginning of the command to change # to self.WorkingDir before running the command # WorkingDir should be in quotes -- filenames might contain spaces cd_command = ''.join(['cd ', str(self.WorkingDir), ';']) if...
def _get_base_command(self)
Returns the full command string input_arg: the argument to the command which represents the input to the program, this will be a string, either representing input or a filename to get input from tI
5.641953
5.821498
0.969158
command = self._command # strip off " characters, in case we got a FilePath object found_in_path = which(command.strip('"')) is not None if not (exists(command) or found_in_path): raise ApplicationNotFoundError("Cannot find %s. Is it installed? " ...
def _error_on_missing_application(self, params)
Raise an ApplicationNotFoundError if the app is not accessible This method checks in the system path (usually $PATH) or for the existence of self._command. If self._command is not found in either place, an ApplicationNotFoundError is raised to inform the user that the ap...
9.626745
8.495445
1.133165
# check not none if not tmp_dir: tmp_dir = self.TmpDir # if not current directory, append "/" if not already on path elif not tmp_dir.endswith("/"): tmp_dir += "/" if include_class_id: # Append the classname to the prefix from the cl...
def getTmpFilename(self, tmp_dir=None, prefix='tmp', suffix='.txt', include_class_id=False, result_constructor=FilePath)
Return a temp filename tmp_dir: directory where temporary files will be stored prefix: text to append to start of file name suffix: text to append to end of file name include_class_id: if True, will append a class identifier (built from the class name) to th...
5.910802
5.178873
1.14133
"Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..." for category in orm['document_library.DocumentCategory'].objects.all(): category.slug = category.documentcategorytitle_set.all()[0].title.lower() cate...
def forwards(self, orm)
Write your forwards methods here.
6.682199
5.456148
1.22471
index = utils.VOWELS.find(char.lower()) if (index != -1): return 5 - index % 6 else: return Accent.NONE
def get_accent_char(char)
Get the accent of an single char, if any.
7.319594
6.827039
1.072148