_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 31
13.1k
| 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:
def generate(length):
# Get lorem ipsum of a specific length.
collect = ""
while len(collect) < length:
collect += ' %s' % self.faker.sentence()
collect = collect[:length]
return collect
# We want to match the pattern of the text - linebreaks
# in the same places.
def source():
parts = val.split("\n")
|
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 = str(self.unique_suffixes[field])
unique_text = lorem_text
|
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
|
python
|
{
"resource": ""
}
|
q4003
|
uuid
|
train
|
def uuid(anon, obj, field, val):
"""
Returns a random uuid string
"""
|
python
|
{
"resource": ""
}
|
q4004
|
varchar
|
train
|
def varchar(anon, obj, field, val):
"""
Returns random data for a varchar field.
|
python
|
{
"resource": ""
}
|
q4005
|
datetime
|
train
|
def datetime(anon, obj, field, val):
"""
Returns a random datetime
"""
|
python
|
{
"resource": ""
}
|
q4006
|
date
|
train
|
def date(anon, obj, field, val):
"""
Returns a random date
"""
|
python
|
{
"resource": ""
}
|
q4007
|
decimal
|
train
|
def decimal(anon, obj, field, val):
"""
Returns a random decimal
"""
|
python
|
{
"resource": ""
}
|
q4008
|
country
|
train
|
def country(anon, obj, field, val):
"""
Returns a randomly selected country.
"""
|
python
|
{
"resource": ""
}
|
q4009
|
username
|
train
|
def username(anon, obj, field, val):
"""
Generates a random username
"""
|
python
|
{
"resource": ""
}
|
q4010
|
first_name
|
train
|
def first_name(anon, obj, field, val):
"""
Returns a random first name
"""
|
python
|
{
"resource": ""
}
|
q4011
|
last_name
|
train
|
def last_name(anon, obj, field, val):
"""
Returns a random second name
"""
|
python
|
{
"resource": ""
}
|
q4012
|
email
|
train
|
def email(anon, obj, field, val):
"""
Generates a random email address.
"""
|
python
|
{
"resource": ""
}
|
q4013
|
similar_email
|
train
|
def similar_email(anon, obj, field, val):
"""
Generate a random email address using the same
|
python
|
{
"resource": ""
}
|
q4014
|
full_address
|
train
|
def full_address(anon, obj, field, val):
"""
Generates a random full address, using newline characters between the lines.
|
python
|
{
"resource": ""
}
|
q4015
|
phonenumber
|
train
|
def phonenumber(anon, obj, field, val):
"""
Generates a random US-style phone number
|
python
|
{
"resource": ""
}
|
q4016
|
street_address
|
train
|
def street_address(anon, obj, field, val):
"""
Generates a random street address - the first line of a full
|
python
|
{
"resource": ""
}
|
q4017
|
state
|
train
|
def state(anon, obj, field, val):
"""
Returns a randomly selected US state code
|
python
|
{
"resource": ""
}
|
q4018
|
company
|
train
|
def company(anon, obj, field, val):
"""
Generates a random company name
"""
|
python
|
{
"resource": ""
}
|
q4019
|
lorem
|
train
|
def lorem(anon, obj, field, val):
"""
Generates a paragraph of lorem ipsum text
"""
|
python
|
{
"resource": ""
}
|
q4020
|
unique_lorem
|
train
|
def unique_lorem(anon, obj, field, val):
"""
Generates a unique paragraph of lorem ipsum text
|
python
|
{
"resource": ""
}
|
q4021
|
choice
|
train
|
def choice(anon, obj, field, val):
"""
Randomly chooses one of the choices set on the 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 module. You may
use the default ``PVLDecoder`` class or provide a custom sublcass.
:param **kwargs: the keyword
|
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.
:param **kwargs: the keyword arguments to pass to the decoder
|
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 string it will be treated as a filename
:param cls: the encoder class used to serialize the pvl module. You may use
the default ``PVLEncoder`` class or provided encoder formats such as the
|
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 provided encoder formats such as the
```IsisCubeLabelEncoder``` and ```PDSLabelEncoder``` classes. You may
also provided a custom sublcass
|
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],
|
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,
|
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 suppress(psutil.NoSuchProcess):
p.terminate()
|
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:
|
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/backend.rst
:return: `
A `tuple``,
containing a :py:class:`multiprocessing.Process` object for server and the server address.
"""
recv_conn, send_conn = multiprocessing.Pipe()
server_process = backend(target=main, args=[server_address, send_conn])
server_process.start()
try:
with recv_conn:
server_meta: ServerMeta = serializer.loads(recv_conn.recv_bytes())
except zmq.ZMQError as e:
if e.errno == 98:
|
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/server_address.rst
:param timeout:
The timeout in seconds.
If this is set to ``None``, then it will block forever, until the zproc server replies.
For all other values, it will wait for a reply,
for that amount of time before returning with a :py:class:`TimeoutError`.
By default it is set to ``None``.
:param payload:
payload that will be sent to the server.
If it is set to None, then ``os.urandom(56)`` (56 random bytes) will be used.
(No real reason for the ``56`` magic number.)
:return:
The zproc server's **pid**.
"""
if payload is None:
payload = os.urandom(56)
with util.create_zmq_ctx() as zmq_ctx:
with zmq_ctx.socket(zmq.DEALER) as dealer_sock:
dealer_sock.connect(server_address)
if timeout is not None:
dealer_sock.setsockopt(zmq.RCVTIMEO, int(timeout * 1000))
|
python
|
{
"resource": ""
}
|
q4032
|
cookie_eater
|
train
|
def cookie_eater(ctx):
"""Eat cookies as they're baked."""
state = ctx.create_state()
state["ready"] = True
|
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_exception(signals.SIGTERM)
try:
...
except zproc.SignalException as e:
|
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 unaffected.
- | If a signal is sent to the "callee", the ``fn`` remains unaffected.
| (The state is not left in an incoherent state.)
.. note::
- The first argument to the wrapped function *must* be a :py:class:`State` object.
- The wrapped ``fn`` receives a frozen version (snapshot) of state,
which is a ``dict`` object, not a :py:class:`State` object.
|
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 no args are provided to this function,
|
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.
|
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 state watchers are built upon this only.
.. include::
|
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, and then return a copy of the state.
.. include:: /api/state/get_when_change.rst
"""
if not keys:
def callback(update: StateUpdate) -> dict:
return update.after
else:
if identical_okay:
raise ValueError(
"Passing both `identical_okay` and `keys` is not possible. "
"(Hint: Omit `keys`)"
)
key_set = set(keys)
def select(before, after):
selected = {*before.keys(), *after.keys()}
if exclude:
return selected - key_set
|
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.
..
|
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`.
|
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 goes wrong while communicating with the child.
:param timeout:
The timeout in seconds.
If the value is ``None``, it will block until the zproc server replies.
For all other values, it will wait for a reply,
for that amount of time before returning with a :py:class:`TimeoutError`.
:return:
The value returned by the ``target`` function.
"""
# try to fetch the cached result.
if self._has_returned:
|
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_context=True) # you may pass some arguments here
def p1(ctx):
print('hello', ctx)
@zproc.process # or not...
def p2(state):
print('hello', state)
def p3(state):
print('hello', state)
zproc.process(p3) # or just use as a good ol' function
:param target:
Passed on to the :py:class:`Process` constructor.
*Must be omitted when using this as a decorator.*
|
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, str) and _cronslash(v, k) is not None:
|
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):
user = user.casefold()
|
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
|
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")
|
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
d = r[3] if r[2] == 'd' else -1
return ('r', perform_roll(r[0], r[1], k, d))
if spec[0] == "x":
c = None
roll = None
if spec[1][0] == "c": c = spec[1]
elif spec[1][0] == "r": roll = spec[1]
if spec[2][0] == "c": c = spec[2]
|
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':
|
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:
k_max = THRESHOLD // 2
repeats = []
i = 0
last_repeat = i
while i < length:
max_count = 0
max_k = 1
for k in range(min_length, k_max):
count = 0
for j in range(i + k, length - k + 1, k):
if string[i:i + k] != string[j:j + k]:
break
count += 1
if count > 0 and count >= max_count:
|
python
|
{
"resource": ""
}
|
q4051
|
Printer.json
|
train
|
def json(cls, message):
""" Print a nice JSON output
Args:
message: the message to print
"""
|
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_name"] = self.resource_name
data["model"]["rest_name"] = self.rest_name
data["model"]["extends"] = self.extends
data["model"]["get"] = self.allows_get
|
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 "package" in model else None
self.extends = model["extends"] if "extends" in model else []
self.entity_name = model["entity_name"] if "entity_name" in model else None
self.rest_name = model["rest_name"] if "rest_name" in model else None
self.resource_name = model["resource_name"] if "resource_name" in model else None
self.allows_get = model["get"] if "get" in model else False
self.allows_create = model["create"] if "create" in model else False
self.allows_update = model["update"] if "update" in model else False
|
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
"""
|
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 = []
self.generic_enums = []
self.named_entity_attrs = []
self.overide_generic_enums = []
self.enum_attrs_for_locale = {}
self.generic_enum_attrs_for_locale = {}
self.list_subtypes_generic = []
Printer.log("Configuration file: %s" % (config_file))
if (os.path.isfile(config_file)):
with open(config_file, 'r') as input_json:
json_config_data = json.load(input_json)
|
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 == 'command', specifications.get("job").attributes)[0].allowed_choices
#Printer.log("job_commands: %s" % (self.job_commands))
self._write_abstract_named_entity()
self.entity_names = [specification.entity_name for rest_name, specification in specifications.iteritems()]
for rest_name, specification in specifications.iteritems():
self._write_model(specification=specification)
#self._write_generic_enums()
self.write(destination = self.model_directory,
|
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 template.
# mandatory params: destination directory, destination file name, template file name
# optional params: whatever that is needed
|
python
|
{
"resource": ""
}
|
q4058
|
TaskManager.wait_until_exit
|
train
|
def wait_until_exit(self):
""" Wait until all the threads are finished.
"""
|
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
"""
|
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 specification (with ".spec")
report: The
"""
|
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", "bool"):
return "boolean"
if type_name.lower() in ("int", "integer"):
return "integer"
if type_name.lower() in ("date", "datetime", "time"):
return "time"
if type_name.lower() in ("double", "float", "long"):
|
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:
get_idiomatic_name_in_language("EnterpriseNetwork", "python")
>>> enterprise_network
"""
if language in cls.idiomatic_methods_cache:
m = cls.idiomatic_methods_cache[language]
if not m:
return name
return m(name)
found, method = load_language_plugins(language, 'get_idiomatic_name')
if found:
cls.idiomatic_methods_cache[language] = method
if method:
return method(name)
else:
|
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
Example:
get_type_name_in_language("Varchar", "python")
>>> str
"""
if language in cls.type_methods_cache:
m = cls.type_methods_cache[language]
if not m:
return type_name
return m(type_name)
found, method = load_language_plugins(language, 'get_type_name')
if found:
cls.type_methods_cache[language] = method
if method:
return method(type_name, sub_type)
else:
|
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":
|
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_accronym,
class_prefix=self._class_prefix,
root_api=self.api_root,
api_prefix=self.api_prefix,
|
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(self.type) else None
data["allowed_chars"] = self.allowed_chars if self.allowed_chars and len(self.allowed_chars) else None
data["allowed_choices"] = self.allowed_choices
data["autogenerated"] = self.autogenerated
data["channel"] = self.channel if self.channel and len(self.channel) else None
data["creation_only"] = self.creation_only
data["default_order"] = self.default_order
data["default_value"] = self.default_value if self.default_value and len(self.default_value) else None
data["deprecated"] = self.deprecated
data["exposed"] = self.exposed
data["filterable"] = self.filterable
data["format"] = self.format if self.format and len(self.format) else None
data["max_length"] = int(self.max_length) if self.max_length is not
|
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 the filename
"""
if not os.path.exists(destination):
try:
|
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
|
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._extract_override_content(base_name)
self.write(destination=self.output_directory, filename=filename, template_name="session.py.tpl",
version=self.api_version,
|
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",
|
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", template_name="__init_fetcher__.py.tpl",
|
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,
username=self.username,
password=self.password,
enterprise=self.enterprise,
version=self.apiversion,
specification=configuration.specification,
sdk_identifier=self.sdk_identifier,
|
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
|
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.get('properties', dict()).items()
if schema.get('$ref', None):
def_name = schema.get('$ref').split('/')[-1]
dict_for_render = self.definitions[def_name].get('properties', dict()).items()
elif schema.get('properties', None) is None:
return ''
answer_dict = dict()
json_dict = dict()
for opt_name, opt_value in dict_for_render:
var_type = opt_value.get('format', None) or opt_value.get('type', None) or 'object'
json_name = self.indent + ':jsonparameter {} {}:'.format(var_type, opt_name)
json_dict[json_name]
|
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
:type option_value: dict
:return: dictionary that contains, title and all properties of field
:rtype: dict
'''
props = list()
for name, value in option_value.items():
|
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]
example = dict()
for opt_name, opt_value in def_model.get('properties', dict()).items():
|
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: -- rendered string
:rtype: str,unicode
|
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
|
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
:return: Param from Django settings or default.
|
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))
t.start()
|
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
"""
self.output = ""
env = os.environ.copy()
env.update(self.env)
if six.PY2: # nocv
# Ugly hack because python 2.7.
if self._stdout == self.DEVNULL:
self._stdout = open(os.devnull, 'w+b')
if self._stderr == self.DEVNULL:
self._stderr = open(os.devnull, 'w+b')
proc =
|
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:
raise ex.VSTUtilsException("Backend is
|
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
"""
regexp = name
options = self.opts(regexp)
options.update(kwargs)
args = options.pop('view_args',
|
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)
|
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_method.__name__ = method.__name__
manager_method.__doc__ = method.__doc__
return manager_method
orig_method = models.Manager._get_queryset_methods
new_methods = orig_method(queryset_class)
inspect_func = inspect.isfunction
for name, method in inspect.getmembers(queryset_class, predicate=inspect_func):
# Only copy missing methods.
if hasattr(cls, name)
|
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 ('[email protected]')
:param password: auth password
:return: ldap connection or None if error
'''
result = None
conn = ldap.initialize(ad)
conn.protocol_version = 3
conn.set_option(ldap.OPT_REFERRALS, 0)
user = self.__prepare_user_with_domain(username)
self.logger.debug("Trying to auth with user '{}' to {}".format(user, ad))
try:
conn.simple_bind_s(user, password)
result = conn
self.username, self.password
|
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* is the :mod:`AutoFixture` subclass that shall be used to
generated instances of *model*.
By default :func:`register` will raise :exc:`ValueError` if the given
*model* is already registered. You can overwrite the registered *model* if
you pass ``True`` to the *overwrite* argument.
The :exc:`ValueError` that is usually raised if a model is already
registered can be suppressed by passing ``True`` to the *fail_silently*
argument.
|
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 model_or_iterable:
if isinstance(model, string_types):
model = get_model(*model.split('.', 1))
try:
del REGISTRY[model]
except KeyError:
|
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 a previous call so
# that we avoid running autodiscover again when the URLconf is loaded by
# the exception handler to resolve the handler500 view. This prevents an
# autofixtures.py module with errors from re-registering models and raising a
# spurious AlreadyRegistered exception (see #8245).
global LOADING
if LOADING:
return
LOADING = True
app_paths = {}
# For each app, we need to look for an autofixture.py inside that app's
# package. We can't use os.path here -- recall that modules may be
# imported different ways (think zip files) -- so we need to get
# the app's __path__ and look for autofixture.py on that path.
# Step 1: find out the app's __path__ Import errors here will (and
# should) bubble up, but a missing __path__ (which is legal, but weird)
# fails silently -- apps that do weird things with __path__ might
# need to roll their own autofixture registration.
import imp
|
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
|
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)
|
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 documentation in new tab.
`n`, `w` or `window`: Open documentation in new window.
'''
import webbrowser
docs_dir = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
|
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
|
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 opened, or it can be an existing file object
to read from or write to.
The mode argument can be "r", "rb" (default), "w", "wb", "a", or "ab" for
binary mode, or "rt", "wt" or "at" for text mode.
The format, check, preset and filters arguments specify the compression
settings, as for LZMACompressor, LZMADecompressor and LZMAFile.
For binary mode, this function is equivalent to the LZMAFile constructor:
|
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
|
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.
"""
results = []
while True:
decomp = LZMADecompressor(format, memlimit, filters)
try:
res = decomp.decompress(data)
except LZMAError:
if results:
break # Leftover data is not
|
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, _MODE_READ_EOF):
self._decompressor = None
self._buffer = None
elif self._mode == _MODE_WRITE:
self._fp.write(self._compressor.flush())
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.