_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q4000 | DjangoFaker.lorem | train | def lorem(self, field=None, val=None):
"""
Returns lorem ipsum text. If val is provided, the lorem ipsum text will
be the same length as the original text, and with the same pattern of
line breaks.
"""
if val == '':
return ''
if val is not None:
... | python | {
"resource": ""
} |
q4001 | DjangoFaker.unique_lorem | train | def unique_lorem(self, field=None, val=None):
"""
Returns lorem ipsum text guaranteed to be unique. First uses lorem function
then adds a unique integer suffix.
"""
lorem_text = self.lorem(field, val)
max_length = getattr(field, 'max_length', None)
suffix_str = s... | python | {
"resource": ""
} |
q4002 | Anonymizer.alter_object | train | def alter_object(self, obj):
"""
Alters all the attributes in an individual object.
If it returns False, the object will not be saved
"""
for attname, field, replacer in self.replacers:
currentval = getattr(obj, attname)
replacement = replacer(self, obj, ... | python | {
"resource": ""
} |
q4003 | uuid | train | def uuid(anon, obj, field, val):
"""
Returns a random uuid string
"""
return anon.faker.uuid(field=field) | python | {
"resource": ""
} |
q4004 | varchar | train | def varchar(anon, obj, field, val):
"""
Returns random data for a varchar field.
"""
return anon.faker.varchar(field=field) | python | {
"resource": ""
} |
q4005 | datetime | train | def datetime(anon, obj, field, val):
"""
Returns a random datetime
"""
return anon.faker.datetime(field=field) | python | {
"resource": ""
} |
q4006 | date | train | def date(anon, obj, field, val):
"""
Returns a random date
"""
return anon.faker.date(field=field) | python | {
"resource": ""
} |
q4007 | decimal | train | def decimal(anon, obj, field, val):
"""
Returns a random decimal
"""
return anon.faker.decimal(field=field) | python | {
"resource": ""
} |
q4008 | country | train | def country(anon, obj, field, val):
"""
Returns a randomly selected country.
"""
return anon.faker.country(field=field) | python | {
"resource": ""
} |
q4009 | username | train | def username(anon, obj, field, val):
"""
Generates a random username
"""
return anon.faker.user_name(field=field) | python | {
"resource": ""
} |
q4010 | first_name | train | def first_name(anon, obj, field, val):
"""
Returns a random first name
"""
return anon.faker.first_name(field=field) | python | {
"resource": ""
} |
q4011 | last_name | train | def last_name(anon, obj, field, val):
"""
Returns a random second name
"""
return anon.faker.last_name(field=field) | python | {
"resource": ""
} |
q4012 | email | train | def email(anon, obj, field, val):
"""
Generates a random email address.
"""
return anon.faker.email(field=field) | python | {
"resource": ""
} |
q4013 | similar_email | train | def similar_email(anon, obj, field, val):
"""
Generate a random email address using the same domain.
"""
return val if 'betterworks.com' in val else '@'.join([anon.faker.user_name(field=field), val.split('@')[-1]]) | python | {
"resource": ""
} |
q4014 | full_address | train | def full_address(anon, obj, field, val):
"""
Generates a random full address, using newline characters between the lines.
Resembles a US address
"""
return anon.faker.address(field=field) | python | {
"resource": ""
} |
q4015 | phonenumber | train | def phonenumber(anon, obj, field, val):
"""
Generates a random US-style phone number
"""
return anon.faker.phone_number(field=field) | python | {
"resource": ""
} |
q4016 | street_address | train | def street_address(anon, obj, field, val):
"""
Generates a random street address - the first line of a full address
"""
return anon.faker.street_address(field=field) | python | {
"resource": ""
} |
q4017 | state | train | def state(anon, obj, field, val):
"""
Returns a randomly selected US state code
"""
return anon.faker.state(field=field) | python | {
"resource": ""
} |
q4018 | company | train | def company(anon, obj, field, val):
"""
Generates a random company name
"""
return anon.faker.company(field=field) | python | {
"resource": ""
} |
q4019 | lorem | train | def lorem(anon, obj, field, val):
"""
Generates a paragraph of lorem ipsum text
"""
return ' '.join(anon.faker.sentences(field=field)) | python | {
"resource": ""
} |
q4020 | unique_lorem | train | def unique_lorem(anon, obj, field, val):
"""
Generates a unique paragraph of lorem ipsum text
"""
return anon.faker.unique_lorem(field=field) | python | {
"resource": ""
} |
q4021 | choice | train | def choice(anon, obj, field, val):
"""
Randomly chooses one of the choices set on the field.
"""
return anon.faker.choice(field=field) | python | {
"resource": ""
} |
q4022 | load | train | def load(stream, cls=PVLDecoder, strict=True, **kwargs):
"""Deserialize ``stream`` as a pvl module.
:param stream: a ``.read()``-supporting file-like object containing a
module. If ``stream`` is a string it will be treated as a filename
:param cls: the decoder class used to deserialize the pvl mod... | python | {
"resource": ""
} |
q4023 | loads | train | def loads(data, cls=PVLDecoder, strict=True, **kwargs):
"""Deserialize ``data`` as a pvl module.
:param data: a pvl module as a byte or unicode string
:param cls: the decoder class used to deserialize the pvl module. You may
use the default ``PVLDecoder`` class or provide a custom sublcass.
:... | python | {
"resource": ""
} |
q4024 | dump | train | def dump(module, stream, cls=PVLEncoder, **kwargs):
"""Serialize ``module`` as a pvl module to the provided ``stream``.
:param module: a ```PVLModule``` or ```dict``` like object to serialize
:param stream: a ``.write()``-supporting file-like object to serialize the
module to. If ``stream`` is a s... | python | {
"resource": ""
} |
q4025 | dumps | train | def dumps(module, cls=PVLEncoder, **kwargs):
"""Serialize ``module`` as a pvl module formated byte string.
:param module: a ```PVLModule``` or ```dict``` like object to serialize
:param cls: the encoder class used to serialize the pvl module. You may use
the default ``PVLEncoder`` class or provide... | python | {
"resource": ""
} |
q4026 | StateServer.run_dict_method | train | def run_dict_method(self, request):
"""Execute a method on the state ``dict`` and reply with the result."""
state_method_name, args, kwargs = (
request[Msgs.info],
request[Msgs.args],
request[Msgs.kwargs],
)
# print(method_name, args, kwargs)
w... | python | {
"resource": ""
} |
q4027 | StateServer.run_fn_atomically | train | def run_fn_atomically(self, request):
"""Execute a function, atomically and reply with the result."""
fn = serializer.loads_fn(request[Msgs.info])
args, kwargs = request[Msgs.args], request[Msgs.kwargs]
with self.mutate_safely():
self.reply(fn(self.state, *args, **kwargs)) | python | {
"resource": ""
} |
q4028 | clean_process_tree | train | def clean_process_tree(*signal_handler_args):
"""Stop all Processes in the current Process tree, recursively."""
parent = psutil.Process()
procs = parent.children(recursive=True)
if procs:
print(f"[ZProc] Cleaning up {parent.name()!r} ({os.getpid()})...")
for p in procs:
with suppre... | python | {
"resource": ""
} |
q4029 | strict_request_reply | train | def strict_request_reply(msg, send: Callable, recv: Callable):
"""
Ensures a strict req-reply loop,
so that clients dont't receive out-of-order messages,
if an exception occurs between request-reply.
"""
try:
send(msg)
except Exception:
raise
try:
return recv()
... | python | {
"resource": ""
} |
q4030 | start_server | train | def start_server(
server_address: str = None, *, backend: Callable = multiprocessing.Process
) -> Tuple[multiprocessing.Process, str]:
"""
Start a new zproc server.
:param server_address:
.. include:: /api/snippets/server_address.rst
:param backend:
.. include:: /api/snippets/ba... | python | {
"resource": ""
} |
q4031 | ping | train | def ping(
server_address: str, *, timeout: float = None, payload: Union[bytes] = None
) -> int:
"""
Ping the zproc server.
This can be used to easily detect if a server is alive and running, with the aid of a suitable ``timeout``.
:param server_address:
.. include:: /api/snippets/serve... | python | {
"resource": ""
} |
q4032 | cookie_eater | train | def cookie_eater(ctx):
"""Eat cookies as they're baked."""
state = ctx.create_state()
state["ready"] = True
for _ in state.when_change("cookies"):
eat_cookie(state) | python | {
"resource": ""
} |
q4033 | signal_to_exception | train | def signal_to_exception(sig: signal.Signals) -> SignalException:
"""
Convert a ``signal.Signals`` to a ``SignalException``.
This allows for natural, pythonic signal handing with the use of try-except blocks.
.. code-block:: python
import signal
import zproc
zproc.signal_to_ex... | python | {
"resource": ""
} |
q4034 | atomic | train | def atomic(fn: Callable) -> Callable:
"""
Wraps a function, to create an atomic operation out of it.
This contract guarantees, that while an atomic ``fn`` is running -
- No one, except the "callee" may access the state.
- If an ``Exception`` occurs while the ``fn`` is running, the state remains un... | python | {
"resource": ""
} |
q4035 | State.fork | train | def fork(self, server_address: str = None, *, namespace: str = None) -> "State":
r"""
"Forks" this State object.
Takes the same args as the :py:class:`State` constructor,
except that they automatically default to the values provided during the creation of this State object.
If ... | python | {
"resource": ""
} |
q4036 | State.set | train | def set(self, value: dict):
"""
Set the state, completely over-writing the previous value.
.. caution::
This kind of operation usually leads to a data race.
Please take good care while using this.
Use the :py:func:`atomic` deocrator if you're feeling anxio... | python | {
"resource": ""
} |
q4037 | State.when_change_raw | train | def when_change_raw(
self,
*,
live: bool = False,
timeout: float = None,
identical_okay: bool = False,
start_time: bool = None,
count: int = None,
) -> StateWatcher:
"""
A low-level hook that emits each and every state update.
All other... | python | {
"resource": ""
} |
q4038 | State.when_change | train | def when_change(
self,
*keys: Hashable,
exclude: bool = False,
live: bool = False,
timeout: float = None,
identical_okay: bool = False,
start_time: bool = None,
count: int = None,
) -> StateWatcher:
"""
Block until a change is observed,... | python | {
"resource": ""
} |
q4039 | State.when_available | train | def when_available(self, key: Hashable, **when_kwargs) -> StateWatcher:
"""
Block until ``key in state``, and then return a copy of the state.
.. include:: /api/state/get_when_equality.rst
"""
return self.when(lambda snapshot: key in snapshot, **when_kwargs) | python | {
"resource": ""
} |
q4040 | Process.stop | train | def stop(self):
"""
Stop this process.
Once closed, it should not, and cannot be used again.
:return: :py:attr:`~exitcode`.
"""
self.child.terminate()
self._cleanup()
return self.child.exitcode | python | {
"resource": ""
} |
q4041 | Process.wait | train | def wait(self, timeout: Union[int, float] = None):
"""
Wait until this process finishes execution,
then return the value returned by the ``target``.
This method raises a a :py:exc:`.ProcessWaitError`,
if the child Process exits with a non-zero exitcode,
or if something g... | python | {
"resource": ""
} |
q4042 | Context._process | train | def _process(
self, target: Callable = None, **process_kwargs
) -> Union[Process, Callable]:
r"""
Produce a child process bound to this context.
Can be used both as a function and decorator:
.. code-block:: python
:caption: Usage
@zproc.process(pass... | python | {
"resource": ""
} |
q4043 | _expand_scheduledict | train | def _expand_scheduledict(scheduledict):
"""Converts a dict of items, some of which are scalar and some of which are
lists, to a list of dicts with scalar items."""
result = []
def f(d):
nonlocal result
#print(d)
d2 = {}
for k,v in d.items():
if isinstance(v, s... | python | {
"resource": ""
} |
q4044 | get_mentions | train | def get_mentions(status_dict, exclude=[]):
"""
Given a status dictionary, return all people mentioned in the toot,
excluding those in the list passed in exclude.
"""
# Canonicalise the exclusion dictionary by lowercasing all names and
# removing leading @'s
for i, user in enumerate(exclude):... | python | {
"resource": ""
} |
q4045 | PineappleBot.report_error | train | def report_error(self, error, location=None):
"""Report an error that occurred during bot operations. The default
handler tries to DM the bot admin, if one is set, but more handlers can
be added by using the @error_reporter decorator."""
if location == None: location = inspect.stack()[1]... | python | {
"resource": ""
} |
q4046 | PineappleBot.get_reply_visibility | train | def get_reply_visibility(self, status_dict):
"""Given a status dict, return the visibility that should be used.
This behaves like Mastodon does by default.
"""
# Visibility rankings (higher is more limited)
visibility = ("public", "unlisted", "private", "direct")
default... | python | {
"resource": ""
} |
q4047 | spec_dice | train | def spec_dice(spec):
""" Return the dice specification as a string in a common format """
if spec[0] == 'c':
return str(spec[1])
elif spec[0] == 'r':
r = spec[1:]
s = "{}d{}".format(r[0], r[1])
if len(r) == 4 and ((r[2] == 'd' and r[3] < r[0]) or (r[2] == 'k' and r[3] > 0)):... | python | {
"resource": ""
} |
q4048 | roll_dice | train | def roll_dice(spec):
""" Perform the dice rolls and replace all roll expressions with lists of
the dice faces that landed up. """
if spec[0] == 'c': return spec
if spec[0] == 'r':
r = spec[1:]
if len(r) == 2: return ('r', perform_roll(r[0], r[1]))
k = r[3] if r[2] == 'k' else -1 ... | python | {
"resource": ""
} |
q4049 | sum_dice | train | def sum_dice(spec):
""" Replace the dice roll arrays from roll_dice in place with summations of
the rolls. """
if spec[0] == 'c': return spec[1]
elif spec[0] == 'r': return sum(spec[1])
elif spec[0] == 'x':
return [sum_dice(r) for r in spec[1]]
elif spec[0] in ops:
return (spec[0... | python | {
"resource": ""
} |
q4050 | short_sequence_repeat_extractor | train | def short_sequence_repeat_extractor(string, min_length=1):
"""
Extract the short tandem repeat structure from a string.
:arg string string: The string.
:arg integer min_length: Minimum length of the repeat structure.
"""
length = len(string)
k_max = length // 2 + 1
if k_max > THRESHOLD... | python | {
"resource": ""
} |
q4051 | Printer.json | train | def json(cls, message):
""" Print a nice JSON output
Args:
message: the message to print
"""
if type(message) is OrderedDict:
pprint(dict(message))
else:
pprint(message) | python | {
"resource": ""
} |
q4052 | Specification.to_dict | train | def to_dict(self):
""" Transform the current specification to a dictionary
"""
data = {"model": {}}
data["model"]["description"] = self.description
data["model"]["entity_name"] = self.entity_name
data["model"]["package"] = self.package
data["model"]["resource_n... | python | {
"resource": ""
} |
q4053 | Specification.from_dict | train | def from_dict(self, data):
""" Fill the current object with information from the specification
"""
if "model" in data:
model = data["model"]
self.description = model["description"] if "description" in model else None
self.package = model["package"] if "packag... | python | {
"resource": ""
} |
q4054 | Specification._get_apis | train | def _get_apis(self, apis):
""" Process apis for the given model
Args:
model: the model processed
apis: the list of apis availble for the current model
relations: dict containing all relations between resources
"""
ret = []
for... | python | {
"resource": ""
} |
q4055 | APIVersionWriter._read_config | train | def _read_config(self):
""" This method reads provided json config file.
"""
this_dir = os.path.dirname(__file__)
config_file = os.path.abspath(os.path.join(this_dir, "..", "config", "config.json"))
self.generic_enum_attrs = []
self.base_attrs = []
... | python | {
"resource": ""
} |
q4056 | APIVersionWriter.perform | train | def perform(self, specifications):
""" This method is the entry point of javascript code writer. Monolithe will call it when
the javascript plugin is to generate code.
"""
self.enum_list = []
self.model_list = []
self.job_commands = filter(lambda attr: attr.name == 'comma... | python | {
"resource": ""
} |
q4057 | APIVersionWriter._write_abstract_named_entity | train | def _write_abstract_named_entity(self):
""" This method generates AbstractNamedEntity class js file.
"""
filename = "%sAbstractNamedEntity.js" % (self._class_prefix)
superclass_name = "%sEntity" % (self._class_prefix)
# write will write a file using a te... | python | {
"resource": ""
} |
q4058 | TaskManager.wait_until_exit | train | def wait_until_exit(self):
""" Wait until all the threads are finished.
"""
[t.join() for t in self.threads]
self.threads = list() | python | {
"resource": ""
} |
q4059 | TaskManager.start_task | train | def start_task(self, method, *args, **kwargs):
""" Start a task in a separate thread
Args:
method: the method to start in a separate thread
args: Accept args/kwargs arguments
"""
thread = threading.Thread(target=method, args=args, kwargs=kwargs)
... | python | {
"resource": ""
} |
q4060 | CourgetteResult.add_report | train | def add_report(self, specification_name, report):
"""
Adds a given report with the given specification_name as key
to the reports list and computes the number of success, failures
and errors
Args:
specification_name: string representing the specif... | python | {
"resource": ""
} |
q4061 | SDKUtils.massage_type_name | train | def massage_type_name(cls, type_name):
""" Returns a readable type according to a java type
"""
if type_name.lower() in ("enum", "enumeration"):
return "enum"
if type_name.lower() in ("str", "string"):
return "string"
if type_name.lower() in ("boolean",... | python | {
"resource": ""
} |
q4062 | SDKUtils.get_idiomatic_name_in_language | train | def get_idiomatic_name_in_language(cls, name, language):
""" Get the name for the given language
Args:
name (str): the name to convert
language (str): the language to use
Returns:
a name in the given language
Example:
... | python | {
"resource": ""
} |
q4063 | SDKUtils.get_type_name_in_language | train | def get_type_name_in_language(cls, type_name, sub_type, language):
""" Get the type for the given language
Args:
type_name (str): the type to convert
language (str): the language to use
Returns:
a type name in the given language
... | python | {
"resource": ""
} |
q4064 | get_type_name | train | def get_type_name(type_name, sub_type=None):
""" Returns a go type according to a spec type
"""
if type_name in ("string", "enum"):
return "string"
if type_name == "float":
return "float64"
if type_name == "boolean":
return "bool"
if type_name == "list":
st = ... | python | {
"resource": ""
} |
q4065 | APIVersionWriter._write_info | train | def _write_info(self):
""" Write API Info file
"""
self.write(destination=self.output_directory,
filename="vspk/SdkInfo.cs",
template_name="sdkinfo.cs.tpl",
version=self.api_version,
product_accronym=self._product_accron... | python | {
"resource": ""
} |
q4066 | SpecificationAttribute.to_dict | train | def to_dict(self):
""" Transform an attribute to a dict
"""
data = {}
# mandatory characteristics
data["name"] = self.name
data["description"] = self.description if self.description and len(self.description) else None
data["type"] = self.type if self.type and len... | python | {
"resource": ""
} |
q4067 | _FileWriter.write | train | def write(self, destination, filename, content):
""" Write a file at the specific destination with the content.
Args:
destination (string): the destination location
filename (string): the filename that will be written
content (string): the content of ... | python | {
"resource": ""
} |
q4068 | TemplateFileWriter.write | train | def write(self, destination, filename, template_name, **kwargs):
""" Write a file according to the template name
Args:
destination (string): the destination location
filename (string): the filename that will be written
template_name (string): the name... | python | {
"resource": ""
} |
q4069 | APIVersionWriter._write_session | train | def _write_session(self):
""" Write SDK session file
Args:
version (str): the version of the server
"""
base_name = "%ssession" % self._product_accronym.lower()
filename = "%s%s.py" % (self._class_prefix.lower(), base_name)
override_content = self._e... | python | {
"resource": ""
} |
q4070 | APIVersionWriter._write_init_models | train | def _write_init_models(self, filenames):
""" Write init file
Args:
filenames (dict): dict of filename and classes
"""
self.write(destination=self.output_directory, filename="__init__.py", template_name="__init_model__.py.tpl",
filenames=self._pre... | python | {
"resource": ""
} |
q4071 | APIVersionWriter._write_init_fetchers | train | def _write_init_fetchers(self, filenames):
""" Write fetcher init file
Args:
filenames (dict): dict of filename and classes
"""
destination = "%s%s" % (self.output_directory, self.fetchers_path)
self.write(destination=destination, filename="__init__.py", tem... | python | {
"resource": ""
} |
q4072 | APIVersionWriter._extract_constants | train | def _extract_constants(self, specification):
""" Removes attributes and computes constants
"""
constants = {}
for attribute in specification.attributes:
if attribute.allowed_choices and len(attribute.allowed_choices) > 0:
name = attribute.local_name.upper(... | python | {
"resource": ""
} |
q4073 | Courgette.run | train | def run(self, configurations):
""" Run all tests
Returns:
A dictionnary containing tests results.
"""
result = CourgetteResult()
for configuration in configurations:
runner = CourgetteTestsRunner(url=self.url,
... | python | {
"resource": ""
} |
q4074 | get_db | train | def get_db(db_name=None):
""" GetDB - simple function to wrap getting a database
connection from the connection pool.
"""
import pymongo
return pymongo.Connection(host=DB_HOST,
port=DB_PORT)[db_name] | python | {
"resource": ""
} |
q4075 | VSTOpenApiBase.get_main_title | train | def get_main_title(self, path_name, request_name):
'''
Get title, from request type and path
:param path_name: --path for create title
:type path_name: str, unicode
:param request_name: --name of request
:type request_name: str, unicode
:return:
'''
... | python | {
"resource": ""
} |
q4076 | VSTOpenApiBase.schema_handler | train | def schema_handler(self, schema):
'''
Function prepare body of response with examples and create detailed information
about response fields
:param schema: --dictionary with information about answer
:type schema: dict
:return:
'''
dict_for_render = schema.... | python | {
"resource": ""
} |
q4077 | VSTOpenApiBase.get_json_props_for_response | train | def get_json_props_for_response(self, var_type, option_value):
'''
Prepare JSON section with detailed information about response
:param var_type: --contains variable type
:type var_type: , unicode
:param option_value: --dictionary that contains information about property
... | python | {
"resource": ""
} |
q4078 | VSTOpenApiBase.get_object_example | train | def get_object_example(self, def_name):
'''
Create example for response, from object structure
:param def_name: --deffinition name of structure
:type def_name: str, unicode
:return: example of object
:rtype: dict
'''
def_model = self.definitions[def_name]... | python | {
"resource": ""
} |
q4079 | get_render | train | def get_render(name, data, trans='en'):
"""
Render string based on template
:param name: -- full template name
:type name: str,unicode
:param data: -- dict of rendered vars
:type data: dict
:param trans: -- translation for render. Default 'en'.
:type trans: str,unicode
:return: -- r... | python | {
"resource": ""
} |
q4080 | tmp_file.write | train | def write(self, wr_string):
"""
Write to file and flush
:param wr_string: -- writable string
:type wr_string: str
:return: None
:rtype: None
"""
result = self.fd.write(wr_string)
self.fd.flush()
return result | python | {
"resource": ""
} |
q4081 | BaseVstObject.get_django_settings | train | def get_django_settings(cls, name, default=None):
# pylint: disable=access-member-before-definition
"""
Get params from Django settings.
:param name: name of param
:type name: str,unicode
:param default: default value of param
:type default: object
:retur... | python | {
"resource": ""
} |
q4082 | Executor._unbuffered | train | def _unbuffered(self, proc, stream='stdout'):
"""
Unbuffered output handler.
:type proc: subprocess.Popen
:type stream: six.text_types
:return:
"""
if self.working_handler is not None:
t = Thread(target=self._handle_process, args=(proc, stream))
... | python | {
"resource": ""
} |
q4083 | Executor.execute | train | def execute(self, cmd, cwd):
"""
Execute commands and output this
:param cmd: -- list of cmd command and arguments
:type cmd: list
:param cwd: -- workdir for executions
:type cwd: str,unicode
:return: -- string with full output
:rtype: str
"""
... | python | {
"resource": ""
} |
q4084 | ModelHandlers.backend | train | def backend(self, name):
"""
Get backend class
:param name: -- name of backend type
:type name: str
:return: class of backend
:rtype: class,module,object
"""
try:
backend = self.get_backend_handler_path(name)
if backend is None:
... | python | {
"resource": ""
} |
q4085 | URLHandlers.get_object | train | def get_object(self, name, *argv, **kwargs):
"""
Get url object tuple for url
:param name: url regexp from
:type name: str
:param argv: overrided args
:param kwargs: overrided kwargs
:return: url object
:rtype: django.conf.urls.url
"""
reg... | python | {
"resource": ""
} |
q4086 | CopyMixin.copy | train | def copy(self, request, **kwargs):
# pylint: disable=unused-argument
'''
Copy instance with deps.
'''
instance = self.copy_instance(self.get_object())
serializer = self.get_serializer(instance, data=request.data, partial=True)
serializer.is_valid()
seriali... | python | {
"resource": ""
} |
q4087 | BaseManager._get_queryset_methods | train | def _get_queryset_methods(cls, queryset_class):
'''
Django overrloaded method for add cyfunction.
'''
def create_method(name, method):
def manager_method(self, *args, **kwargs):
return getattr(self.get_queryset(), name)(*args, **kwargs)
manager_me... | python | {
"resource": ""
} |
q4088 | LDAP.__authenticate | train | def __authenticate(self, ad, username, password):
'''
Active Directory auth function
:param ad: LDAP connection string ('ldap://server')
:param username: username with domain ('user@domain.name')
:param password: auth password
:return: ldap connection or None if error
... | python | {
"resource": ""
} |
q4089 | register | train | def register(model, autofixture, overwrite=False, fail_silently=False):
'''
Register a model with the registry.
Arguments:
*model* can be either a model class or a string that contains the model's
app label and class name seperated by a dot, e.g. ``"app.ModelClass"``.
*autofixture... | python | {
"resource": ""
} |
q4090 | unregister | train | def unregister(model_or_iterable, fail_silently=False):
'''
Remove one or more models from the autofixture registry.
'''
from django.db import models
from .compat import get_model
if issubclass(model_or_iterable, models.Model):
model_or_iterable = [model_or_iterable]
for model in mo... | python | {
"resource": ""
} |
q4091 | autodiscover | train | def autodiscover():
'''
Auto-discover INSTALLED_APPS autofixtures.py and tests.py modules and fail
silently when not present. This forces an import on them to register any
autofixture bits they may want.
'''
from .compat import importlib
# Bail out if autodiscover didn't finish loading from... | python | {
"resource": ""
} |
q4092 | AutoFixtureBase.is_inheritance_parent | train | def is_inheritance_parent(self, field):
'''
Checks if the field is the automatically created OneToOneField used by
django mulit-table inheritance
'''
return (
isinstance(field, related.OneToOneField) and
field.primary_key and
issubclass(field.m... | python | {
"resource": ""
} |
q4093 | AutoFixtureBase.check_constraints | train | def check_constraints(self, instance):
'''
Return fieldnames which need recalculation.
'''
recalc_fields = []
for constraint in self.constraints:
try:
constraint(self.model, instance)
except constraints.InvalidConstraint as e:
... | python | {
"resource": ""
} |
q4094 | opendocs | train | def opendocs(where='index', how='default'):
'''
Rebuild documentation and opens it in your browser.
Use the first argument to specify how it should be opened:
`d` or `default`: Open in new tab or new window, using the default
method of your browser.
`t` or `tab`: Open documentatio... | python | {
"resource": ""
} |
q4095 | Col.td_contents | train | def td_contents(self, item, attr_list):
"""Given an item and an attr, return the contents of the td.
This method is a likely candidate to override when extending
the Col class, which is done in LinkCol and
ButtonCol. Override this method if you need to get some extra
data from t... | python | {
"resource": ""
} |
q4096 | open | train | def open(filename, mode="rb",
format=None, check=-1, preset=None, filters=None,
encoding=None, errors=None, newline=None):
"""Open an LZMA-compressed file in binary or text mode.
filename can be either an actual file name (given as a str or bytes object),
in which case the named file is o... | python | {
"resource": ""
} |
q4097 | compress | train | def compress(data, format=FORMAT_XZ, check=-1, preset=None, filters=None):
"""Compress a block of data.
Refer to LZMACompressor's docstring for a description of the
optional arguments *format*, *check*, *preset* and *filters*.
For incremental compression, use an LZMACompressor object instead.
"""
... | python | {
"resource": ""
} |
q4098 | decompress | train | def decompress(data, format=FORMAT_AUTO, memlimit=None, filters=None):
"""Decompress a block of data.
Refer to LZMADecompressor's docstring for a description of the
optional arguments *format*, *check* and *filters*.
For incremental decompression, use a LZMADecompressor object instead.
"""
res... | python | {
"resource": ""
} |
q4099 | LZMAFile.close | train | def close(self):
"""Flush and close the file.
May be called more than once without error. Once the file is
closed, any other operation on it will raise a ValueError.
"""
if self._mode == _MODE_CLOSED:
return
try:
if self._mode in (_MODE_READ, _MOD... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.