_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q44800 | setup_app | train | def setup_app(command, conf, vars):
"""Place any commands to setup tg2raptorized here"""
load_environment(conf.global_conf, conf.local_conf)
setup_schema(command, conf, vars)
bootstrap.bootstrap(command, conf, vars) | python | {
"resource": ""
} |
q44801 | VocationFilter.from_name | train | def from_name(cls, name, all_fallback=True):
"""Gets a vocation filter from a vocation's name.
Parameters
----------
name: :class:`str`
The name of the vocation.
all_fallback: :class:`bool`
Whether to return :py:attr:`ALL` if no match is found. Otherwise,... | python | {
"resource": ""
} |
q44802 | connect | train | def connect(*args, **kwargs):
"""Connect to the database. Passes arguments along to
``pymongo.connection.Connection`` unmodified.
The Connection returned by this proxy method will be used by micromongo
for all of its queries. Micromongo will alter the behavior of this
conneciton object in some su... | python | {
"resource": ""
} |
q44803 | Model.new | train | def new(cls, *args, **kwargs):
"""Create a new instance of this model based on its spec and either
a map or the provided kwargs."""
new = cls(make_default(getattr(cls, 'spec', {})))
new.update(args[0] if args and not kwargs else kwargs)
return new | python | {
"resource": ""
} |
q44804 | Model.find_one | train | def find_one(cls, *args, **kwargs):
"""Run a find_one on this model's collection. The arguments to
``Model.find_one`` are the same as to ``pymongo.Collection.find_one``."""
database, collection = cls._collection_key.split('.')
return current()[database][collection].find_one(*args, **kwa... | python | {
"resource": ""
} |
q44805 | apply | train | def apply(query, collection=None):
"""Enhance the query restricting not permitted collections.
Get the permitted restricted collection for the current user from the
user_info object and all the restriced collections from the
restricted_collection_cache.
"""
if not collection:
return que... | python | {
"resource": ""
} |
q44806 | SinonSpy.calledBefore | train | def calledBefore(self, spy): #pylint: disable=invalid-name
"""
Compares the order in which two spies were called
E.g.
spy_a()
spy_b()
spy_a.calledBefore(spy_b) # True
spy_b.calledBefore(spy_a) # False
spy_a()
spy_b.calledBe... | python | {
"resource": ""
} |
q44807 | SinonSpy.reset | train | def reset(self):
"""
Reseting wrapped function
"""
super(SinonSpy, self).unwrap()
super(SinonSpy, self).wrap2spy() | python | {
"resource": ""
} |
q44808 | b64decode | train | def b64decode(foo, *args):
'Only here for consistency with the above.'
if isinstance(foo, str):
foo = foo.encode('utf8')
return base64.b64decode(foo, *args) | python | {
"resource": ""
} |
q44809 | UserLock.from_passphrase | train | def from_passphrase(cls, email, passphrase):
"""
This performs key derivation from an email address and passphrase according
to the miniLock specification.
Specifically, the passphrase is digested with a standard blake2s 32-bit digest,
then it is passed through scrypt wi... | python | {
"resource": ""
} |
q44810 | UserLock.from_id | train | def from_id(cls, id):
"""
This decodes an ID to a public key and verifies the checksum byte. ID
structure in miniLock is the base58 encoded form of the public key
appended with a single-byte digest from blake2s of the public key, as a
simple check-sum.
"""
decoded... | python | {
"resource": ""
} |
q44811 | UserLock.ephemeral | train | def ephemeral(cls):
"""
Creates a new ephemeral key constructed using a raw 32-byte string from urandom.
Ephemeral keys are used once for each encryption task and are then discarded;
they are not intended for long-term or repeat use.
"""
private_key = nacl.public.PrivateK... | python | {
"resource": ""
} |
q44812 | SymmetricMiniLock.piece_file | train | def piece_file(input_f, chunk_size):
"""
Provides a streaming interface to file data in chunks of even size, which
avoids memoryerrors from loading whole files into RAM to pass to `pieces`.
"""
chunk = input_f.read(chunk_size)
total_bytes = 0
while chunk:
... | python | {
"resource": ""
} |
q44813 | MiniLockHeader.decrypt | train | def decrypt(self, recipient_key):
"""
Attempt decryption of header with a private key; returns decryptInfo.
Returns a dictionary, not a new MiniLockHeader!
"""
ephem = UserLock.from_b64(self.dict['ephemeral'])
ephem_box = nacl.public.Box(recipient_key.private_key, ephem.p... | python | {
"resource": ""
} |
q44814 | unique_index | train | def unique_index(data, keys=None, fail_on_dup=True):
"""
RETURN dict THAT USES KEYS TO INDEX DATA
ONLY ONE VALUE ALLOWED PER UNIQUE KEY
"""
o = UniqueIndex(listwrap(keys), fail_on_dup=fail_on_dup)
for d in data:
try:
o.add(d)
except Exception as e:
o.add(... | python | {
"resource": ""
} |
q44815 | tuple | train | def tuple(data, field_name):
"""
RETURN LIST OF TUPLES
"""
if isinstance(data, Cube):
Log.error("not supported yet")
if isinstance(data, FlatList):
Log.error("not supported yet")
if is_data(field_name) and "value" in field_name:
# SIMPLIFY {"value":value} AS STRING
... | python | {
"resource": ""
} |
q44816 | select | train | def select(data, field_name):
"""
return list with values from field_name
"""
if isinstance(data, Cube):
return data._select(_normalize_selects(field_name))
if isinstance(data, PartFlatList):
return data.select(field_name)
if isinstance(data, UniqueIndex):
data = (
... | python | {
"resource": ""
} |
q44817 | wrap_function | train | def wrap_function(func):
"""
RETURN A THREE-PARAMETER WINDOW FUNCTION TO MATCH
"""
if is_text(func):
return compile_expression(func)
numarg = func.__code__.co_argcount
if numarg == 0:
def temp(row, rownum, rows):
return func()
return temp
elif numarg ==... | python | {
"resource": ""
} |
q44818 | get_context_hints_per_source | train | def get_context_hints_per_source(context_renderers):
"""
Given a list of context renderers, return a dictionary of context hints per source.
"""
# Merge the context render hints for each source as there can be multiple context hints for
# sources depending on the render target. Merging them together... | python | {
"resource": ""
} |
q44819 | dict_find | train | def dict_find(d, which_key):
"""
Finds key values in a nested dictionary. Returns a tuple of the dictionary in which
the key was found along with the value
"""
# If the starting point is a list, iterate recursively over all values
if isinstance(d, (list, tuple)):
for i in d:
... | python | {
"resource": ""
} |
q44820 | fetch_model_data | train | def fetch_model_data(model_querysets, model_ids_to_fetch):
"""
Given a dictionary of models to querysets and model IDs to models, fetch the IDs
for every model and return the objects in the following structure.
{
model: {
id: obj,
...
},
...
}
"""... | python | {
"resource": ""
} |
q44821 | load_fetched_objects_into_contexts | train | def load_fetched_objects_into_contexts(events, model_data, context_hints_per_source):
"""
Given the fetched model data and the context hints for each source, go through each
event and populate the contexts with the loaded information.
"""
for event in events:
context_hints = context_hints_pe... | python | {
"resource": ""
} |
q44822 | load_renderers_into_events | train | def load_renderers_into_events(events, mediums, context_renderers, default_rendering_style):
"""
Given the events and the context renderers, load the renderers into the event objects
so that they may be able to call the 'render' method later on.
"""
# Make a mapping of source groups and rendering st... | python | {
"resource": ""
} |
q44823 | load_contexts_and_renderers | train | def load_contexts_and_renderers(events, mediums):
"""
Given a list of events and mediums, load the context model data into the contexts of the events.
"""
sources = {event.source for event in events}
rendering_styles = {medium.rendering_style for medium in mediums if medium.rendering_style}
# F... | python | {
"resource": ""
} |
q44824 | get_printer | train | def get_printer(colors: bool = True, width_limit: bool = True, disabled: bool = False) -> Printer:
"""
Returns an already initialized instance of the printer.
:param colors: If False, no colors will be printed.
:param width_limit: If True, printing width will be limited by console width.
:param dis... | python | {
"resource": ""
} |
q44825 | _get_windows_console_width | train | def _get_windows_console_width() -> int:
"""
A small utility function for getting the current console window's width, in Windows.
:return: The current console window's width.
"""
from ctypes import byref, windll
import pyreadline
out = windll.kernel32.GetStdHandle(-11)
info = pyreadlin... | python | {
"resource": ""
} |
q44826 | _in_qtconsole | train | def _in_qtconsole() -> bool:
"""
A small utility function which determines if we're running in QTConsole's context.
"""
try:
from IPython import get_ipython
try:
from ipykernel.zmqshell import ZMQInteractiveShell
shell_object = ZMQInteractiveShell
except I... | python | {
"resource": ""
} |
q44827 | get_console_width | train | def get_console_width() -> int:
"""
A small utility function for getting the current console window's width.
:return: The current console window's width.
"""
# Assigning the value once, as frequent call to this function
# causes a major slow down(ImportErrors + isinstance).
global _IN_QT
... | python | {
"resource": ""
} |
q44828 | Printer.group | train | def group(self, indent: int = DEFAULT_INDENT, add_line: bool = True) -> _TextGroup:
"""
Returns a context manager which adds an indentation before each line.
:param indent: Number of spaces to print.
:param add_line: If True, a new line will be printed after the group.
:return: ... | python | {
"resource": ""
} |
q44829 | Printer._split_lines | train | def _split_lines(self, original_lines: List[str]) -> List[str]:
"""
Splits the original lines list according to the current console width and group indentations.
:param original_lines: The original lines list to split.
:return: A list of the new width-formatted lines.
"""
... | python | {
"resource": ""
} |
q44830 | Printer.write | train | def write(self, text: str):
"""
Prints text to the screen.
Supports colors by using the color constants.
To use colors, add the color before the text you want to print.
:param text: The text to print.
"""
# Default color is NORMAL.
last_color = (self._DAR... | python | {
"resource": ""
} |
q44831 | Printer.write_aligned | train | def write_aligned(self, key: str, value: str, not_important_keys: Optional[List[str]] = None,
is_list: bool = False, align_size: Optional[int] = None, key_color: str = PURPLE,
value_color: str = GREEN, dark_key_color: str = DARK_PURPLE, dark_value_color: str = DARK_GREEN,
... | python | {
"resource": ""
} |
q44832 | Printer.write_title | train | def write_title(self, title: str, title_color: str = YELLOW, hyphen_line_color: str = WHITE):
"""
Prints title with hyphen line underneath it.
:param title: The title to print.
:param title_color: The title text color (default is yellow).
:param hyphen_line_color: The hyphen lin... | python | {
"resource": ""
} |
q44833 | generate_pos_tagger | train | def generate_pos_tagger(check_accuracy=False):
"""Accuracy is about 0.94 with 90% training data."""
global tagger
logging.debug("Reading TIGER corpus")
corp = nltk.corpus.ConllCorpusReader(DIR_PATH, TIGER_FILE_NAME,
['ignore', 'words', 'ignore', 'ignore', 'pos'],... | python | {
"resource": ""
} |
q44834 | make_lock_securely | train | def make_lock_securely(email = None, warn_only = False):
"Terminal oriented; produces a prompt for user input of email and password. Returns crypto.UserLock."
email = email or input("Please provide email address: ")
while True:
passphrase = getpass.getpass("Please type a secure passphrase (with spac... | python | {
"resource": ""
} |
q44835 | encrypt_file | train | def encrypt_file(file_path, sender, recipients):
"Returns encrypted binary file content if successful"
for recipient_key in recipients:
crypto.assert_type_and_length('recipient_key', recipient_key, (str, crypto.UserLock))
crypto.assert_type_and_length("sender_key", sender, crypto.UserLock)
if (n... | python | {
"resource": ""
} |
q44836 | encrypt_folder | train | def encrypt_folder(path, sender, recipients):
"""
This helper function should zip the contents of a folder and encrypt it as
a zip-file. Recipients are responsible for opening the zip-file.
"""
for recipient_key in recipients:
crypto.assert_type_and_length('recipient_key', recipient_key, (st... | python | {
"resource": ""
} |
q44837 | get_profile | train | def get_profile(A):
"Fail-soft profile getter; if no profile is present assume none and quietly ignore."
try:
with open(os.path.expanduser(A.profile)) as I:
profile = json.load(I)
return profile
except:
return {} | python | {
"resource": ""
} |
q44838 | main_encrypt | train | def main_encrypt(A):
"Encrypt to recipient list using primary key OR prompted key. Recipients may be IDs or petnames."
profile = get_profile(A)
localKeys = profile.get('local keys', [])
if not localKeys:
localKeys = [make_lock_securely(warn_only = A.ignore_entropy)]
else:
localKeys =... | python | {
"resource": ""
} |
q44839 | main_decrypt | train | def main_decrypt(A):
"Get all local keys OR prompt user for key, then attempt to decrypt with each."
profile = get_profile(A)
localKeys = profile.get('local keys', [])
if not localKeys:
localKeys = [make_lock_securely(warn_only = A.ignore_entropy)]
else:
localKeys = [crypto.UserLock.... | python | {
"resource": ""
} |
q44840 | collection | train | def collection(name=None):
"""Render the collection page.
It renders it either with a collection specific template (aka
collection_{collection_name}.html) or with the default collection
template (collection.html).
"""
if name is None:
collection = Collection.query.get_or_404(1)
else... | python | {
"resource": ""
} |
q44841 | Highscores.from_tibiadata | train | def from_tibiadata(cls, content, vocation=None):
"""Builds a highscores object from a TibiaData highscores response.
Notes
-----
Since TibiaData.com's response doesn't contain any indication of the vocation filter applied,
:py:attr:`vocation` can't be determined from the respons... | python | {
"resource": ""
} |
q44842 | transform | train | def transform(string, transliterations=None):
"""
Transform the string to "upside-down" writing.
Example:
>>> import upsidedown
>>> print(upsidedown.transform('Hello World!'))
¡pꞁɹoM oꞁꞁǝH
For languages with diacritics you might want to supply a transliteration to
work aro... | python | {
"resource": ""
} |
q44843 | main | train | def main():
"""Main method for running upsidedown.py from the command line."""
import sys
output = []
line = sys.stdin.readline()
while line:
line = line.strip("\n")
output.append(transform(line))
line = sys.stdin.readline()
output.reverse()
print("\n".join(output)... | python | {
"resource": ""
} |
q44844 | capture_termination_signal | train | def capture_termination_signal(please_stop):
"""
WILL SIGNAL please_stop WHEN THIS AWS INSTANCE IS DUE FOR SHUTDOWN
"""
def worker(please_stop):
seen_problem = False
while not please_stop:
request_time = (time.time() - timer.START)/60 # MINUTES
try:
... | python | {
"resource": ""
} |
q44845 | SinonMock.restore | train | def restore(self):
"""
Destroy all inspectors in exp_list and SinonMock itself
"""
for expectation in self.exp_list:
try:
expectation.restore()
except ReferenceError:
pass #ignore removed expectation
self._queue.remove(self) | python | {
"resource": ""
} |
q44846 | execute_by_options | train | def execute_by_options(args):
"""execute by argument dictionary
Args:
args (dict): command line argument dictionary
"""
if args['subcommand'] == 'sphinx':
s = Sphinx(proj_info)
if args['quickstart']:
s.quickstart()
elif args['gen_code_api']:
s.ge... | python | {
"resource": ""
} |
q44847 | Editor.editline_with_regex | train | def editline_with_regex(self, regex_tgtline, to_replace):
"""find the first matched line, then replace
Args:
regex_tgtline (str): regular expression used to match the target line
to_replace (str): line you wanna use to replace
"""
for idx, line in enumerate(s... | python | {
"resource": ""
} |
q44848 | SinonStub.onCall | train | def onCall(self, n): #pylint: disable=invalid-name
"""
Adds a condition for when the stub is called. When the condition is met, a special
return value can be returned. Adds the specified call number into the condition
list.
For example, when the stub function is called the secon... | python | {
"resource": ""
} |
q44849 | _SinonStubCondition.returns | train | def returns(self, obj):
"""
Customizes the return values of the stub function. If conditions like withArgs or onCall
were specified, then the return value will only be returned when the conditions are met.
Args: obj (anything)
Return: a SinonStub object (able to be chained)
... | python | {
"resource": ""
} |
q44850 | assign_operation_ids | train | def assign_operation_ids(spec, operids):
""" used to assign caller provided operationId values into a spec """
empty_dict = {}
for path_name, path_data in six.iteritems(spec['paths']):
for method, method_data in six.iteritems(path_data):
oper_id = operids.get(path_name, empty_dict).get... | python | {
"resource": ""
} |
q44851 | Table.pretty_print | train | def pretty_print(self, printer: Optional[Printer] = None, align: int = ALIGN_CENTER, border: bool = False):
"""
Pretty prints the table.
:param printer: The printer to print with.
:param align: The alignment of the cells(Table.ALIGN_CENTER/ALIGN_LEFT/ALIGN_RIGHT)
:param border: ... | python | {
"resource": ""
} |
q44852 | Table.rows | train | def rows(self) -> List[List[str]]:
"""
Returns the table rows.
"""
return [list(d.values()) for d in self.data] | python | {
"resource": ""
} |
q44853 | Table.set_column_size_limit | train | def set_column_size_limit(self, column_name: str, size_limit: int):
"""
Sets the size limit of a specific column.
:param column_name: The name of the column to change.
:param size_limit: The max size of the column width.
"""
if self._column_size_map.get(column_name):
... | python | {
"resource": ""
} |
q44854 | Table.get_as_html | train | def get_as_html(self) -> str:
"""
Returns the table object as an HTML string.
:return: HTML representation of the table.
"""
table_string = self._get_pretty_table().get_html_string()
title = ('{:^' + str(len(table_string.splitlines()[0])) + '}').format(self.title)
... | python | {
"resource": ""
} |
q44855 | Table.get_as_csv | train | def get_as_csv(self, output_file_path: Optional[str] = None) -> str:
"""
Returns the table object as a CSV string.
:param output_file_path: The output file to save the CSV to, or None.
:return: CSV representation of the table.
"""
output = StringIO() if not output_file_p... | python | {
"resource": ""
} |
q44856 | Schedulable.schedule | train | def schedule(self, when=None, action=None, **kwargs):
"""
Schedule an update of this object.
when: The date for the update.
action: if provided it will be looked up
on the implementing class and called with
**kwargs. If action is not provided each k/v pair
in kw... | python | {
"resource": ""
} |
q44857 | Schedulable.do_scheduled_update | train | def do_scheduled_update(self, action, **kwargs):
"""
Do the actual update.
action: if provided it will be looked up
on the implementing class and called with
**kwargs. If action is not provided each k/v pair
in kwargs will be set on self and then self
is saved.
... | python | {
"resource": ""
} |
q44858 | get_md5_hash | train | def get_md5_hash(file_path):
"""
Calculate the MD5 checksum for a file.
:param string file_path:
Path to the file
:return:
MD5 checksum
"""
checksum = hashlib.md5()
with open(file_path, 'rb') as f:
for chunk in iter(lambda: f.read(128 * checksum.block_size), b''):
... | python | {
"resource": ""
} |
q44859 | FileRecordSearch.as_dict | train | def as_dict(self):
"""
Convert this FileRecordSearch to a dict, ready for serialization to JSON for use in the API.
:return:
Dict representation of this FileRecordSearch instance
"""
d = {}
_add_value(d, 'obstory_ids', self.obstory_ids)
_add_value(d, ... | python | {
"resource": ""
} |
q44860 | FileRecordSearch.from_dict | train | def from_dict(d):
"""
Builds a new instance of FileRecordSearch from a dict
:param Object d: the dict to parse
:return: a new FileRecordSearch based on the supplied dict
"""
obstory_ids = _value_from_dict(d, 'obstory_ids')
lat_min = _value_from_dict(d, 'lat_min')... | python | {
"resource": ""
} |
q44861 | ObservationGroupSearch.as_dict | train | def as_dict(self):
"""
Convert this ObservationGroupSearch to a dict, ready for serialization to JSON for use in the API.
:return:
Dict representation of this ObservationGroupSearch instance
"""
d = {}
_add_string(d, 'obstory_name', self.obstory_name)
... | python | {
"resource": ""
} |
q44862 | ObservatoryMetadataSearch.as_dict | train | def as_dict(self):
"""
Convert this ObservatoryMetadataSearch to a dict, ready for serialization to JSON for use in the API.
:return:
Dict representation of this ObservatoryMetadataSearch instance
"""
d = {}
_add_value(d, 'obstory_ids', self.obstory_ids)
... | python | {
"resource": ""
} |
q44863 | ObservatoryMetadata.type | train | def type(self):
"""Returns 'number', 'string', 'date' or 'unknown' based on the type of the value"""
if isinstance(self.value, numbers.Number):
return "number"
if isinstance(self.value, basestring):
return "string"
return "unknown" | python | {
"resource": ""
} |
q44864 | RiffIndexList.find | train | def find(self, header, list_type=None):
"""Find the first chunk with specified header and optional list type."""
for chunk in self:
if chunk.header == header and (list_type is None or (header in
list_headers and chunk.type == list_type)):
return chunk
... | python | {
"resource": ""
} |
q44865 | RiffIndexList.find_all | train | def find_all(self, header, list_type=None):
"""Find all direct children with header and optional list type."""
found = []
for chunk in self:
if chunk.header == header and (not list_type or (header in
list_headers and chunk.type == list_type)):
found.ap... | python | {
"resource": ""
} |
q44866 | RiffIndexList.replace | train | def replace(self, child, replacement):
"""Replace a child chunk with something else."""
for i in range(len(self.chunks)):
if self.chunks[i] == child:
self.chunks[i] = replacement | python | {
"resource": ""
} |
q44867 | RiffIndexList.remove | train | def remove(self, child):
"""Remove a child element."""
for i in range(len(self)):
if self[i] == child:
del self[i] | python | {
"resource": ""
} |
q44868 | RiffDataChunk.from_data | train | def from_data(data):
"""Create a chunk from data including header and length bytes."""
header, length = struct.unpack('4s<I', data[:8])
data = data[8:]
return RiffDataChunk(header, data) | python | {
"resource": ""
} |
q44869 | AdminMixin.get_urls | train | def get_urls(self):
"""Add our dashboard view to the admin urlconf. Deleted the default index."""
from django.conf.urls import patterns, url
from views import DashboardWelcomeView
urls = super(AdminMixin, self).get_urls()
del urls[0]
custom_url = patterns(
''... | python | {
"resource": ""
} |
q44870 | index_to_coordinate | train | def index_to_coordinate(dims):
"""
RETURN A FUNCTION THAT WILL TAKE AN INDEX, AND MAP IT TO A coordinate IN dims
:param dims: TUPLE WITH NUMBER OF POINTS IN EACH DIMENSION
:return: FUNCTION
"""
_ = divmod # SO WE KEEP THE IMPORT
num_dims = len(dims)
if num_dims == 0:
return _z... | python | {
"resource": ""
} |
q44871 | Matrix.groupby | train | def groupby(self, io_select):
"""
SLICE THIS MATRIX INTO ONES WITH LESS DIMENSIONALITY
io_select - 1 IF GROUPING BY THIS DIMENSION, 0 IF FLATTENING
return -
"""
# offsets WILL SERVE TO MASK DIMS WE ARE NOT GROUPING BY, AND SERVE AS RELATIVE INDEX FOR EACH COORDINATE
... | python | {
"resource": ""
} |
q44872 | Matrix.items | train | def items(self):
"""
ITERATE THROUGH ALL coord, value PAIRS
"""
for c in self._all_combos():
_, value = _getitem(self.cube, c)
yield c, value | python | {
"resource": ""
} |
q44873 | Matrix._all_combos | train | def _all_combos(self):
"""
RETURN AN ITERATOR OF ALL COORDINATES
"""
combos = _product(self.dims)
if not combos:
return
calc = [(coalesce(_product(self.dims[i+1:]), 1), mm) for i, mm in enumerate(self.dims)]
for c in xrange(combos):
yield... | python | {
"resource": ""
} |
q44874 | Publisher.send | train | def send(self, topic, message):
"""Publishes a pulse message to the proper exchange."""
if not message:
Log.error("Expecting a message")
message._prepare()
if not self.connection:
self.connect()
producer = Producer(
channel=self.connection,... | python | {
"resource": ""
} |
q44875 | Extends.add_child | train | def add_child(self, child):
"""
Add a child to the tree. Extends discards all comments
and whitespace Text. On non-whitespace Text, and any
other nodes, raise a syntax error.
"""
if isinstance(child, Comment):
return
# ignore Text nodes with whitespa... | python | {
"resource": ""
} |
q44876 | MeteorExporter.handle_next_export | train | def handle_next_export(self):
"""
Retrieve and fully evaluate the next export task, including resolution of any sub-tasks requested by the
import client such as requests for binary data, observation, etc.
:return:
An instance of ExportStateCache, the 'state' field contains t... | python | {
"resource": ""
} |
q44877 | MeteorExporter._handle_next_export_subtask | train | def _handle_next_export_subtask(self, export_state=None):
"""
Process the next export sub-task, if there is one.
:param ExportState export_state:
If provided, this is used instead of the database queue, in effect directing the exporter to process the
previous export agai... | python | {
"resource": ""
} |
q44878 | extract_options_dict | train | def extract_options_dict(template, options):
"""Extract options from a dictionary against the template"""
for option, val in template.items():
if options and option in options:
yield option, options[option]
else:
yield option, Default(template[option]['default'](os.enviro... | python | {
"resource": ""
} |
q44879 | VersionedProjectState.from_apps | train | def from_apps(cls, apps):
"Takes in an Apps and returns a VersionedProjectState matching it"
app_models = {}
for model in apps.get_models(include_swapped=True):
model_state = VersionedModelState.from_model(model)
app_models[(model_state.app_label, model_state.name.lower()... | python | {
"resource": ""
} |
q44880 | AssetManager.search_tags | train | def search_tags(self, tags):
"""
Search assets by passing a list of one or more tags.
"""
qs = self.filter(tags__name__in=tags).order_by('file').distinct()
return qs | python | {
"resource": ""
} |
q44881 | Cloneable._gather_reverses | train | def _gather_reverses(self):
"""
Get all the related objects that point to this
object that we need to clone. Uses self.clone_related
to find those objects.
"""
old_reverses = {'m2m': {}, 'reverse': {}}
for reverse in self.clone_related:
ctype, name, l... | python | {
"resource": ""
} |
q44882 | Cloneable._set_m2ms | train | def _set_m2ms(self, old_m2ms):
"""
Creates the same m2m relationships that the old
object had.
"""
for k, v in old_m2ms.items():
if v:
setattr(self, k, v) | python | {
"resource": ""
} |
q44883 | Cloneable._clone_reverses | train | def _clone_reverses(self, old_reverses):
"""
Clones all the objects that were previously gathered.
"""
for ctype, reverses in old_reverses.items():
for parts in reverses.values():
sub_objs = parts[1]
field_name = parts[0]
attr... | python | {
"resource": ""
} |
q44884 | Cloneable._clone | train | def _clone(self, **attrs):
"""
Makes a copy of an model instance.
for every key in **attrs value will
be set on the new instance.
"""
with xact():
# Gather objs we'll need save after
old_m2ms = self._gather_m2ms()
old_reverses = self.... | python | {
"resource": ""
} |
q44885 | Cloneable._delete_reverses | train | def _delete_reverses(self):
"""
Delete all objects that would have been cloned
on a clone command. This is done separately because
there may be m2m and other relationships that
would have not been deleted otherwise.
"""
for reverse in self.clone_related:
... | python | {
"resource": ""
} |
q44886 | Cloneable.delete | train | def delete(self, *args, **kwargs):
"""
Delete clonable relations first, since they may be
objects that wouldn't otherwise be deleted.
Calls super to actually delete the object.
"""
skip_reverses = kwargs.pop('skip_reverses', False)
if not skip_reverses:
... | python | {
"resource": ""
} |
q44887 | Cloneable.register_related | train | def register_related(cls, related_name):
"""
Register a related item that should be cloned
when this model is.
:param related_name: Use the name you would use in filtering
i.e.: book not book_set.
"""
if not hasattr(cls, '_clone_related'):
cls._c... | python | {
"resource": ""
} |
q44888 | BaseModel.get_version | train | def get_version(self, state=None, date=None):
"""
Get a particular version of an item
:param state: The state you want to get.
:param date: Get a version that was published before or on this date.
"""
version_model = self._meta._version_model
q = version_model.o... | python | {
"resource": ""
} |
q44889 | BaseVersionedModel.unpublish | train | def unpublish(self):
"""
Unpublish this item.
This will set and currently published versions to
the archived state and delete all currently scheduled
versions.
"""
assert self.state == self.DRAFT
with xact():
self._publish(published=False)
... | python | {
"resource": ""
} |
q44890 | BaseVersionedModel.publish | train | def publish(self, user=None, when=None):
"""
Publishes a item and any sub items.
A new transaction will be started if
we aren't already in a transaction.
Should only be run on draft items
"""
assert self.state == self.DRAFT
user_published = 'code'
... | python | {
"resource": ""
} |
q44891 | BaseVersionedModel.make_draft | train | def make_draft(self):
"""
Make this version the draft
"""
assert self.__class__ == self.get_version_class()
# If this is draft do nothing
if self.state == self.DRAFT:
return
with xact():
# Delete whatever is currently this draft
... | python | {
"resource": ""
} |
q44892 | BaseVersionedModel.purge_archives | train | def purge_archives(self):
"""
Delete older archived items.
Use the class attribute NUM_KEEP_ARCHIVED to control
how many items are kept.
"""
klass = self.get_version_class()
qs = klass.normal.filter(object_id=self.object_id,
stat... | python | {
"resource": ""
} |
q44893 | BaseVersionedModel.status_line | train | def status_line(self):
"""
Returns a status line for an item.
Only really interesting when called for a draft
item as it can tell you if the draft is the same as
another version.
"""
date = self.date_published
status = self.state.title()
if self.... | python | {
"resource": ""
} |
q44894 | BaseVersionedModel.schedule | train | def schedule(self, when=None, action=None, **kwargs):
"""
Schedule this item to be published.
:param when: Date/time when this item should go live. None means now.
"""
action = '_publish'
super(BaseVersionedModel, self).schedule(when=when, action=action,
... | python | {
"resource": ""
} |
q44895 | VersionModel.save | train | def save(self, *args, **kwargs):
"""
Saves this item.
Creates a default base if there isn't
one already.
"""
with xact():
if not self.vid:
self.state = self.DRAFT
if not self.object_id:
base = self._meta._b... | python | {
"resource": ""
} |
q44896 | parser | train | def parser():
"""Return search query parser."""
query_parser = current_app.config['COLLECTIONS_QUERY_PARSER']
if isinstance(query_parser, six.string_types):
query_parser = import_string(query_parser)
return query_parser | python | {
"resource": ""
} |
q44897 | query_walkers | train | def query_walkers():
"""Return query walker instances."""
return [
import_string(walker)() if isinstance(walker, six.string_types)
else walker() for walker in current_app.config[
'COLLECTIONS_QUERY_WALKERS']
] | python | {
"resource": ""
} |
q44898 | AESCipher.pad | train | def pad(cls, data):
"""
Pads data to match AES block size
"""
if sys.version_info > (3, 0):
try:
data = data.encode("utf-8")
except AttributeError:
pass
length = AES.block_size - (len(data) % AES.block_size)
... | python | {
"resource": ""
} |
q44899 | AESCipher.unpad | train | def unpad(cls, data):
"""
Unpads data that has been padded
"""
if sys.version_info > (3, 0):
return data[:-ord(data[len(data)-1:])].decode()
else:
return data[:-ord(data[len(data)-1:])] | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.