_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q38900
IndexPage.run
train
def run(self): """ Index the document. Since ids are predictable, we won't index anything twice. """ with self.input().open() as handle: body = json.loads(handle.read()) es = elasticsearch.Elasticsearch() id = body.get('_id') es.index(index='frontpage', do...
python
{ "resource": "" }
q38901
DailyIndex.requires
train
def requires(self): """ Index all pages. """ for url in NEWSPAPERS: yield IndexPage(url=url, date=self.date)
python
{ "resource": "" }
q38902
Query.get_name
train
def get_name(self, data): """ For non-specific queries, this will return the actual name in the result. """ if self.node.specific_attribute: return self.node.name name = data.get(self.predicate_var) if str(RDF.type) in [self.node.name, name]: return '$sche...
python
{ "resource": "" }
q38903
Query.project
train
def project(self, q, parent=False): """ Figure out which attributes should be returned for the current level of the query. """ if self.parent: print (self.parent.var, self.predicate, self.var) q = q.project(self.var, append=True) if parent and self.parent: ...
python
{ "resource": "" }
q38904
Query.filter
train
def filter(self, q, parents=None): """ Apply any filters to the query. """ if self.node.leaf and self.node.filtered: # TODO: subject filters? q = q.where((self.parent.var, self.predicate, self.var)) # TODO: inverted no...
python
{ "resource": "" }
q38905
Query.query
train
def query(self, parents=None): """ Compose the query and generate SPARQL. """ # TODO: benchmark single-query strategy q = Select([]) q = self.project(q, parent=True) q = self.filter(q, parents=parents) if self.parent is None: subq = Select([self.var]) ...
python
{ "resource": "" }
q38906
Query.base_object
train
def base_object(self, data): """ Make sure to return all the existing filter fields for query results. """ obj = {'id': data.get(self.id)} if self.parent is not None: obj['$parent'] = data.get(self.parent.id) return obj
python
{ "resource": "" }
q38907
Query.execute
train
def execute(self, parents=None): """ Run the data query and construct entities from it's results. """ results = OrderedDict() for row in self.query(parents=parents).execute(self.context.graph): data = {k: v.toPython() for (k, v) in row.asdict().items()} id = data.get(self...
python
{ "resource": "" }
q38908
Query.collect
train
def collect(self, parents=None): """ Given re-constructed entities, conduct queries for child entities and merge them into the current level's object graph. """ results = self.execute(parents=parents) ids = results.keys() for child in self.nested(): name = child.node....
python
{ "resource": "" }
q38909
_download_and_decompress_if_necessary
train
def _download_and_decompress_if_necessary( full_path, download_url, timeout=None, use_wget_if_available=False): """ Downloads remote file at `download_url` to local file at `full_path` """ logger.info("Downloading %s to %s", download_url, full_path) filename = os.path...
python
{ "resource": "" }
q38910
fetch_and_transform
train
def fetch_and_transform( transformed_filename, transformer, loader, source_filename, source_url, subdir=None): """ Fetch a remote file from `source_url`, save it locally as `source_filename` and then use the `loader` and `transformer` function arguments to tur...
python
{ "resource": "" }
q38911
fetch_csv_dataframe
train
def fetch_csv_dataframe( download_url, filename=None, subdir=None, **pandas_kwargs): """ Download a remote file from `download_url` and save it locally as `filename`. Load that local file as a CSV into Pandas using extra keyword arguments such as sep='\t'. """ path = ...
python
{ "resource": "" }
q38912
getLoader
train
def getLoader(*a, **kw): """ Deprecated. Don't use this. """ warn("xmantissa.publicweb.getLoader is deprecated, use " "PrivateApplication.getDocFactory or SiteTemplateResolver." "getDocFactory.", category=DeprecationWarning, stacklevel=2) from xmantissa.webtheme import getLoader ...
python
{ "resource": "" }
q38913
_CustomizingResource.locateChild
train
def locateChild(self, ctx, segments): """ Return a Deferred which will fire with the customized version of the resource being located. """ D = defer.maybeDeferred( self.currentResource.locateChild, ctx, segments) def finishLocating((nextRes, nextPath)): ...
python
{ "resource": "" }
q38914
_PublicPageMixin.render_authenticateLinks
train
def render_authenticateLinks(self, ctx, data): """ For unauthenticated users, add login and signup links to the given tag. For authenticated users, remove the given tag from the output. When necessary, the I{signup-link} pattern will be loaded from the tag. Each copy of it will ...
python
{ "resource": "" }
q38915
_PublicPageMixin.render_startmenu
train
def render_startmenu(self, ctx, data): """ For authenticated users, add the start-menu style navigation to the given tag. For unauthenticated users, remove the given tag from the output. @see L{xmantissa.webnav.startMenu} """ if self.username is None: ...
python
{ "resource": "" }
q38916
_PublicPageMixin.render_settingsLink
train
def render_settingsLink(self, ctx, data): """ For authenticated users, add the URL of the settings page to the given tag. For unauthenticated users, remove the given tag from the output. """ if self.username is None: return '' translator = self._getViewerPriv...
python
{ "resource": "" }
q38917
_PublicPageMixin.render_applicationNavigation
train
def render_applicationNavigation(self, ctx, data): """ For authenticated users, add primary application navigation to the given tag. For unauthenticated users, remove the given tag from the output. @see L{xmantissa.webnav.applicationNavigation} """ if self.usern...
python
{ "resource": "" }
q38918
_PublicPageMixin.render_search
train
def render_search(self, ctx, data): """ Render some UI for performing searches, if we know about a search aggregator. """ if self.username is None: return '' translator = self._getViewerPrivateApplication() searchAggregator = translator.getPageComponen...
python
{ "resource": "" }
q38919
_PublicPageMixin.getHeadContent
train
def getHeadContent(self, req): """ Retrieve a list of header content from all installed themes on the site store. """ site = ixmantissa.ISiteURLGenerator(self.store) for t in getInstalledThemes(self.store): yield t.head(req, site)
python
{ "resource": "" }
q38920
_OfferingsFragment.data_offerings
train
def data_offerings(self, ctx, data): """ Generate a list of installed offerings. @return: a generator of dictionaries mapping 'name' to the name of an offering installed on the store. """ for io in self.original.store.query(offering.InstalledOffering): pp = i...
python
{ "resource": "" }
q38921
_PublicFrontPage._getAppStoreResource
train
def _getAppStoreResource(self, ctx, name): """ Customize child lookup such that all installed offerings on the site store that this page is viewing are given an opportunity to display their own page. """ offer = self.frontPageItem.store.findFirst( offering.Ins...
python
{ "resource": "" }
q38922
_PublicFrontPage.child_
train
def child_(self, ctx): """ If the root resource is requested, return the primary application's front page, if a primary application has been chosen. Otherwise return 'self', since this page can render a simple index. """ if self.frontPageItem.defaultApplication i...
python
{ "resource": "" }
q38923
AnonymousSite.rootChild_resetPassword
train
def rootChild_resetPassword(self, req, webViewer): """ Return a page which will allow the user to re-set their password. """ from xmantissa.signup import PasswordResetResource return PasswordResetResource(self.store)
python
{ "resource": "" }
q38924
BaseConfigurator.get_configurable_by_name
train
def get_configurable_by_name(self, name): """ Returns the registered configurable with the specified name or ``None`` if no such configurator exists. """ l = [c for c in self.configurables if c.name == name] if l: return l[0]
python
{ "resource": "" }
q38925
Project.results
train
def results(self, trial_ids): """ Accepts a sequence of trial ids and returns a pandas dataframe with the schema trial_id, iteration?, *metric_schema_union where iteration is an optional column that specifies the iteration when a user logged a metric, if the user suppli...
python
{ "resource": "" }
q38926
Project.fetch_artifact
train
def fetch_artifact(self, trial_id, prefix): """ Verifies that all children of the artifact prefix path are available locally. Fetches them if not. Returns the local path to the given trial's artifacts at the specified prefix, which is always just {log_dir}/{trial_id}/{p...
python
{ "resource": "" }
q38927
MetaData._load
train
def _load(self): """ Load provenance info from the main store. """ graph = self.context.parent.graph.get_context(self.context.identifier) data = {} for (_, p, o) in graph.triples((self.context.identifier, None, None)): if not p.startswith(META): continue ...
python
{ "resource": "" }
q38928
MetaData.generate
train
def generate(self): """ Add provenance info to the context graph. """ t = (self.context.identifier, RDF.type, META.Provenance) if t not in self.context.graph: self.context.graph.add(t) for name, value in self.data.items(): pat = (self.context.identifier, META[name...
python
{ "resource": "" }
q38929
jsonresolver_loader
train
def jsonresolver_loader(url_map): """Jsonresolver hook for funders resolving.""" def endpoint(doi_code): pid_value = "10.13039/{0}".format(doi_code) _, record = Resolver(pid_type='frdoi', object_type='rec', getter=Record.get_record).resolve(pid_value) return ...
python
{ "resource": "" }
q38930
SR830.snap
train
def snap(self, *args): """Records up to 6 parameters at a time. :param args: Specifies the values to record. Valid ones are 'X', 'Y', 'R', 'theta', 'AuxIn1', 'AuxIn2', 'AuxIn3', 'AuxIn4', 'Ref', 'CH1' and 'CH2'. If none are given 'X' and 'Y' are used. """ # TODO: Do...
python
{ "resource": "" }
q38931
SR830.trace
train
def trace(self, buffer, start, length=1): """Reads the points stored in the channel buffer. :param buffer: Selects the channel buffer (either 1 or 2). :param start: Selects the bin where the reading starts. :param length: The number of bins to read. .. todo:: Use bin...
python
{ "resource": "" }
q38932
isAppStore
train
def isAppStore(s): """ Return whether the given store is an application store or not. @param s: A Store. """ if s.parent is None: return False substore = s.parent.getItemByID(s.idInParent) return s.parent.query(InstalledOffering, InstalledOffering.applicatio...
python
{ "resource": "" }
q38933
RouterHandler.send_file
train
def send_file(self, file): """ Send a file to the client, it is a convenient method to avoid duplicated code """ if self.logger: self.logger.debug("[ioc.extra.tornado.RouterHandler] send file %s" % file) self.send_file_header(file) fp = open(file, 'rb') ...
python
{ "resource": "" }
q38934
triplify_object
train
def triplify_object(binding): """ Create bi-directional bindings for object relationships. """ triples = [] if binding.uri: triples.append((binding.subject, RDF.type, binding.uri)) if binding.parent is not None: parent = binding.parent.subject if binding.parent.is_array: ...
python
{ "resource": "" }
q38935
triplify
train
def triplify(binding): """ Recursively generate RDF statement triples from the data and schema supplied to the application. """ triples = [] if binding.data is None: return None, triples if binding.is_object: return triplify_object(binding) elif binding.is_array: for ite...
python
{ "resource": "" }
q38936
_candidate_type_names
train
def _candidate_type_names(python_type_representation): """Generator which yields possible type names to look up in the conversion dictionary. Parameters ---------- python_type_representation : object Any Python object which represents a type, such as `int`, `dtype('int8')`, `np.int8...
python
{ "resource": "" }
q38937
Droplet.fetch
train
def fetch(self): """ Fetch & return a new `Droplet` object representing the droplet's current state :rtype: Droplet :raises DOAPIError: if the API endpoint replies with an error (e.g., if the droplet no longer exists) """ api = self.doapi_manager ...
python
{ "resource": "" }
q38938
Droplet.fetch_all_neighbors
train
def fetch_all_neighbors(self): r""" Returns a generator that yields all of the droplets running on the same physical server as the droplet :rtype: generator of `Droplet`\ s :raises DOAPIError: if the API endpoint replies with an error """ api = self.doapi_manager...
python
{ "resource": "" }
q38939
Droplet.fetch_all_snapshots
train
def fetch_all_snapshots(self): r""" Returns a generator that yields all of the snapshot images created from the droplet :rtype: generator of `Image`\ s :raises DOAPIError: if the API endpoint replies with an error """ api = self.doapi_manager for obj in a...
python
{ "resource": "" }
q38940
Droplet.fetch_all_backups
train
def fetch_all_backups(self): r""" Returns a generator that yields all of the backup images created from the droplet :rtype: generator of `Image`\ s :raises DOAPIError: if the API endpoint replies with an error """ api = self.doapi_manager for obj in api.p...
python
{ "resource": "" }
q38941
Droplet.fetch_all_kernels
train
def fetch_all_kernels(self): r""" Returns a generator that yields all of the kernels available to the droplet :rtype: generator of `Kernel`\ s :raises DOAPIError: if the API endpoint replies with an error """ api = self.doapi_manager for kern in api.pagin...
python
{ "resource": "" }
q38942
Droplet.restore
train
def restore(self, image): """ Restore the droplet to the specified backup image A Droplet restoration will rebuild an image using a backup image. The image ID that is passed in must be a backup of the current Droplet instance. The operation will leave any embedded S...
python
{ "resource": "" }
q38943
Droplet.resize
train
def resize(self, size, disk=None): """ Resize the droplet :param size: a size slug or a `Size` object representing the size to resize to :type size: string or `Size` :param bool disk: Set to `True` for a permanent resize, including disk changes :r...
python
{ "resource": "" }
q38944
Droplet.rebuild
train
def rebuild(self, image): """ Rebuild the droplet with the specified image A rebuild action functions just like a new create. [APIDocs]_ :param image: an image ID, an image slug, or an `Image` object representing the image the droplet should use as a base :type ...
python
{ "resource": "" }
q38945
Droplet.change_kernel
train
def change_kernel(self, kernel): """ Change the droplet's kernel :param kernel: a kernel ID or `Kernel` object representing the new kernel :type kernel: integer or `Kernel` :return: an `Action` representing the in-progress operation on the droplet ...
python
{ "resource": "" }
q38946
minter
train
def minter(record_uuid, data, pid_type, key): """Mint PIDs for a record.""" pid = PersistentIdentifier.create( pid_type, data[key], object_type='rec', object_uuid=record_uuid, status=PIDStatus.REGISTERED ) for scheme, identifier in data['identifiers'].items(): ...
python
{ "resource": "" }
q38947
date_range
train
def date_range(start_date, end_date, increment, period): """ Generate `date` objects between `start_date` and `end_date` in `increment` `period` intervals. """ next = start_date delta = relativedelta.relativedelta(**{period:increment}) while next <= end_date: yield next next ...
python
{ "resource": "" }
q38948
send_message
train
def send_message(frm=None, to=None, text=None): """Shortcut to send a sms using libnexmo api. :param frm: The originator of the message :param to: The message's recipient :param text: The text message body Example usage: >>> send_message(to='+33123456789', text='My sms message body') """...
python
{ "resource": "" }
q38949
filtered
train
def filtered(f): ''' Decorator function that wraps functions returning pandas dataframes, such that the dataframe is filtered according to left and right bounds set. ''' def _filter(f, self, *args, **kwargs): frame = f(self, *args, **kwargs) ret = type(self)(frame) ret._...
python
{ "resource": "" }
q38950
Result.to_datetime
train
def to_datetime(self, column): ''' This function converts epoch timestamps to datetimes. :param column: column to convert from current state -> datetime ''' if column in self: if self[column].dtype in NUMPY_NUMERICAL: self[column] = pd.to_datetime(sel...
python
{ "resource": "" }
q38951
Result.set_date_bounds
train
def set_date_bounds(self, date): ''' Pass in the date used in the original query. :param date: Date (date range) that was queried: date -> 'd', '~d', 'd~', 'd~d' d -> '%Y-%m-%d %H:%M:%S,%f', '%Y-%m-%d %H:%M:%S', '%Y-%m-%d' ''' if date is not None: ...
python
{ "resource": "" }
q38952
Result.check_in_bounds
train
def check_in_bounds(self, date): '''Check that left and right bounds are sane :param date: date to validate left/right bounds for ''' dt = Timestamp(date) return ((self._lbound is None or dt >= self._lbound) and (self._rbound is None or dt <= self._rbound))
python
{ "resource": "" }
q38953
Result.on_date
train
def on_date(self, date, only_count=False): ''' Filters out only the rows that match the spectified date. Works only on a Result that has _start and _end columns. :param date: date can be anything Pandas.Timestamp supports parsing :param only_count: return back only the match cou...
python
{ "resource": "" }
q38954
Result.history
train
def history(self, dates=None, linreg_since=None, lin_reg_days=20): ''' Works only on a Result that has _start and _end columns. :param dates: list of dates to query :param linreg_since: estimate future values using linear regression. :param lin_reg_days: number of past days to u...
python
{ "resource": "" }
q38955
Result._linreg_future
train
def _linreg_future(self, series, since, days=20): ''' Predicts future using linear regression. :param series: A series in which the values will be places. The index will not be touched. Only the values on dates > `since` will be predicted. :param sinc...
python
{ "resource": "" }
q38956
Result.get_dates_range
train
def get_dates_range(self, scale='auto', start=None, end=None, date_max='2010-01-01'): ''' Returns a list of dates sampled according to the specified parameters. :param scale: {'auto', 'maximum', 'daily', 'weekly', 'monthly', 'quarterly', 'yearly'} ...
python
{ "resource": "" }
q38957
Result._auto_select_scale
train
def _auto_select_scale(self, start=None, end=None, ideal=300): ''' Guess what a good timeseries scale might be, given a particular data set, attempting to make the total number of x values as close to `ideal` as possible This is a helper for plotting ''' ...
python
{ "resource": "" }
q38958
Result.filter_oids
train
def filter_oids(self, oids): ''' Leaves only objects with specified oids. :param oids: list of oids to include ''' oids = set(oids) return self[self['_oid'].map(lambda x: x in oids)]
python
{ "resource": "" }
q38959
Result.unfinished_objects
train
def unfinished_objects(self): ''' Leaves only versions of those objects that has some version with `_end == None` or with `_end > right cutoff`. ''' mask = self._end_isnull if self._rbound is not None: mask = mask | (self._end > self._rbound) oids = se...
python
{ "resource": "" }
q38960
Result.last_chain
train
def last_chain(self): ''' Leaves only the last chain for each object. Chain is a series of consecutive versions where `_end` of one is `_start` of another. ''' cols = self.columns.tolist() i_oid = cols.index('_oid') i_start = cols.index('_start') ...
python
{ "resource": "" }
q38961
Result.one_version
train
def one_version(self, index=0): ''' Leaves only one version for each object. :param index: List-like index of the version. 0 == first; -1 == last ''' def prep(df): start = sorted(df._start.tolist())[index] return df[df._start == start] return pd...
python
{ "resource": "" }
q38962
Result.started_after
train
def started_after(self, date): ''' Leaves only those objects whose first version started after the specified date. :param date: date string to use in calculation ''' dt = Timestamp(date) starts = self.groupby(self._oid).apply(lambda df: df._start.min()) o...
python
{ "resource": "" }
q38963
Result.object_apply
train
def object_apply(self, function): ''' Groups by _oid, then applies the function to each group and finally concatenates the results. :param function: func that takes a DataFrame and returns a DataFrame ''' return pd.concat([function(df) for _, df in self.groupby(self._oid...
python
{ "resource": "" }
q38964
IIIVZincBlendeQuaternary._has_x
train
def _has_x(self, kwargs): '''Returns True if x is explicitly defined in kwargs''' return (('x' in kwargs) or (self._element_x in kwargs) or (self._type == 3 and self._element_1mx in kwargs))
python
{ "resource": "" }
q38965
IIIVZincBlendeQuaternary._get_x
train
def _get_x(self, kwargs): ''' Returns x if it is explicitly defined in kwargs. Otherwise, raises TypeError. ''' if 'x' in kwargs: return round(float(kwargs['x']), 6) elif self._element_x in kwargs: return round(float(kwargs[self._element_x]), 6) ...
python
{ "resource": "" }
q38966
IIIVZincBlendeQuaternary._has_y
train
def _has_y(self, kwargs): '''Returns True if y is explicitly defined in kwargs''' return (('y' in kwargs) or (self._element_y in kwargs) or (self._type == 3 and self._element_1my in kwargs))
python
{ "resource": "" }
q38967
IIIVZincBlendeQuaternary._get_y
train
def _get_y(self, kwargs): ''' Returns y if it is explicitly defined in kwargs. Otherwise, raises TypeError. ''' if 'y' in kwargs: return round(float(kwargs['y']), 6) elif self._element_y in kwargs: return round(float(kwargs[self._element_y]), 6) ...
python
{ "resource": "" }
q38968
IIIVZincBlendeQuaternary._has_z
train
def _has_z(self, kwargs): ''' Returns True if type is 1 or 2 and z is explicitly defined in kwargs. ''' return ((self._type == 1 or self._type ==2) and (('z' in kwargs) or (self._element_z in kwargs)))
python
{ "resource": "" }
q38969
IIIVZincBlendeQuaternary._get_z
train
def _get_z(self, kwargs): ''' Returns z if type is 1 or 2 and z is explicitly defined in kwargs. Otherwise, raises TypeError. ''' if self._type == 1 or self._type == 2: if 'z' in kwargs: return round(float(kwargs['z']), 6) elif self._elemen...
python
{ "resource": "" }
q38970
DatabaseObject.db
train
def db(cls, path=None): """ Returns a pymongo Collection object from the current database connection. If the database connection is in test mode, collection will be in the test database. @param path: if is None, the PATH attribute of the current class is used; ...
python
{ "resource": "" }
q38971
DatabaseObject.rename
train
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 ...
python
{ "resource": "" }
q38972
DatabaseObject.copy
train
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 attribu...
python
{ "resource": "" }
q38973
raxml_alignment
train
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 (ph...
python
{ "resource": "" }
q38974
insert_sequences_into_tree
train
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...
python
{ "resource": "" }
q38975
Raxml._format_output
train
def _format_output(self, outfile_name, out_type): """ Prepend proper output prefix to output filename """ outfile_name = self._absolute(outfile_name) outparts = outfile_name.split("/") outparts[-1] = self._out_format % (out_type, outparts[-1] ) return '/'.join(outparts)
python
{ "resource": "" }
q38976
Raxml._checkpoint_out_filenames
train
def _checkpoint_out_filenames(self): """ RAxML generates a crapload of checkpoint files so need to walk directory to collect names of all of them. """ out_filenames = [] if self.Parameters['-n'].isOn(): out_name = str(self.Parameters['-n'].Value) w...
python
{ "resource": "" }
q38977
Raxml._handle_app_result_build_failure
train
def _handle_app_result_build_failure(self,out,err,exit_status,result_paths): """ Catch the error when files are not produced """ try: raise ApplicationError, \ 'RAxML failed to produce an output file due to the following error: \n\n%s ' \ % err.read() excep...
python
{ "resource": "" }
q38978
Queue.names
train
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. """ data = None if not self.connected: raise ConnectionError('Queue is not connected') ...
python
{ "resource": "" }
q38979
Queue.length
train
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`. """ if not self.connected: raise ConnectionError('Queue is not conn...
python
{ "resource": "" }
q38980
Queue.connect
train
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 cal...
python
{ "resource": "" }
q38981
Queue.send
train
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...
python
{ "resource": "" }
q38982
Queue.find
train
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 """ if not self.connected: ...
python
{ "resource": "" }
q38983
Job.result
train
def result(self): """ Returns the result from the worker for this job. This is used to pass result in async way. """ if self.__result: return self.__result data = self.rdb.rpop(self.urn) if data: self.rdb.delete(self.urn) data =...
python
{ "resource": "" }
q38984
Job.wait
train
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...
python
{ "resource": "" }
q38985
PushConnection.messages_in_flight
train
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. """ self.prune_sent() if not self.send_queue.empty() or len(self.sent) > 0: return True return False
python
{ "resource": "" }
q38986
SQLAlchemyMiddleware.db
train
def db(self, connection_string=None): """Gets the SQLALchemy session for this request""" 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_conn...
python
{ "resource": "" }
q38987
SQLAlchemyMiddleware._sqlalchemy_on_finish
train
def _sqlalchemy_on_finish(self): """ Closes the sqlalchemy transaction. Rolls back if an error occurred. """ if hasattr(self, "_db_conns"): try: if self.get_status() >= 200 and self.get_status() <= 399: for db_conn in self._db_conns.values...
python
{ "resource": "" }
q38988
SQLAlchemyMiddleware._sqlalchemy_on_connection_close
train
def _sqlalchemy_on_connection_close(self): """ Rollsback and closes the active session, since the client disconnected before the request could be completed. """ if hasattr(self, "_db_conns"): try: for db_conn in self._db_conns.values(): ...
python
{ "resource": "" }
q38989
use_settings
train
def use_settings(**kwargs): ''' Context manager to temporarily override settings ''' from omnic import singletons singletons.settings.use_settings_dict(kwargs) yield singletons.settings.use_previous_settings()
python
{ "resource": "" }
q38990
GitHub2GitLab.add_key
train
def add_key(self): "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 ...
python
{ "resource": "" }
q38991
GitHub2GitLab.add_project
train
def add_project(self): "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 + "...
python
{ "resource": "" }
q38992
GitHub2GitLab.unprotect_branches
train
def unprotect_branches(self): "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...
python
{ "resource": "" }
q38993
GitHub2GitLab.json_loads
train
def json_loads(payload): "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
python
{ "resource": "" }
q38994
SeqPrep._unassembled_reads1_out_file_name
train
def _unassembled_reads1_out_file_name(self): """Checks file name is set for reads1 output. Returns absolute path.""" if self.Parameters['-1'].isOn(): unassembled_reads1 = self._absolute( str(self.Parameters['-1'].Value)) else: raise ValueError("...
python
{ "resource": "" }
q38995
SeqPrep._unassembled_reads2_out_file_name
train
def _unassembled_reads2_out_file_name(self): """Checks if file name is set for reads2 output. Returns absolute path.""" if self.Parameters['-2'].isOn(): unassembled_reads2 = self._absolute( str(self.Parameters['-2'].Value)) else: raise ValueErro...
python
{ "resource": "" }
q38996
SeqPrep._discarded_reads1_out_file_name
train
def _discarded_reads1_out_file_name(self): """Checks if file name is set for discarded reads1 output. Returns absolute path.""" if self.Parameters['-3'].isOn(): discarded_reads1 = self._absolute(str(self.Parameters['-3'].Value)) else: raise ValueError( ...
python
{ "resource": "" }
q38997
SeqPrep._discarded_reads2_out_file_name
train
def _discarded_reads2_out_file_name(self): """Checks if file name is set for discarded reads2 output. Returns absolute path.""" if self.Parameters['-4'].isOn(): discarded_reads2 = self._absolute(str(self.Parameters['-4'].Value)) else: raise ValueError( ...
python
{ "resource": "" }
q38998
SeqPrep._assembled_out_file_name
train
def _assembled_out_file_name(self): """Checks file name is set for assembled output. Returns absolute path.""" if self.Parameters['-s'].isOn(): assembled_reads = self._absolute(str(self.Parameters['-s'].Value)) else: raise ValueError( "No assemb...
python
{ "resource": "" }
q38999
SeqPrep._pretty_alignment_out_file_name
train
def _pretty_alignment_out_file_name(self): """Checks file name is set for pretty alignment output. Returns absolute path.""" if self.Parameters['-E'].isOn(): pretty_alignment = self._absolute(str(self.Parameters['-E'].Value)) else: raise ValueError( ...
python
{ "resource": "" }