code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
q = self.session.query(models.Pathway)
if pathway_name:
q = q.filter(models.Pathway.pathway_name.like(pathway_name))
if pathway_id:
q = q.filter(models.Pathway.pathway_id.like(pathway_id))
return self._limit_and_df(q, limit, as_df) | def get_pathway(self, pathway_name=None, pathway_id=None, limit=None, as_df=False) | Get pathway
.. note::
Format of pathway_id is KEGG:X* or REACTOME:X* . X* stands for a sequence of digits
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param str pathway_name: pathway name
:param str pathway_id: KEGG or REACTOME identifier
... | 1.98511 | 2.230614 | 0.889939 |
q = self.session.query(models.Chemical)
if chemical_name:
q = q.filter(models.Chemical.chemical_name.like(chemical_name))
if chemical_id:
q = q.filter(models.Chemical.chemical_id == chemical_id)
if cas_rn:
q = q.filter(models.Chemical.cas_r... | def get_chemical(self, chemical_name=None, chemical_id=None, cas_rn=None, drugbank_id=None, parent_id=None,
parent_tree_number=None, tree_number=None, synonym=None, limit=None, as_df=False) | Get chemical
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param str chemical_name: chemical name
:param str chemical_id: cehmical identifier
:param str cas_rn: CAS registry number
:param str drugbank_id: DrugBank identifier
:param str parent_... | 1.463006 | 1.5003 | 0.975142 |
q = self.session.query(models.ChemGeneIxn)
if organism_id:
q = q.filter(models.ChemGeneIxn.organism_id == organism_id)
if interaction_sentence:
q = q.filter(models.ChemGeneIxn.interaction == interaction_sentence)
if gene_form:
q = q.join(mo... | def get_chem_gene_interaction_actions(self, gene_name=None, gene_symbol=None, gene_id=None, limit=None,
cas_rn=None, chemical_id=None, chemical_name=None, organism_id=None,
interaction_sentence=None, chemical_definition=None,
... | Get all interactions for chemicals on a gene or biological entity (linked to this gene).
Chemicals can interact on different types of biological entities linked to a gene. A list of allowed
entities linked to a gene can be retrieved via the attribute :attr:`~.gene_forms`.
Interactions are clas... | 1.766731 | 1.709783 | 1.033307 |
q = self.session.query(distinct(models.ChemGeneIxnGeneForm.gene_form))
return [x[0] for x in q.all()] | def gene_forms(self) | :return: List of strings for all available gene forms
:rtype: list[str] | 8.79165 | 7.386545 | 1.190225 |
r = self.session.query(distinct(models.ChemGeneIxnInteractionAction.interaction_action)).all()
return [x[0] for x in r] | def interaction_actions(self) | :return: List of strings for allowed interaction/actions combinations
:rtype: list[str] | 11.755912 | 10.182858 | 1.154481 |
r = self.session.query(models.Action).all()
return [x.type_name for x in r] | def actions(self) | Gets the list of allowed actions
:rtype: list[str] | 6.934675 | 6.464103 | 1.072798 |
q = self.session.query(models.GeneDisease)
if direct_evidence:
q = q.filter(models.GeneDisease.direct_evidence == direct_evidence)
if inference_chemical_name:
q = q.filter(models.GeneDisease.inference_chemical_name == inference_chemical_name)
if infere... | def get_gene_disease(self, direct_evidence=None, inference_chemical_name=None, inference_score=None,
gene_name=None, gene_symbol=None, gene_id=None, disease_name=None, disease_id=None,
disease_definition=None, limit=None, as_df=False) | Get gene–disease associations
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param int gene_id: gene identifier
:param str gene_symbol: gene symbol
:param str gene_name: gene name
:param str direct_evidence: direct evidence
:param str inference_... | 1.651142 | 1.754263 | 0.941217 |
q = self.session.query(distinct(models.GeneDisease.direct_evidence))
return q.all() | def direct_evidences(self) | :return: All available direct evidences for gene disease correlations
:rtype: list | 10.173027 | 7.048229 | 1.443345 |
q = self.session.query(models.DiseasePathway)
q = self._join_disease(query=q, disease_id=disease_id, disease_name=disease_name,
disease_definition=disease_definition)
q = self._join_pathway(query=q, pathway_id=pathway_id, pathway_name=pathway_name)
... | def get_disease_pathways(self, disease_id=None, disease_name=None, pathway_id=None, pathway_name=None,
disease_definition=None, limit=None, as_df=False) | Get disease pathway link
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param disease_id:
:param disease_name:
:param pathway_id:
:param pathway_name:
:param disease_definition:
:param int limit: maximum number of results
... | 2.077389 | 2.192846 | 0.947348 |
q = self.session.query(models.ChemicalDisease)
if direct_evidence:
q = q.filter(models.ChemicalDisease.direct_evidence.like(direct_evidence))
if inference_gene_symbol:
q = q.filter(models.ChemicalDisease.inference_gene_symbol.like(inference_gene_symbol))
... | def get_chemical_diseases(self, direct_evidence=None, inference_gene_symbol=None, inference_score=None,
inference_score_operator=None, cas_rn=None, chemical_name=None,
chemical_id=None, chemical_definition=None, disease_definition=None,
... | Get chemical–disease associations with inference gene
:param direct_evidence: direct evidence
:param inference_gene_symbol: inference gene symbol
:param inference_score: inference score
:param inference_score_operator: inference score operator
:param cas_rn:
:par... | 1.60423 | 1.663324 | 0.964472 |
q = self.session.query(models.GenePathway)
q = self._join_gene(q, gene_name=gene_name, gene_symbol=gene_symbol, gene_id=gene_id)
q = self._join_pathway(q, pathway_id=pathway_id, pathway_name=pathway_name)
return self._limit_and_df(q, limit, as_df) | def get_gene_pathways(self, gene_name=None, gene_symbol=None, gene_id=None, pathway_id=None,
pathway_name=None, limit=None, as_df=False) | Get gene pathway link
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param str gene_name: gene name
:param str gene_symbol: gene symbol
:param int gene_id: NCBI Gene identifier
:param pathway_id:
:param str pathway_name: pathway name
... | 2.034352 | 2.262914 | 0.898997 |
kwargs = {
'storage': self.get_storage(),
'upload_to': self.get_upload_to(),
'content_type_prefix': self.get_content_type_prefix(),
'process_to': self.get_process_to(),
'processed_key_generator': self.get_processed_key_generator(),
}
... | def get_validate_upload_form_kwargs(self) | Return the keyword arguments for instantiating the form for validating
the upload. | 4.747425 | 4.617913 | 1.028046 |
filename = None
if state == SoundService.State.welcome:
filename = "pad_glow_welcome1.wav"
elif state == SoundService.State.goodbye:
filename = "pad_glow_power_off.wav"
elif state == SoundService.State.hotword_detected:
filename = "pad_soft_on... | def play(state) | Play sound for a given state.
:param state: a State value. | 4.753806 | 4.93678 | 0.962937 |
pandoc = None
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
pandoc = os.path.join(path, 'pandoc')
if os.path.isfile(pandoc) and os.access(pandoc, os.X_OK):
break
else:
pandoc = None
try:
if pandoc:
cm... | def get_readme() | Generate long description | 2.11454 | 2.029251 | 1.04203 |
lic = (
'License :: OSI Approved :: GNU Affero '
'General Public License v3 or later (AGPLv3+)')
version = load_source("version", os.path.join("spamc", "version.py"))
opts = dict(
name="spamc",
version=version.__version__,
description="Python spamassassin spamc ... | def main() | Main | 3.185572 | 3.198864 | 0.995845 |
now = datetime.datetime.utcnow()
mdate = meeting['meeting_date']
mtime = meeting['meeting_time_start']
dt_string = "%s %s" % (mdate, mtime)
meeting_dt = datetime.datetime.strptime(dt_string, "%Y-%m-%d %H:%M:%S")
relative_td = dateutil.relativedelta.relativedelta(meeting_dt, now)
denom... | def _casual_timedelta_string(meeting) | Return a casual timedelta string.
If a meeting starts in 2 hours, 15 minutes, and 32 seconds from now, then
return just "in 2 hours".
If a meeting starts in 7 minutes and 40 seconds from now, return just "in 7
minutes".
If a meeting starts 56 seconds from now, just return "right now". | 2.709089 | 2.583155 | 1.048752 |
try:
# git messages look like this now
path = msg['msg']['commit']['path']
project = path.split('.git')[0][9:]
except KeyError:
# they used to look like this, though
project = msg['msg']['commit']['repo']
return project | def repo_name(msg) | Compat util to get the repo name from a message. | 10.375498 | 9.942497 | 1.04355 |
params = {}
if period:
params['period'] = period
if start:
params['start'] = start
if end:
params['end'] = end
return self.request.get('usage', params) | def usage(self, period=None, start=None, end=None) | Get account usage information
:param period: Period is one of either hourly, daily or monthly
:type period: str
:param start: Determines time period of the usage
:type start: int
:param end: Determines time period of the usage
:type end: int
... | 2.592653 | 2.543163 | 1.01946 |
found = id_re.findall(file_column_name)
if not found:
return file_column_name
return '_'.join(x[0].lower() for x in found) | def standard_db_name(file_column_name) | return a standard name by following rules:
1. find all regular expression partners ((IDs)|(ID)|([A-Z][a-z]+)|([A-Z]{2,}))
2. lower very part and join again with _
This method is only used if values in table[model]['columns'] are str
:param str file_column_name: name of column in file
:return: stand... | 4.598549 | 3.934147 | 1.168881 |
if isinstance(input_txt, str):
text = u"{}".format(input_txt)
elif isinstance(input_txt, bytes):
text = input_txt.decode("utf-8")
else:
raise TypeError("Expecting <class 'str'> or <class 'bytes'>, but {} was passed".format(type(input_txt)))
inputq = deque(text.split(u"\n"))... | def transform_text(input_txt) | Transforms text into :py:class:`~collections.deque`, pre-processes
multiline strings.
:param str or bytes input_txt: Input text.
:return: Double-ended queue of single characters and multiline strings.
:rtype: :py:class:`~collections.deque` | 2.356419 | 2.266088 | 1.039862 |
stream = transform_text(text)
wordchars = (u"abcdfeghijklmnopqrstuvwxyz"
u"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"
u"ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ"
u"ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ"
u"!@$%^&*()_+:;?/>.<,~`|\{[}]-=")
whitespace = u"... | def bmrblex(text) | A lexical analyzer for the BMRB NMR-STAR format syntax.
:param text: Input text.
:type text: :py:class:`str` or :py:class:`bytes`
:return: Current token.
:rtype: :py:class:`str` | 2.662833 | 2.66775 | 0.998157 |
available = []
try:
shell('ebook-convert')
available.append('calibre')
except OSError:
pass
try:
shell('pandoc --help')
available.append('pandoc')
except OSError:
pass
if not available:
sys.exit(error('No generator found, you cannot us... | def check_dependencies() | Check external dependecies
Return a tuple with the available generators. | 5.899806 | 5.119491 | 1.15242 |
expire = datetime.utcnow() + timedelta(seconds=expire) if expire else None
try:
self.collection.insert({
'_id': key,
'locked': True,
'owner': owner,
'created': datetime.utcnow(),
'expire': expire
... | def lock(self, key, owner, timeout=None, expire=None) | Lock given `key` to `owner`.
:Parameters:
- `key` - lock name
- `owner` - name of application/component/whatever which asks for lock
- `timeout` (optional) - how long to wait if `key` is locked
- `expire` (optional) - when given, lock will be released after that number o... | 2.686043 | 2.848049 | 0.943117 |
status = self.collection.find_and_modify(
{'_id': key, 'owner': owner},
{'locked': False, 'owner': None, 'created': None, 'expire': None}
) | def release(self, key, owner) | Release lock with given name.
`key` - lock name
`owner` - name of application/component/whatever which held a lock
Raises `MongoLockException` if no such a lock. | 4.540275 | 4.169192 | 1.089006 |
lock = self.collection.find_one({'_id': key, 'owner': owner})
if not lock:
raise MongoLockException(u'Can\'t find lock for {key}: {owner}'.format(key=key, owner=owner))
if not lock['expire']:
return
if not expire:
raise MongoLockException(u'Ca... | def touch(self, key, owner, expire=None) | Renew lock to avoid expiration. | 2.496391 | 2.404428 | 1.038247 |
'''
Return full document for ``{_id:'archive_name'}``
.. note::
MongoDB specific results - do not expose to user
'''
res = self.collection.find_one({'_id': archive_name})
if res is None:
raise KeyError
return res | def _get_archive_listing(self, archive_name) | Return full document for ``{_id:'archive_name'}``
.. note::
MongoDB specific results - do not expose to user | 11.705024 | 2.536746 | 4.614188 |
'''
Batched version of :py:meth:`~MongoDBManager._get_archive_listing`
Returns a list of full archive listings from an iterable of archive
names
.. note ::
Invalid archive names will simply not be returned, so the response
may not be the same length as ... | def _batch_get_archive_listing(self, archive_names) | Batched version of :py:meth:`~MongoDBManager._get_archive_listing`
Returns a list of full archive listings from an iterable of archive
names
.. note ::
Invalid archive names will simply not be returned, so the response
may not be the same length as the supplied `archiv... | 5.068598 | 1.768965 | 2.86529 |
if async:
response.process = lambda: self.build_response(response.result(), path=path, parser=parser, async=False)
return response
if response.status_code != 204:
try:
data = parser(response.headers, response.text)
except ValueErro... | def build_response(self, response, path=None, parser=json_decode_wrapper, async=False) | Builds a List or Dict response object.
Wrapper for a response from the DataSift REST API, can be accessed as a list.
:param response: HTTP response to wrap
:type response: :class:`~datasift.requests.DictResponse`
:param parser: optional parser to overload how the data i... | 2.948163 | 2.690021 | 1.095963 |
# can't use a dict comprehension because we want python2.6 support
r = {}
keys = filter(lambda x: x.startswith("x-ratelimit-"), self.headers.keys())
for key in keys:
r[key.replace("x-ratelimit-", "")] = int(self.headers[key])
return r | def ratelimits(self) | :returns: Rate Limit headers
:rtype: dict | 3.303857 | 3.270756 | 1.01012 |
# Compute required # of IO expanders needed, clear mask variable.
number_IO_expanders = ((len(cls._list) - 1) / 4) + 1
cls.master_mask = [0, 0] * number_IO_expanders
for ctrlobj in cls:
# Or masks together bank-by-banl
cls.master_mask[ctrlobj.bank] |= ct... | def compile_instance_masks(cls) | Compiles instance masks into a master mask that is usable by
the IO expander. Also determines whether or not the pump
should be on.
Method is generalized to support multiple IO expanders
for possible future expansion. | 10.442822 | 8.301379 | 1.257962 |
ControlCluster.compile_instance_masks()
IO_expander_output(
ControlCluster.bus, self.IOexpander,
self.bank,
ControlCluster.master_mask[self.bank])
if self.bank != ControlCluster.pump_bank:
IO_expander_output(
ControlClust... | def update(self) | This method exposes a more simple interface to the IO module
Regardless of what the control instance contains, this method
will transmit the queued IO commands to the IO expander
Usage: plant1Control.update(bus) | 7.004296 | 5.882784 | 1.190643 |
# Compute bank/pins/IOexpander address based on ID
if self.ID == 1:
self.IOexpander = 0x20
self.bank = 0
self.fan = 2
self.light = 3
self.valve = 4
elif self.ID == 2:
self.IOexpander = 0x20
self.bank = 0... | def form_GPIO_map(self) | This method creates a dictionary to map plant IDs to
GPIO pins are associated in triples.
Each ID gets a light, a fan, and a mist nozzle. | 2.954977 | 2.938374 | 1.00565 |
if operation == "on":
self.controls["pump"] = "on"
elif operation == "off":
self.controls["pump"] = "off"
return True | def manage_pump(self, operation) | Updates control module knowledge of pump requests.
If any sensor module requests water, the pump will turn on. | 3.249399 | 3.003637 | 1.081822 |
controls = {"light", "valve", "fan", "pump"}
def cast_arg(arg):
if type(arg) is str:
if arg == "all":
return controls
else:
return {arg} & controls
else:
return set(arg) & controls
... | def control(self, on=[], off=[]) | This method serves as the primary interaction point
to the controls interface.
- The 'on' and 'off' arguments can either be a list or a single string.
This allows for both individual device control and batch controls.
Note:
Both the onlist and offlist are optional.
... | 5.039536 | 5.559958 | 0.906398 |
current_mask = get_IO_reg(ControlCluster.bus,
self.IOexpander,
self.bank)
if current_mask & (1 << ControlCluster.pump_pin):
self.manage_pump("on")
if current_mask & (1 << self.fan):
self.manage_fa... | def restore_state(self) | Method should be called on obj. initialization
When called, the method will attempt to restore
IO expander and RPi coherence and restore
local knowledge across a possible power failure | 7.939059 | 6.350856 | 1.250077 |
'''
Returns a Datastore key object, prefixed with the NAMESPACE.
'''
if not isinstance(key, datastore.Key):
# Switchboard uses ':' to denote one thing (parent-child) and datastore
# uses it for another, so replace ':' in the datastore version of the
# key.
safe_key = key.... | def _key(key='') | Returns a Datastore key object, prefixed with the NAMESPACE. | 10.029082 | 6.77414 | 1.480495 |
'''
A port of functionality from the Django ORM. Defaults can be passed in
if creating a new document is necessary. Keyword args are used to
lookup the document. Returns a tuple of (object, created), where object
is the retrieved or created object and created is a boolean specify... | def get_or_create(cls, key, defaults={}) | A port of functionality from the Django ORM. Defaults can be passed in
if creating a new document is necessary. Keyword args are used to
lookup the document. Returns a tuple of (object, created), where object
is the retrieved or created object and created is a boolean specifying
whether ... | 5.611318 | 2.798773 | 2.00492 |
'''
The spec is used to search for the data to update, updates contains the
values to be updated, and upsert specifies whether to do an insert if
the original data is not found.
'''
if 'key' in spec:
previous = cls.get(spec['key'])
else:
pr... | def update(cls, spec, updates, upsert=False) | The spec is used to search for the data to update, updates contains the
values to be updated, and upsert specifies whether to do an insert if
the original data is not found. | 4.609944 | 3.071892 | 1.500686 |
'''
This is a hack because some datastore implementations don't support
querying. Right now the solution is to drop down to the underlying
native client and query all, which means that this section is ugly.
If it were architected properly, you might be able to do something
... | def _queryless_all(cls) | This is a hack because some datastore implementations don't support
querying. Right now the solution is to drop down to the underlying
native client and query all, which means that this section is ugly.
If it were architected properly, you might be able to do something
like inject an imp... | 10.830607 | 1.87985 | 5.76142 |
condition_set = manager.get_condition_set_by_id(condition_set)
namespace = condition_set.get_namespace()
if namespace not in self.value:
return
if field_name not in self.value[namespace]:
return
conditions = self.value[namespace][field_name]
... | def remove_condition(self, manager, condition_set, field_name, condition,
commit=True) | Removes a condition and updates the global ``operator`` switch manager.
If ``commit`` is ``False``, the data will not be written to the
database.
>>> switch = operator['my_switch'] #doctest: +SKIP
>>> cs_id = condition_set.get_id() #doctest: +SKIP
>>> switch.remove_condition(cs... | 2.086016 | 2.542593 | 0.820428 |
'''
Returns a generator which yields groups of lists of conditions.
>>> conditions = switch.get_active_conditions()
>>> for label, set_id, field, value, exc in conditions: #doctest: +SKIP
>>> print ("%(label)s: %(field)s = %(value)s (exclude: %(exc)s)"
>>> ... | def get_active_conditions(self, manager) | Returns a generator which yields groups of lists of conditions.
>>> conditions = switch.get_active_conditions()
>>> for label, set_id, field, value, exc in conditions: #doctest: +SKIP
>>> print ("%(label)s: %(field)s = %(value)s (exclude: %(exc)s)"
>>> % (label, field.lab... | 3.922876 | 2.096002 | 1.871599 |
parser = optparse.OptionParser()
parser.add_option(
'-s', '--server', help='Index Server Name', metavar='SERVER')
parser.add_option(
'-r', '--repository', help='Repository URL', metavar='URL')
parser.add_option(
'-u', '--username', help='User Name', metavar='USERNAME')
p... | def main() | Main loop. | 2.245362 | 2.254273 | 0.996047 |
return self.request.post('validate',
dict(output_type=output_type, output_params=output_params)) | def validate(self, output_type, output_params) | Check that a subscription is defined correctly.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushvalidate
:param output_type: One of DataSift's supported output types, e.g. s3
:type output_type: str
:param output_params: The set of parame... | 5.16885 | 5.124223 | 1.008709 |
return self._create(True, stream, name, output_type, output_params, initial_status, start, end) | def create_from_hash(self, stream, name, output_type, output_params,
initial_status=None, start=None, end=None) | Create a new push subscription using a live stream.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushcreate
:param stream: The hash of a DataSift stream.
:type stream: str
:param name: The name to give the newly created subscription
... | 3.210751 | 4.289889 | 0.748446 |
return self._create(False, historics_id, name, output_type, output_params, initial_status, start, end) | def create_from_historics(self, historics_id, name, output_type, output_params, initial_status=None, start=None,
end=None) | Create a new push subscription using the given Historic ID.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushcreate
:param historics_id: The ID of a Historics query
:type historics_id: str
:param name: The name to give the newly created sub... | 2.636155 | 3.48723 | 0.755945 |
return self.request.post('pause', data=dict(id=subscription_id)) | def pause(self, subscription_id) | Pause a Subscription and buffer the data for up to one hour.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushpause
:param subscription_id: id of an existing Push Subscription.
:type subscription_id: str
:returns: dict with extra response d... | 8.013116 | 12.971067 | 0.617768 |
return self.request.post('resume', data=dict(id=subscription_id)) | def resume(self, subscription_id) | Resume a previously paused Subscription.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushresume
:param subscription_id: id of an existing Push Subscription.
:type subscription_id: str
:returns: dict with extra response data
:rt... | 8.596774 | 14.200253 | 0.605396 |
params = {'id': subscription_id, 'output_params': output_params}
if name:
params['name'] = name
return self.request.post('update', params) | def update(self, subscription_id, output_params, name=None) | Update the name or output parameters for an existing Subscription.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushupdate
:param subscription_id: id of an existing Push Subscription.
:type subscription_id: str
:param output_params: new out... | 2.950784 | 3.427737 | 0.860855 |
return self.request.post('stop', data=dict(id=subscription_id)) | def stop(self, subscription_id) | Stop the given subscription from running.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushstop
:param subscription_id: id of an existing Push Subscription.
:type subscription_id: str
:returns: dict with extra response data
:rty... | 8.148201 | 14.808045 | 0.550255 |
return self.request.post('delete', data=dict(id=subscription_id)) | def delete(self, subscription_id) | Delete the subscription for the given ID.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushdelete
:param subscription_id: id of an existing Push Subscription.
:type subscription_id: str
:returns: dict with extra response data
:r... | 8.127012 | 12.978485 | 0.626191 |
params = {}
if subscription_id:
params['id'] = subscription_id
if page:
params['page'] = page
if per_page:
params['per_page'] = per_page
if order_by:
params['order_by'] = order_by
if order_dir:
params['o... | def log(self, subscription_id=None, page=None, per_page=None, order_by=None, order_dir=None) | Retrieve any messages that have been logged for your subscriptions.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushlog
:param subscription_id: optional id of an existing Push Subscription, restricts logs to a given subscription if supplied.
:type sub... | 1.603894 | 1.691721 | 0.948084 |
params = {}
if subscription_id:
params['id'] = subscription_id
if stream:
params['hash'] = stream
if historics_id:
params['historics_id'] = historics_id
if page:
params['page'] = page
if per_page:
params... | def get(self, subscription_id=None, stream=None, historics_id=None,
page=None, per_page=None, order_by=None, order_dir=None,
include_finished=None) | Show details of the Subscriptions belonging to this user.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushget
:param subscription_id: optional id of an existing Push Subscription
:type subscription_id: str
:param hash: optional hash of a l... | 1.519824 | 1.543454 | 0.98469 |
''' Return the project as `foo` or `user/foo` if the project is a
fork.
'''
project = msg[key]['name']
ns = msg[key].get('namespace')
if ns:
project = '/'.join([ns, project])
if msg[key]['parent']:
user = msg[key]['user']['name']
project = '/'.join(['fork', user, proj... | def _get_project(msg, key='project') | Return the project as `foo` or `user/foo` if the project is a
fork. | 5.169824 | 2.972341 | 1.73931 |
''' Return the subtitle for the first version of pagure git.receive
messages.
'''
repo = _get_project(msg['msg']['commit'], key='repo')
email = msg['msg']['commit']['email']
user = email2fas(email, **config)
summ = msg['msg']['commit']['summary']
whole = msg['msg']['commit']['message']
... | def _git_receive_v1(msg, tmpl, **config) | Return the subtitle for the first version of pagure git.receive
messages. | 6.712359 | 4.922013 | 1.363743 |
''' Return the subtitle for the second version of pagure git.receive
messages.
'''
repo = _get_project(msg['msg'], key='repo')
user = msg['msg']['agent']
n_commits = msg['msg']['total_commits']
commit_lbl = 'commit' if str(n_commits) == '1' else 'commits'
branch = msg['msg']['branch']
... | def _git_receive_v2(msg, tmpl) | Return the subtitle for the second version of pagure git.receive
messages. | 4.60886 | 3.329894 | 1.384086 |
'''
Register a new version for archive ``archive_name``
.. note ::
need to implement hash checking to prevent duplicate writes
'''
version_metadata['updated'] = self.create_timestamp()
version_metadata['version'] = str(
version_metadata.get('vers... | def update(self, archive_name, version_metadata) | Register a new version for archive ``archive_name``
.. note ::
need to implement hash checking to prevent duplicate writes | 5.358684 | 2.78193 | 1.926247 |
'''
Update metadata for archive ``archive_name``
'''
required_metadata_keys = self.required_archive_metadata.keys()
for key, val in archive_metadata.items():
if key in required_metadata_keys and val is None:
raise ValueError(
'Cann... | def update_metadata(self, archive_name, archive_metadata) | Update metadata for archive ``archive_name`` | 3.82567 | 4.026199 | 0.950194 |
'''
Create a new data archive
Returns
-------
archive : object
new :py:class:`~datafs.core.data_archive.DataArchive` object
'''
archive_metadata = self._create_archive_metadata(
archive_name=archive_name,
authority_name=autho... | def create_archive(
self,
archive_name,
authority_name,
archive_path,
versioned,
raise_on_err=True,
metadata=None,
user_config=None,
tags=None,
helper=False) | Create a new data archive
Returns
-------
archive : object
new :py:class:`~datafs.core.data_archive.DataArchive` object | 2.272196 | 1.667345 | 1.362762 |
'''
Get a data archive given an archive name
Returns
-------
archive_specification : dict
archive_name: name of the archive to be retrieved
authority: name of the archive's authority
archive_path: service path of archive
'''
t... | def get_archive(self, archive_name) | Get a data archive given an archive name
Returns
-------
archive_specification : dict
archive_name: name of the archive to be retrieved
authority: name of the archive's authority
archive_path: service path of archive | 5.656349 | 2.042963 | 2.768698 |
'''
Add tags to an archive
Parameters
----------
archive_name:s tr
Name of archive
tags: list or tuple of strings
tags to add to the archive
'''
updated_tag_list = list(self._get_tags(archive_name))
for tag in tags:
... | def add_tags(self, archive_name, tags) | Add tags to an archive
Parameters
----------
archive_name:s tr
Name of archive
tags: list or tuple of strings
tags to add to the archive | 3.016687 | 1.922579 | 1.569084 |
'''
Delete tags from an archive
Parameters
----------
archive_name:s tr
Name of archive
tags: list or tuple of strings
tags to delete from the archive
'''
updated_tag_list = list(self._get_tags(archive_name))
for tag in t... | def delete_tags(self, archive_name, tags) | Delete tags from an archive
Parameters
----------
archive_name:s tr
Name of archive
tags: list or tuple of strings
tags to delete from the archive | 3.122815 | 1.937189 | 1.612034 |
'''
Coerces tags to lowercase strings
Parameters
----------
tags: list or tuple of strings
'''
lowered_str_tags = []
for tag in tags:
lowered_str_tags.append(str(tag).lower())
return lowered_str_tags | def _normalize_tags(self, tags) | Coerces tags to lowercase strings
Parameters
----------
tags: list or tuple of strings | 4.341622 | 2.765768 | 1.569771 |
"Start the project on the directory"
bookname = self.args.get('--bookname', None)
if not bookname:
bookname = 'book.md'
project_dir = self.args.get('<name>', None)
if not project_dir:
project_dir = join(self.cwd, 'Book')
project_dir = abspath(proje... | def start(self) | Start the project on the directory | 3.593919 | 3.520817 | 1.020763 |
"Build your book"
config = self.load_config()
html_generator = HTMLGenerator(self.cwd, config)
html_generator.build()
if self.args.get('--generator', None):
generator = self.args.get('--generator')
else:
generator = config.get('generator')
... | def build(self) | Build your book | 3.302749 | 3.147676 | 1.049266 |
"Checks EPUB integrity"
config = self.load_config()
if not check_dependency_epubcheck():
sys.exit(error('Unavailable command.'))
epub_file = u"%s.epub" % config['fileroot']
epub_path = join(CWD, 'build', epub_file)
print success("Starting to check %s..." % epu... | def check(self) | Checks EPUB integrity | 6.03493 | 5.667839 | 1.064767 |
create_sql = 'CREATE DATABASE {self.db_name} WITH OWNER {self.user}'
create_sql = create_sql.format(**vars())
self.super_psql(['-c', create_sql])
if sql:
self.psql_string(sql) | def create(self, sql=None) | CREATE this DATABASE.
@param sql: (Optional) A string of psql (such as might be generated
by pg_dump); it will be executed by psql(1) after creating the
database.
@type sql: str
@rtype: None | 4.830028 | 4.90737 | 0.98424 |
argv = [
PostgresFinder.find_root() / 'psql',
'--quiet',
'-U', self.user,
'-h', self.host,
'-p', self.port,
'-f', '-',
self.db_name,
]
popen = subprocess.Popen(argv, stdin=subprocess.PIPE)
popen.... | def psql_string(self, sql) | Evaluate the sql file (possibly multiple statements) using psql. | 2.606853 | 2.684002 | 0.971256 |
r
argv = [
PostgresFinder.find_root() / 'psql',
'--quiet',
'-U', self.user,
'-h', self.host,
'-p', self.port,
] + args + [self.db_name]
subprocess.check_call(argv) | def psql(self, args) | r"""Invoke psql, passing the given command-line arguments.
Typical <args> values: ['-c', <sql_string>] or ['-f', <pathname>].
Connection parameters are taken from self. STDIN, STDOUT,
and STDERR are inherited from the parent.
WARNING: This method uses the psql(1) program, which ignor... | 5.245661 | 5.82147 | 0.901089 |
psycopg2 = importlib.import_module('psycopg2')
importlib.import_module('psycopg2.extensions')
connection = psycopg2.connect(
user=self.user, host=self.host,
port=self.port, database=self.db_name)
connection.set_isolation_level(
psycop... | def sql(self, input_string, *args) | Execute a SQL command using the Python DBI directly.
Connection parameters are taken from self. Autocommit is in effect.
Example: .sql('SELECT %s FROM %s WHERE age > %s', 'name', 'table1',
'45')
@param input_string: A string of SQL. May contain %s or %(name)s
format spec... | 2.588408 | 2.485107 | 1.041568 |
argv = [
PostgresFinder.find_root() / 'psql',
'--quiet',
'-U', self.superuser,
'-h', self.host,
'-p', self.port,
] + args
subprocess.check_call(argv) | def super_psql(self, args) | Just like .psql(), except that we connect as the database superuser
(and we connect to the superuser's database, not the user's database). | 4.843504 | 5.072498 | 0.954856 |
self.stop()
if self.base_pathname is not None:
self._robust_remove(self.base_pathname) | def destroy(self) | Undo the effects of initdb.
Destroy all evidence of this DBMS, including its backing files. | 8.140058 | 8.332932 | 0.976854 |
tries = itertools.count()
max_tries = 50
while os.path.isdir(path):
try:
shutil.rmtree(path)
except WindowsError:
if next(tries) >= max_tries:
raise
time.sleep(0.2) | def _robust_remove(path) | Remove the directory specified by `path`. Because we can't determine
directly if the path is in use, and on Windows, it's not possible to
remove a path if it is in use, retry a few times until the call
succeeds. | 2.799326 | 2.763932 | 1.012805 |
# Defining base_pathname is deferred until this point because we don't
# want to create a temp directory unless it's needed. And now it is!
if self.base_pathname in [None, '']:
self.base_pathname = tempfile.mkdtemp()
if not os.path.isdir(self.base_pathname):
... | def initdb(self, quiet=True, locale='en_US.UTF-8') | Bootstrap this DBMS from nothing.
If you're running in an environment where the DBMS is provided as part
of the basic infrastructure, you probably don't want to call this
method!
@param quiet: Should we operate quietly, emitting nothing if things go
well? | 5.116642 | 5.318976 | 0.96196 |
# We can't possibly be running if our base_pathname isn't defined.
if not self.base_pathname:
return False
if tries < 1:
raise ValueError('tries must be > 0')
cmd = [
PostgresFinder.find_root() / 'pg_ctl',
'status',
'... | def _is_running(self, tries=10) | Return if the server is running according to pg_ctl. | 4.505756 | 4.130221 | 1.090924 |
cmd = self._psql_cmd()
for i in range(50, -1, -1):
res = subprocess.call(
cmd, stdin=DEV_NULL, stdout=DEV_NULL,
stderr=DEV_NULL)
if res == 0:
break
time.sleep(0.2)
return i != 0 | def ready(self) | Assumes postgres now talks to pg_ctl, but might not yet be listening
or connections from psql. Test that psql is able to connect, as
it occasionally takes 5-10 seconds for postgresql to start listening. | 4.157394 | 3.32191 | 1.251507 |
# We can't possibly be running if our base_pathname isn't defined.
if not self.base_pathname:
return None
try:
pidfile = os.path.join(self.base_pathname, 'postmaster.pid')
return int(open(pidfile).readline())
except (IOError, OSError):
... | def pid(self) | The server's PID (None if not running). | 4.044506 | 3.529022 | 1.14607 |
cmd = [PostgresFinder.find_root() / 'pg_ctl', '--version']
results = subprocess.check_output(cmd).decode('utf-8')
match = re.search(r'(\d+\.\d+(\.\d+)?)', results)
if match:
ver_string = match.group(0)
return tuple(int(x) for x in ver_string.split('.')) | def get_version() | Returns the Postgres version in tuple form, e.g: (9, 1) | 3.398699 | 3.040123 | 1.117948 |
log.info('Starting PostgreSQL at %s:%s', self.host, self.port)
if not self.base_pathname:
tmpl = ('Invalid base_pathname: %r. Did you forget to call '
'.initdb()?')
raise NotInitializedError(tmpl % self.base_pathname)
conf_file = os.path.joi... | def start(self) | Launch this postgres server. If it's already running, do nothing.
If the backing storage directory isn't configured, raise
NotInitializedError.
This method is optional. If you're running in an environment
where the DBMS is provided as part of the basic infrastructure,
you pro... | 5.256572 | 4.95688 | 1.06046 |
log.info('Stopping PostgreSQL at %s:%s', self.host, self.port)
if self._is_running():
cmd = [
PostgresFinder.find_root() / 'pg_ctl',
'stop',
'-D', self.base_pathname,
'-m', 'fast',
]
subprocess.c... | def stop(self) | Stop this DMBS daemon. If it's not currently running, do nothing.
Don't return until it's terminated. | 5.491969 | 5.378153 | 1.021163 |
db = PostgresDatabase(
db_name, host=self.host, port=self.port,
superuser=self.superuser, **kwargs)
db.ensure_user()
db.create()
return db | def create(self, db_name, **kwargs) | Construct a PostgresDatabase and create it on self | 4.008576 | 3.200862 | 1.252343 |
kwargs = dict(
ProjectionExpression='#id',
ExpressionAttributeNames={"#id": "_id"})
if len(search_terms) > 0:
kwargs['FilterExpression'] = reduce(
lambda x, y: x & y,
[Attr('tags').contains(arg) for arg in search_terms])
... | def _search(self, search_terms, begins_with=None) | Returns a list of Archive id's in the table on Dynamo | 2.301873 | 2.146411 | 1.072429 |
'''
Updates the version specific metadata attribute in DynamoDB
In DynamoDB this is simply a list append on this attribute value
Parameters
----------
archive_name: str
unique '_id' primary key
version_metadata: dict
dictionary of version... | def _update(self, archive_name, version_metadata) | Updates the version specific metadata attribute in DynamoDB
In DynamoDB this is simply a list append on this attribute value
Parameters
----------
archive_name: str
unique '_id' primary key
version_metadata: dict
dictionary of version metadata values
... | 6.586873 | 1.883482 | 3.497179 |
'''
Dynamo implementation of BaseDataManager create_archive_table
waiter object is implemented to ensure table creation before moving on
this will slow down table creation. However, since we are only creating
table once this should no impact users.
Parameters
--... | def _create_archive_table(self, table_name) | Dynamo implementation of BaseDataManager create_archive_table
waiter object is implemented to ensure table creation before moving on
this will slow down table creation. However, since we are only creating
table once this should no impact users.
Parameters
----------
tab... | 3.959515 | 2.017456 | 1.962627 |
'''
Dynamo implementation of spec config creation
Called by `create_archive_table()` in
:py:class:`manager.BaseDataManager` Simply adds two rows to the spec
table
Parameters
----------
table_name :
base table name (not including .spec suffi... | def _create_spec_config(self, table_name, spec_documents) | Dynamo implementation of spec config creation
Called by `create_archive_table()` in
:py:class:`manager.BaseDataManager` Simply adds two rows to the spec
table
Parameters
----------
table_name :
base table name (not including .spec suffix)
spec_doc... | 8.750564 | 1.846365 | 4.739346 |
'''
Dynamo implementation of project specific metadata spec
'''
# add the updated archive_metadata object to Dynamo
self._spec_table.update_item(
Key={'_id': '{}'.format(document_name)},
UpdateExpression="SET config = :v",
ExpressionAttributeV... | def _update_spec_config(self, document_name, spec) | Dynamo implementation of project specific metadata spec | 8.195041 | 5.417749 | 1.512628 |
archive_metadata_current = self._get_archive_metadata(archive_name)
archive_metadata_current.update(archive_metadata)
for k, v in archive_metadata_current.items():
if v is None:
del archive_metadata_current[k]
# add the updated archive_metadata obje... | def _update_metadata(self, archive_name, archive_metadata) | Appends the updated_metada dict to the Metadata Attribute list
Parameters
----------
archive_name: str
ID of archive to update
updated_metadata: dict
dictionary of metadata keys and values to update. If the value
for a particular key is `None`, the... | 2.683176 | 2.88781 | 0.929139 |
'''
This adds an item in a DynamoDB table corresponding to a S3 object
Args
----
arhive_name: str
corresponds to the name of the Archive (e.g. )
Returns
-------
Dictionary with confirmation of upload
'''
archive_exists = Fa... | def _create_archive(
self,
archive_name,
metadata) | This adds an item in a DynamoDB table corresponding to a S3 object
Args
----
arhive_name: str
corresponds to the name of the Archive (e.g. )
Returns
-------
Dictionary with confirmation of upload | 6.145477 | 2.279027 | 2.696535 |
'''
Batched version of :py:meth:`~DynamoDBManager._get_archive_listing`
Returns a list of full archive listings from an iterable of archive
names
.. note ::
Invalid archive names will simply not be returned, so the response
may not be the same length as... | def _batch_get_archive_listing(self, archive_names) | Batched version of :py:meth:`~DynamoDBManager._get_archive_listing`
Returns a list of full archive listings from an iterable of archive
names
.. note ::
Invalid archive names will simply not be returned, so the response
may not be the same length as the supplied `archi... | 3.170288 | 2.021533 | 1.568259 |
try:
if len(backend_name.split(".")) > 1:
mod = import_module(backend_name)
else:
mod = import_module("spamc.backend_%s" % backend_name)
return mod
except ImportError:
error_msg = "%s isn't a spamc backend" % backend_name
raise ImportError(err... | def load_backend(backend_name) | load pool backend. | 3.020094 | 3.078032 | 0.981177 |
parser = objectify.makeparser(remove_blank_text=True)
v = objectify.fromstring(voeventparse.definitions.v2_0_skeleton_str,
parser=parser)
_remove_root_tag_prefix(v)
if not isinstance(stream_id, string_types):
stream_id = repr(stream_id)
v.attrib['ivorn'] = '... | def Voevent(stream, stream_id, role) | Create a new VOEvent element tree, with specified IVORN and role.
Args:
stream (str): used to construct the IVORN like so::
ivorn = 'ivo://' + stream + '#' + stream_id
(N.B. ``stream_id`` is converted to string if required.)
So, e.g. we might set::
... | 5.700257 | 5.330462 | 1.069374 |
# .. note::
#
# The namespace is removed from the root element tag to make
# objectify access work as expected,
# (see :py:func:`._remove_root_tag_prefix`)
# so we must re-insert it when we want to conform to schema.
v = objectify.fromstring(s)
_remove_root_tag... | def loads(s, check_version=True) | Load VOEvent from bytes.
This parses a VOEvent XML packet string, taking care of some subtleties.
For Python 3 users, ``s`` should be a bytes object - see also
http://lxml.de/FAQ.html,
"Why can't lxml parse my XML from unicode strings?"
(Python 2 users can stick with old-school ``str`` type if pref... | 8.261832 | 7.329422 | 1.127215 |
s = file.read()
return loads(s, check_version) | def load(file, check_version=True) | Load VOEvent from file object.
A simple wrapper to read a file before passing the contents to
:py:func:`.loads`. Use with an open file object, e.g.::
with open('/path/to/voevent.xml', 'rb') as f:
v = vp.load(f)
Args:
file (io.IOBase): An open file object (binary mode preferred... | 6.782428 | 17.330643 | 0.391355 |
vcopy = copy.deepcopy(voevent)
_return_to_standard_xml(vcopy)
s = etree.tostring(vcopy, pretty_print=pretty_print,
xml_declaration=xml_declaration,
encoding=encoding)
return s | def dumps(voevent, pretty_print=False, xml_declaration=True, encoding='UTF-8') | Converts voevent to string.
.. note:: Default encoding is UTF-8, in line with VOE2.0 schema.
Declaring the encoding can cause diffs with the original loaded VOEvent,
but I think it's probably the right thing to do (and lxml doesn't
really give you a choice anyway).
Args:
voeven... | 3.398948 | 4.711096 | 0.721477 |
file.write(dumps(voevent, pretty_print, xml_declaration)) | def dump(voevent, file, pretty_print=True, xml_declaration=True) | Writes the voevent to the file object.
e.g.::
with open('/tmp/myvoevent.xml','wb') as f:
voeventparse.dump(v, f)
Args:
voevent(:class:`Voevent`): Root node of the VOevent etree.
file (io.IOBase): An open (binary mode) file object for writing.
pretty_print
p... | 3.601317 | 4.03426 | 0.892684 |
_return_to_standard_xml(voevent)
valid_bool = voevent_v2_0_schema.validate(voevent)
_remove_root_tag_prefix(voevent)
return valid_bool | def valid_as_v2_0(voevent) | Tests if a voevent conforms to the schema.
Args:
voevent(:class:`Voevent`): Root node of a VOEvent etree.
Returns:
bool: Whether VOEvent is valid | 7.857449 | 9.248411 | 0.8496 |
if author_ivorn is not None:
voevent.Who.AuthorIVORN = ''.join(('ivo://', author_ivorn))
if date is not None:
voevent.Who.Date = date.replace(microsecond=0).isoformat() | def set_who(voevent, date=None, author_ivorn=None) | Sets the minimal 'Who' attributes: date of authoring, AuthorIVORN.
Args:
voevent(:class:`Voevent`): Root node of a VOEvent etree.
date(datetime.datetime): Date of authoring.
NB Microseconds are ignored, as per the VOEvent spec.
author_ivorn(str): Short author identifier,
... | 3.254026 | 2.682173 | 1.213205 |
# We inspect all local variables except the voevent packet,
# Cycling through and assigning them on the Who.Author element.
AuthChildren = locals()
AuthChildren.pop('voevent')
if not voevent.xpath('Who/Author'):
etree.SubElement(voevent.Who, 'Author')
for k, v in AuthChildren.items(... | def set_author(voevent, title=None, shortName=None, logoURL=None,
contactName=None, contactEmail=None, contactPhone=None,
contributor=None) | For setting fields in the detailed author description.
This can optionally be neglected if a well defined AuthorIVORN is supplied.
.. note:: Unusually for this library,
the args here use CamelCase naming convention,
since there's a direct mapping to the ``Author.*``
attributes to which... | 8.257065 | 8.391893 | 0.983933 |
# .. todo:: Implement TimeError using datetime.timedelta
if obs_time.tzinfo is not None:
utc_naive_obs_time = obs_time.astimezone(pytz.utc).replace(tzinfo=None)
elif not allow_tz_naive_datetime:
raise ValueError(
"Datetime passed without tzinfo, cannot be sure if it is real... | def add_where_when(voevent, coords, obs_time, observatory_location,
allow_tz_naive_datetime=False) | Add details of an observation to the WhereWhen section.
We
Args:
voevent(:class:`Voevent`): Root node of a VOEvent etree.
coords(:class:`.Position2D`): Sky co-ordinates of event.
obs_time(datetime.datetime): Nominal DateTime of the observation. Must
either be timezone-aware... | 3.741911 | 3.557457 | 1.05185 |
if not voevent.xpath('How'):
etree.SubElement(voevent, 'How')
if descriptions is not None:
for desc in _listify(descriptions):
# d = etree.SubElement(voevent.How, 'Description')
# voevent.How.Description[voevent.How.index(d)] = desc
##Simpler:
... | def add_how(voevent, descriptions=None, references=None) | Add descriptions or references to the How section.
Args:
voevent(:class:`Voevent`): Root node of a VOEvent etree.
descriptions(str): Description string, or list of description
strings.
references(:py:class:`voeventparse.misc.Reference`): A reference element
(or list ... | 3.378956 | 3.218637 | 1.049809 |
if not voevent.xpath('Why'):
etree.SubElement(voevent, 'Why')
if importance is not None:
voevent.Why.attrib['importance'] = str(importance)
if expires is not None:
voevent.Why.attrib['expires'] = expires.replace(
microsecond=0).isoformat()
if inferences is not No... | def add_why(voevent, importance=None, expires=None, inferences=None) | Add Inferences, or set importance / expires attributes of the Why section.
.. note::
``importance`` / ``expires`` are 'Why' attributes, therefore setting them
will overwrite previous values.
``inferences``, on the other hand, are appended to the list.
Args:
voevent(:class:`Vo... | 2.589053 | 2.417058 | 1.071159 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.