code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
return anon.faker.datetime(field=field) | def datetime(anon, obj, field, val) | Returns a random datetime | 18.226795 | 11.634363 | 1.566635 |
return anon.faker.date(field=field) | def date(anon, obj, field, val) | Returns a random date | 15.825747 | 11.175303 | 1.416136 |
return anon.faker.decimal(field=field) | def decimal(anon, obj, field, val) | Returns a random decimal | 20.43004 | 14.362651 | 1.422442 |
return anon.faker.postcode(field=field) | def postcode(anon, obj, field, val) | Generates a random postcode (not necessarily valid, but it will look like one). | 15.959905 | 9.737826 | 1.63896 |
return anon.faker.country(field=field) | def country(anon, obj, field, val) | Returns a randomly selected country. | 16.996935 | 9.774081 | 1.73898 |
return anon.faker.user_name(field=field) | def username(anon, obj, field, val) | Generates a random username | 13.645545 | 9.903103 | 1.377906 |
return anon.faker.first_name(field=field) | def first_name(anon, obj, field, val) | Returns a random first name | 12.426819 | 8.833543 | 1.406776 |
return anon.faker.last_name(field=field) | def last_name(anon, obj, field, val) | Returns a random second name | 13.949656 | 9.736389 | 1.432734 |
return anon.faker.name(field=field) | def name(anon, obj, field, val) | Generates a random full name (using first name and last name) | 18.639372 | 9.548575 | 1.952058 |
return anon.faker.email(field=field) | def email(anon, obj, field, val) | Generates a random email address. | 16.508097 | 9.793793 | 1.685567 |
return val if 'betterworks.com' in val else '@'.join([anon.faker.user_name(field=field), val.split('@')[-1]]) | def similar_email(anon, obj, field, val) | Generate a random email address using the same domain. | 11.530082 | 8.817999 | 1.307562 |
return anon.faker.address(field=field) | def full_address(anon, obj, field, val) | Generates a random full address, using newline characters between the lines.
Resembles a US address | 17.782721 | 16.1273 | 1.102647 |
return anon.faker.phone_number(field=field) | def phonenumber(anon, obj, field, val) | Generates a random US-style phone number | 12.299419 | 8.586358 | 1.432437 |
return anon.faker.street_address(field=field) | def street_address(anon, obj, field, val) | Generates a random street address - the first line of a full address | 12.192098 | 7.159422 | 1.702944 |
return anon.faker.city(field=field) | def city(anon, obj, field, val) | Generates a random city name. Resembles the name of US/UK city. | 18.580997 | 11.097122 | 1.674398 |
return anon.faker.state(field=field) | def state(anon, obj, field, val) | Returns a randomly selected US state code | 22.352095 | 14.123681 | 1.582597 |
return anon.faker.zipcode(field=field) | def zip_code(anon, obj, field, val) | Returns a randomly generated US zip code (not necessarily valid, but will look like one). | 13.374743 | 8.728644 | 1.532282 |
return anon.faker.company(field=field) | def company(anon, obj, field, val) | Generates a random company name | 19.246758 | 11.423477 | 1.684842 |
return ' '.join(anon.faker.sentences(field=field)) | def lorem(anon, obj, field, val) | Generates a paragraph of lorem ipsum text | 19.263807 | 21.243921 | 0.906792 |
return anon.faker.unique_lorem(field=field) | def unique_lorem(anon, obj, field, val) | Generates a unique paragraph of lorem ipsum text | 8.953879 | 9.413531 | 0.951171 |
return anon.faker.datetime(field=field, val=val) | def similar_datetime(anon, obj, field, val) | Returns a datetime that is within plus/minus two years of the original datetime | 10.557453 | 9.405473 | 1.12248 |
return anon.faker.date(field=field, val=val) | def similar_date(anon, obj, field, val) | Returns a date that is within plus/minus two years of the original date | 9.423209 | 8.728367 | 1.079607 |
return anon.faker.lorem(field=field, val=val) | def similar_lorem(anon, obj, field, val) | Generates lorem ipsum text with the same length and same pattern of linebreaks
as the original. If the original often takes a standard form (e.g. a single word
'yes' or 'no'), this could easily fail to hide the original data. | 8.722307 | 7.32526 | 1.190716 |
return anon.faker.choice(field=field) | def choice(anon, obj, field, val) | Randomly chooses one of the choices set on the field. | 18.50902 | 15.906429 | 1.163619 |
decoder = __create_decoder(cls, strict, **kwargs)
if isinstance(stream, six.string_types):
with open(stream, 'rb') as fp:
return decoder.decode(fp)
return decoder.decode(stream) | 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 pro... | 2.782583 | 4.038214 | 0.689063 |
decoder = __create_decoder(cls, strict, **kwargs)
if not isinstance(data, bytes):
data = data.encode('utf-8')
return decoder.decode(data) | 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 cl... | 3.123131 | 4.852201 | 0.643652 |
if isinstance(stream, six.string_types):
with open(stream, 'wb') as fp:
return cls(**kwargs).encode(module, fp)
cls(**kwargs).encode(module, stream) | 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... | 2.707512 | 4.095683 | 0.661065 |
stream = io.BytesIO()
cls(**kwargs).encode(module, stream)
return stream.getvalue() | 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
```IsisCubeLab... | 3.794891 | 6.65941 | 0.569854 |
def remote_method(self, *args, **kwargs):
return self._s_request_reply(
{
Msgs.cmd: Cmds.run_dict_method,
Msgs.info: dict_method_name,
Msgs.args: args,
Msgs.kwargs: kwargs,
}
)
remote_method.__name__ =... | def _create_remote_dict_method(dict_method_name: str) | Generates a method for the State class,
that will call the "method_name" on the state (a ``dict``) stored on the server,
and return the result.
Glorified RPC. | 4.08932 | 3.633592 | 1.125421 |
state_method_name, args, kwargs = (
request[Msgs.info],
request[Msgs.args],
request[Msgs.kwargs],
)
# print(method_name, args, kwargs)
with self.mutate_safely():
self.reply(getattr(self.state, state_method_name)(*args, **kwargs)) | def run_dict_method(self, request) | Execute a method on the state ``dict`` and reply with the result. | 6.071488 | 5.210641 | 1.165209 |
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)) | def run_fn_atomically(self, request) | Execute a function, atomically and reply with the result. | 9.548954 | 8.830644 | 1.081343 |
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()
_, alive = psutil.wait_procs(procs, timeout=0.5) # 0.5 ... | def clean_process_tree(*signal_handler_args) | Stop all Processes in the current Process tree, recursively. | 3.071985 | 3.002769 | 1.023051 |
try:
send(msg)
except Exception:
raise
try:
return recv()
except Exception:
with suppress(zmq.error.Again):
recv()
raise | 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. | 4.27774 | 4.069528 | 1.051164 |
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... | 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. | 3.735402 | 4.026988 | 0.927592 |
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))
... | 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 ... | 3.912435 | 3.565894 | 1.097182 |
state = ctx.create_state()
state["ready"] = True
for _ in state.when_change("cookies"):
eat_cookie(state) | def cookie_eater(ctx) | Eat cookies as they're baked. | 14.368971 | 10.532357 | 1.364269 |
if a is None:
a = []
if k is None:
k = {}
if mi is None and ma is None and mk is None:
return []
elif mi is None and ma is None:
return [target(*a, **mki, **k) for mki in mk]
elif ma is None and mk is None:
return [target(mii, *a, **k) for mii in mi]
... | def map_plus(target: Callable, mi, ma, a, mk, k) | The builtin `map()`, but with superpowers. | 1.664717 | 1.639137 | 1.015606 |
signal.signal(sig, _sig_exc_handler)
return SignalException(sig) | 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.Si... | 7.100995 | 17.9573 | 0.395438 |
if isinstance(sig, SignalException):
signum = sig.signum
else:
signum = sig.value
signal.signal(signum, signal.SIG_DFL) | def exception_to_signal(sig: Union[SignalException, signal.Signals]) | Rollback any changes done by :py:func:`signal_to_exception`. | 2.725721 | 2.295152 | 1.187599 |
msg = {
Msgs.cmd: Cmds.run_fn_atomically,
Msgs.info: serializer.dumps_fn(fn),
Msgs.args: (),
Msgs.kwargs: {},
}
@wraps(fn)
def wrapper(state: State, *args, **kwargs):
msg[Msgs.args] = args
msg[Msgs.kwargs] = kwargs
return state._s_request_rep... | 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 "call... | 5.359171 | 6.203298 | 0.863923 |
r
if server_address is None:
server_address = self.server_address
if namespace is None:
namespace = self.namespace
return self.__class__(server_address, namespace=namespace) | 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,
then it shall create a new :py:class:`Stat... | 2.824045 | 2.921397 | 0.966676 |
self._s_request_reply({Msgs.cmd: Cmds.set_state, Msgs.info: value}) | 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 anxious. | 29.263874 | 34.759583 | 0.841894 |
return StateWatcher(
state=self,
live=live,
timeout=timeout,
identical_okay=identical_okay,
start_time=start_time,
count=count,
) | 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:: /api/state/get_raw_update.rst | 1.946021 | 2.340655 | 0.8314 |
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 `key... | 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 | 3.14517 | 3.281837 | 0.958357 |
if args is None:
args = []
if kwargs is None:
kwargs = {}
def callback(update: StateUpdate) -> dict:
snapshot = update.after
if test_fn(snapshot, *args, **kwargs):
return snapshot
raise _SkipStateUpdate
... | def when(
self,
test_fn,
*,
args: Sequence = None,
kwargs: Mapping = None,
live: bool = False,
timeout: float = None,
identical_okay: bool = False,
start_time: bool = None,
count: int = None,
) -> StateWatcher | Block until ``test_fn(snapshot)`` returns a "truthy" value,
and then return a copy of the state.
*Where-*
``snapshot`` is a ``dict``, containing a version of the state after this update was applied.
.. include:: /api/state/get_when.rst | 2.79828 | 2.814782 | 0.994137 |
def _(snapshot):
try:
return snapshot[key] == value
except KeyError:
return False
return self.when(_, **when_kwargs) | def when_equal(self, key: Hashable, value: Any, **when_kwargs) -> StateWatcher | Block until ``state[key] == value``, and then return a copy of the state.
.. include:: /api/state/get_when_equality.rst | 7.921664 | 7.213908 | 1.09811 |
return self.when(lambda snapshot: key in snapshot, **when_kwargs) | 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 | 8.00588 | 9.39504 | 0.852139 |
self.child.terminate()
self._cleanup()
return self.child.exitcode | def stop(self) | Stop this process.
Once closed, it should not, and cannot be used again.
:return: :py:attr:`~exitcode`. | 9.448598 | 10.803436 | 0.874592 |
# try to fetch the cached result.
if self._has_returned:
return self._result
if timeout is not None:
target = time.time() + timeout
while time.time() < target:
self.child.join(timeout)
if self.is_alive:
ra... | 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:
... | 4.213896 | 3.991947 | 1.055599 |
if safe:
_wait = self._wait_or_catch_exc
else:
_wait = Process.wait
if timeout is None:
return [_wait(process) for process in self]
else:
final = time.time() + timeout
return [_wait(process, final - time.time()) for pr... | def wait(
self, timeout: Union[int, float] = None, safe: bool = False
) -> List[Union[Any, Exception]] | Call :py:meth:`~Process.wait()` on all the Processes in this list.
:param timeout:
Same as :py:meth:`~Process.wait()`.
This parameter controls the timeout for all the Processes combined,
not a single :py:meth:`~Process.wait()` call.
:param safe:
Suppress... | 3.936691 | 4.325814 | 0.910046 |
if namespace is None:
namespace = self.namespace
state = State(self.server_address, namespace=namespace)
if value is not None:
state.update(value)
return state | def create_state(self, value: dict = None, *, namespace: str = None) | Creates a new :py:class:`State` object, sharing the same zproc server as this Context.
:param value:
If provided, call ``state.update(value)``.
:param namespace:
Use this as the namespace for the :py:class:`State` object,
instead of this :py:class:`Context`\ 's names... | 3.474914 | 2.701514 | 1.286284 |
r
process = Process(
self.server_address, target, **{**self.process_kwargs, **process_kwargs}
)
self.process_list.append(process)
return process | 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)
... | 4.347225 | 7.546053 | 0.576092 |
r
if not targets:
def wrapper(target: Callable):
return self.spawn(target, count=count, **process_kwargs)
return wrapper
if len(targets) * count == 1:
return self._process(targets[0], **process_kwargs)
return ProcessList(
... | def spawn(self, *targets: Callable, count: int = 1, **process_kwargs) | r"""
Produce one or many child process(s) bound to this context.
:param \*targets:
Passed on to the :py:class:`Process` constructor, one at a time.
:param count:
The number of processes to spawn for each item in ``targets``.
:param \*\*process_kwargs:
... | 3.482436 | 3.195293 | 1.089864 |
return self.process_list.wait(timeout, safe) | def wait(
self, timeout: Union[int, float] = None, safe: bool = False
) -> List[Union[Any, Exception]] | alias for :py:meth:`ProcessList.wait()` | 10.311848 | 4.010705 | 2.571081 |
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:
d[k] = _cronslash(v, k)
for k,v in d.items():
if isinstance(v, Iterable):
co... | 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. | 2.81784 | 2.836943 | 0.993266 |
has_interval = hasattr(f, "interval")
has_schedule = hasattr(f, "schedule")
if (not has_interval and not has_schedule):
return 0
if (has_interval and not has_schedule):
tNext = tLast + timedelta(seconds = f.interval)
return max(total_seconds(tNext - t), 0)
if (has_sched... | def interval_next(f, t = datetime.now(), tLast = datetime.now()) | Calculate the number of seconds from now until the function should next run.
This function handles both cron-like and interval-like scheduling via the
following:
∗ If no interval and no schedule are specified, return 0
∗ If an interval is specified but no schedule, return the number of seconds
... | 2.852958 | 2.693402 | 1.05924 |
# Canonicalise the exclusion dictionary by lowercasing all names and
# removing leading @'s
for i, user in enumerate(exclude):
user = user.casefold()
if user[0] == "@":
user = user[1:]
exclude[i] = user
users = [user["username"] for user in status_dict["mention... | 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. | 4.309822 | 4.174448 | 1.032429 |
if location == None: location = inspect.stack()[1][3]
self.log(location, error)
for f in self.report_funcs:
f(error) | 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. | 5.237324 | 5.459965 | 0.959223 |
# Visibility rankings (higher is more limited)
visibility = ("public", "unlisted", "private", "direct")
default_visibility = visibility.index(self.default_visibility)
status_visibility = visibility.index(status_dict["visibility"])
return visibility[max(default_visibili... | 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. | 4.497397 | 4.031767 | 1.11549 |
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)):
s += "{}{}".format(r[2], r[3])
return s
elif spec[0] in ops:
... | def spec_dice(spec) | Return the dice specification as a string in a common format | 2.800089 | 2.561737 | 1.093043 |
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... | def roll_dice(spec) | Perform the dice rolls and replace all roll expressions with lists of
the dice faces that landed up. | 2.664837 | 2.661102 | 1.001404 |
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], sum_dice(spec[1]), sum_dice(spec[2]))
else: raise ValueError("Invalid dice specification") | def sum_dice(spec) | Replace the dice roll arrays from roll_dice in place with summations of
the rolls. | 2.960973 | 2.825586 | 1.047915 |
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... | 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. | 2.222266 | 2.341667 | 0.94901 |
error_message = "[error] %s" % message
if cls.__raise_exception__:
raise Exception(error_message)
cls.colorprint(error_message, Fore.RED)
sys.exit(1) | def raiseError(cls, message) | Print an error message
Args:
message: the message to print | 5.012774 | 5.901817 | 0.849361 |
if type(message) is OrderedDict:
pprint(dict(message))
else:
pprint(message) | def json(cls, message) | Print a nice JSON output
Args:
message: the message to print | 7.496354 | 7.106876 | 1.054803 |
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
... | def to_dict(self) | Transform the current specification to a dictionary | 2.355771 | 2.306142 | 1.02152 |
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 []
... | def from_dict(self, data) | Fill the current object with information from the specification | 1.958871 | 1.961825 | 0.998494 |
ret = []
for data in apis:
ret.append(SpecificationAPI(specification=self, data=data))
return sorted(ret, key=lambda x: x.rest_name[1:]) | 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 | 6.43519 | 7.872442 | 0.817432 |
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... | def _read_config(self) | This method reads provided json config file. | 2.621971 | 2.559992 | 1.02421 |
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()
... | 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. | 4.988783 | 4.750625 | 1.050132 |
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
# o... | def _write_abstract_named_entity(self) | This method generates AbstractNamedEntity class js file. | 6.436901 | 5.629482 | 1.143427 |
self.enum_attrs_for_locale[entity_name] = attributes;
for attribute in attributes:
enum_name = "%s%sEnum" % (entity_name, attribute.name[0].upper() + attribute.name[1:])
self.enum_list.append(enum_name)
filename = "%s%s.js" % (self._class_prefix, en... | def _write_enums(self, entity_name, attributes) | This method writes the ouput for a particular specification. | 3.779331 | 3.751154 | 1.007512 |
[t.join() for t in self.threads]
self.threads = list() | def wait_until_exit(self) | Wait until all the threads are finished. | 8.426952 | 6.308522 | 1.335804 |
thread = threading.Thread(target=method, args=args, kwargs=kwargs)
thread.is_daemon = False
thread.start()
self.threads.append(thread) | 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 | 2.414232 | 3.704206 | 0.651754 |
self._reports[specification_name] = report
self._total = self._total + report.testsRun
self._failures = self._failures + len(report.failures)
self._errors = self._errors + len(report.errors)
self._success = self._total - self._failures - self._errors | 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 | 2.709029 | 2.865947 | 0.945247 |
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"):
... | def massage_type_name(cls, type_name) | Returns a readable type according to a java type | 1.762926 | 1.792699 | 0.983392 |
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_metho... | 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"... | 2.533987 | 2.677655 | 0.946346 |
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[l... | 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")
... | 2.527261 | 2.72437 | 0.92765 |
if type_name == "enum":
return type_name
elif type_name == "boolean":
return "bool"
elif type_name == "integer":
return "long"
elif type_name == "time":
return "long"
elif type_name == "object":
return "Object"
elif type_name == "list":
return... | def get_type_name(type_name, sub_type=None) | Returns a c# type according to a spec type | 2.11507 | 2.120477 | 0.99745 |
self.write(destination=self._base_output_directory,
filename="pom.xml",
template_name="pom.xml.tpl",
version=self.api_version,
product_accronym=self._product_accronym,
class_prefix=self._class_prefix,
... | def _write_build_file(self) | Write Maven build file (pom.xml) | 4.479261 | 4.002595 | 1.119089 |
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 = get_type_name(type_name=sub_type, sub_type=None) if sub_type else "interface{}"
return "[]%s... | def get_type_name(type_name, sub_type=None) | Returns a go type according to a spec type | 2.695963 | 2.404612 | 1.121163 |
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,
... | def _write_info(self) | Write API Info file | 5.436288 | 5.095706 | 1.066837 |
filename = "vspk/%s%s.cs" % (self._class_prefix, specification.entity_name)
override_content = self._extract_override_content(specification.entity_name)
superclass_name = "RestObject"
defaults = {}
section = specification.entity_name
if self.attrs_defaults.has_... | def _write_model(self, specification, specification_set) | Write autogenerate specification file | 3.946615 | 3.866693 | 1.020669 |
destination = "%s" % (self.output_directory)
base_name = "%sFetcher" % specification.entity_name_plural
filename = "vspk/%s%s.cs" % (self._class_prefix, base_name)
override_content = self._extract_override_content(base_name)
self.write(destination=destination,
... | def _write_fetcher(self, specification, specification_set) | Write fetcher | 4.35191 | 4.2751 | 1.017967 |
for rest_name, specification in specifications.items():
for attribute in specification.attributes:
if attribute.type == "enum":
enum_type = attribute.local_name[0:1].upper() + attribute.local_name[1:]
attribute.local_type = enum_type
... | def _set_enum_list_local_type(self, specifications) | This method is needed until get_type_name() is enhanced to include specification subtype and local_name | 2.034976 | 1.95131 | 1.042877 |
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_... | def to_dict(self) | Transform an attribute to a dict | 1.71335 | 1.700093 | 1.007798 |
template_file = "o11nplugin-core/model.java.tpl"
filename = "%s%s.java" % (self._class_prefix, specification.entity_name)
override_content = self._extract_override_content(specification.entity_name)
superclass_name = "BaseRootObject" if specification.rest_name == self.api_root ... | def _write_model(self, specification, specification_set, output_directory, package_name) | Write autogenerate specification file | 3.213467 | 3.213116 | 1.000109 |
enum_name = specification.entity_name + attribute.local_name[0:1].upper() + attribute.local_name[1:]
template_file = "o11nplugin-core/enum.java.tpl"
destination = "%s%s" % (output_directory, self.enums_path)
filename = "%s%s.java" % (self._class_prefix, enum_name)
self.... | def _write_enum(self, specification, attribute, output_directory, package_name) | Write autogenerate specification file | 3.984635 | 4.005495 | 0.994792 |
if not os.path.exists(destination):
try:
os.makedirs(destination)
except: # The directory can be created while creating it.
pass
filepath = "%s/%s" % (destination, filename)
f = open(filepath, "w+")
f.write(content)
... | 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 | 3.139592 | 3.618841 | 0.867569 |
template = self.env.get_template(template_name)
content = template.render(kwargs)
super(TemplateFileWriter, self).write(destination=destination, filename=filename, content=content) | 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 of the template
kwargs (dict): all attribute that will be pa... | 2.597388 | 3.491564 | 0.743904 |
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",
... | def _write_session(self) | Write SDK session file
Args:
version (str): the version of the server | 4.324653 | 4.743018 | 0.911793 |
self.write(destination=self.output_directory, filename="__init__.py", template_name="__init_model__.py.tpl",
filenames=self._prepare_filenames(filenames),
class_prefix=self._class_prefix,
product_accronym=self._product_accronym,
... | def _write_init_models(self, filenames) | Write init file
Args:
filenames (dict): dict of filename and classes | 7.131779 | 7.80022 | 0.914305 |
filename = "%s%s.py" % (self._class_prefix.lower(), specification.entity_name.lower())
override_content = self._extract_override_content(specification.entity_name)
constants = self._extract_constants(specification)
superclass_name = "NURESTRootObject" if specification.rest_name... | def _write_model(self, specification, specification_set) | Write autogenerate specification file | 4.556797 | 4.427382 | 1.02923 |
destination = "%s%s" % (self.output_directory, self.fetchers_path)
self.write(destination=destination, filename="__init__.py", template_name="__init_fetcher__.py.tpl",
filenames=self._prepare_filenames(filenames, suffix='Fetcher'),
class_prefix=self._class_... | def _write_init_fetchers(self, filenames) | Write fetcher init file
Args:
filenames (dict): dict of filename and classes | 6.73199 | 7.688475 | 0.875595 |
destination = "%s%s" % (self.output_directory, self.fetchers_path)
base_name = "%s_fetcher" % specification.entity_name_plural.lower()
filename = "%s%s.py" % (self._class_prefix.lower(), base_name)
override_content = self._extract_override_content(base_name)
self.write(... | def _write_fetcher(self, specification, specification_set) | Write fetcher | 4.117382 | 4.064599 | 1.012986 |
constants = {}
for attribute in specification.attributes:
if attribute.allowed_choices and len(attribute.allowed_choices) > 0:
name = attribute.local_name.upper()
for choice in attribute.allowed_choices:
constants["CONST_%s_%s"... | def _extract_constants(self, specification) | Removes attributes and computes constants | 3.777004 | 3.540612 | 1.066766 |
result = CourgetteResult()
for configuration in configurations:
runner = CourgetteTestsRunner(url=self.url,
username=self.username,
password=self.password,
... | def run(self, configurations) | Run all tests
Returns:
A dictionnary containing tests results. | 5.080291 | 5.019395 | 1.012132 |
data = self.get_data()
series_names = data[0][1:]
serieses = []
options = self.get_options()
if 'annotation' in options:
data = self.get_data()
annotation_list = options['annotation']
for i, name in enumerate(series_names):
... | def get_series(self) | Example usage:
data = [
['Year', 'Sales', 'Expenses', 'Items Sold', 'Net Profit'],
['2004', 1000, 400, 100, 600],
['2005', 1170, 460, 120, 310],
['2006', 660, 1120, 50, -460],
['2007', 1030, 540, 100, 200],
]
... | 2.391066 | 2.263354 | 1.056426 |
import pymongo
return pymongo.Connection(host=DB_HOST,
port=DB_PORT)[db_name] | def get_db(db_name=None) | GetDB - simple function to wrap getting a database
connection from the connection pool. | 4.076913 | 3.637916 | 1.120673 |
'''
Load OpenAPI specification from yaml file. Path to file taking from command
`vst_openapi`.
:return:
'''
env = self.state.document.settings.env
relpath, abspath = env.relfn2path(directives.path(self.arguments[0]))
env.note_dependency(relpath)
... | def load_yaml(self) | Load OpenAPI specification from yaml file. Path to file taking from command
`vst_openapi`.
:return: | 5.189602 | 3.590062 | 1.445547 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.