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 provide a custom sublcass. :param **kwargs: the keyword arguments to pass to the decoder class.
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 class.
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 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 of ```PVLEncoder``` :param **kwargs: the keyword arguments to pass to the encoder class.
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 ```IsisCubeLabelEncoder``` and ```PDSLabelEncoder``` classes. You may also provided a custom sublcass of ```PVLEncoder``` :param **kwargs: the keyword arguments to pass to the encoder class. :returns: a byte string encoding of the pvl module
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__ = dict_method_name return remote_method
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 seems to work for p in alive: with suppress(psutil.NoSuchProcess): p.kill() try: signum = signal_handler_args[0] except IndexError: pass else: os._exit(signum)
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 == 98: raise ConnectionError( "Encountered - %s. Perhaps the server is already running?" % repr(e) ) if e.errno == 22: raise ValueError( "Encountered - %s. `server_address` must be a string containing a valid endpoint." % repr(e) ) raise return server_process, server_meta.state_router
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)) dealer_sock.send( serializer.dumps( {Msgs.cmd: Cmds.ping, Msgs.info: payload} ) ) try: recv_payload, pid = serializer.loads(dealer_sock.recv()) except zmq.error.Again: raise TimeoutError( "Timed-out waiting while for the ZProc server to respond." ) assert ( recv_payload == payload ), "Payload doesn't match! The server connection may be compromised, or unstable." return pid
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**.
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] elif mk is None and mi is None: return [target(*mai, *a, **k) for mai in ma] elif mi is None: return [target(*mai, *a, **mki, **k) for mai, mki in zip(ma, mk)] elif ma is None: return [target(mii, *a, **mki, **k) for mii, mki in zip(mi, mk)] elif mk is None: return [target(mii, *mai, *a, **k) for mii, mai in zip(mi, ma)] else: return [target(mii, *mai, *a, **mki, **k) for mii, mai, mki in zip(mi, ma, mk)]
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.SignalException as e: print("encountered:", e) finally: zproc.exception_to_signal(signals.SIGTERM)
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_reply(msg) return wrapper
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. - It is not possible to call one atomic function from other. Please read :ref:`atomicity` for a detailed explanation. :param fn: The function to be wrapped, as an atomic function. :returns: A wrapper function. The wrapper function returns the value returned by the wrapped ``fn``. >>> import zproc >>> >>> @zproc.atomic ... def increment(snapshot): ... return snapshot['count'] + 1 ... >>> >>> ctx = zproc.Context() >>> state = ctx.create_state({'count': 0}) >>> >>> increment(state) 1
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:`State` object that follows the exact same semantics as this one. This is preferred over ``copy()``\ -ing a :py:class:`State` object. Useful when one needs to access 2 or more namespaces from the same code.
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 `keys`)" ) key_set = set(keys) def select(before, after): selected = {*before.keys(), *after.keys()} if exclude: return selected - key_set else: return selected & key_set def callback(update: StateUpdate) -> dict: before, after = update.before, update.after try: if not any(before[k] != after[k] for k in select(before, after)): raise _SkipStateUpdate except KeyError: # this indirectly implies that something has changed pass return update.after return StateWatcher( state=self, live=live, timeout=timeout, identical_okay=identical_okay, start_time=start_time, count=count, callback=callback, )
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 return StateWatcher( state=self, live=live, timeout=timeout, identical_okay=identical_okay, start_time=start_time, count=count, callback=callback, )
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: raise TimeoutError( f"Timed-out while waiting for Process to return. -- {self!r}" ) else: self.child.join() if self.is_alive: return None exitcode = self.exitcode if exitcode != 0: raise exceptions.ProcessWaitError( f"Process finished with a non-zero exitcode ({exitcode}). -- {self!r}", exitcode, self, ) try: self._result = serializer.loads(self._result_sock.recv()) except zmq.error.Again: raise exceptions.ProcessWaitError( "The Process died before sending its return value. " "It probably crashed, got killed, or exited without warning.", exitcode, ) self._has_returned = True self._cleanup() return self._result
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.
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 process in self]
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 any errors that occur while waiting for a Process. The return value of failed :py:meth:`~Process.wait()` calls are substituted with the ``Exception`` that occurred. :return: A ``list`` containing the values returned by child Processes of this Context.
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 namespace. :return: A :py:class:`State` object.
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) @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.* :param \*\*process_kwargs: .. include:: /api/context/params/process_kwargs.rst :return: The :py:class:`Process` instance produced.
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( self._process(target, **process_kwargs) for _ in range(count) for target in targets )
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: .. include:: /api/context/params/process_kwargs.rst :return: A ``ProcessList`` of the :py:class:`Process` instance(s) produced.
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): continue else: d2[k] = v if len(d2.keys()) == len(d.keys()): result.append(d2) return for k,v in d.items(): if isinstance(v, Iterable): for i in v: dprime = dict(**d) dprime[k] = i f(dprime) break f(scheduledict) return result
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_schedule): # and not has_interval): interval_min = 3600 for s in f.schedule: interval = schedule_next(s, t) if interval < interval_min: interval_min = interval return interval_min
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 from <t> until <interval> has passed since <tLast> or 0 if it's overdue. ∗ If a schedule is passed but no interval, figure out when next to run by parsing the schedule according to the following rules: ∗ If all of second, minute, hour, day_of_week/day_of_month, month, year are specified, then the time to run is singular and the function will run only once at that time. If it has not happened yet, return the number of seconds from <t> until that time, otherwise return -1. ∗ If one or more are unspecified, then they are treated as open slots. return the number of seconds from <t> until the time next fits within the specified constraints, or if it never will again return -1. ∗ Only one of day_of_week and day_of_month may be specified. if both are specified, then day_of_month is used and day_of_week is ignored. ∗ If all are unspecified treat it as having no schedule specified ∗ If both a schedule and an interval are specified, TODO but it should do something along the lines of finding the next multiple of interval from tLast that fits the schedule spec and returning the number of seconds until then. NOTE: If the time until the next event is greater than an hour in the future, this function will return the number of seconds until the top of the next hour (1-3600). Be sure to continue checking until this function returns 0.
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["mentions"] if user["username"].casefold() not in exclude] return users
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_visibility, status_visibility)]
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: return "{} {} {}".format(spec_dice(spec[1]), spec[0], spec_dice(spec[2])) else: raise ValueError("Invalid dice specification")
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 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] elif spec[2][0] == "r": roll = spec[2] if (c == None or roll == None): return ('*', roll_dice(spec[1]), roll_dice(spec[2])) else: if (c[1] > 50): raise SillyDiceError("I don't have that many dice!") return ("x", [roll_dice(roll) for i in range(c[1])]) if spec[0] in ops: return (spec[0], roll_dice(spec[1]), roll_dice(spec[2])) else: raise ValueError("Invalid dice specification")
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 + k, length - k + 1, k): if string[i:i + k] != string[j:j + k]: break count += 1 if count > 0 and count >= max_count: max_count = count max_k = k if max_count > 0: if last_repeat < i: repeats.append(Repeat(last_repeat, i)) repeats.append(Repeat(i, i + max_k, max_count)) last_repeat = i + max_k * (max_count + 1) i += max_k * (max_count + 1) if last_repeat < i: repeats.append(Repeat(last_repeat, i)) return repeats
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 data["model"]["extends"] = self.extends data["model"]["get"] = self.allows_get data["model"]["update"] = self.allows_update data["model"]["create"] = self.allows_create data["model"]["delete"] = self.allows_delete data["model"]["root"] = self.is_root data["model"]["userlabel"] = self.userlabel data["model"]["template"] = self.template data["model"]["allowed_job_commands"] = self.allowed_job_commands data["attributes"] = [] for attribute in self.attributes: data["attributes"].append(attribute.to_dict()) data["children"] = [] for api in self.child_apis: data["children"].append(api.to_dict()) return data
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 [] 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 self.allows_delete = model["delete"] if "delete" in model else False self.is_root = model["root"] if "root" in model else False self.userlabel = model["userlabel"] if "userlabel" in model else None self.template = model["template"] if "template" in model else False self.allowed_job_commands = model["allowed_job_commands"] if "allowed_job_commands" in model else None if "attributes" in data: self.attributes = self._get_attributes(data["attributes"]) if "children" in data: self.child_apis = self._get_apis(data["children"])
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_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) self.base_attrs = json_config_data['base_attrs'] self.generic_enums = json_config_data['generic_enums'] self.named_entity_attrs = json_config_data['named_entity_attrs'] self.overide_generic_enums = json_config_data['overide_generic_enums'] self.list_subtypes_generic = json_config_data['list_subtypes_generic'] for enum_name, values in self.generic_enums.iteritems(): enum_attr = SpecificationAttribute() enum_attr.name = enum_name enum_attr.allowed_choices = values self.generic_enum_attrs.append(enum_attr) else: Printer.log("Configuration file missing: %s" % (config_file))
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() 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, filename="index.js", template_name="model_index.js.tpl", class_prefix = self._class_prefix, model_list = sorted(self.model_list)) self.write(destination = self.enum_directory, filename="index.js", template_name="enum_index.js.tpl", class_prefix = self._class_prefix, enum_list = sorted(self.enum_list)) self._write_locales(specifications)
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 # optional params: whatever that is needed from inside the Jinja template self.write(destination = self.abstract_directory, filename = filename, template_name = "abstract_named_entity.js.tpl", class_prefix = self._class_prefix, superclass_name = superclass_name)
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, enum_name) self.write(destination = self.enum_directory, filename=filename, template_name="enum.js.tpl", class_prefix = self._class_prefix, enum_name = enum_name, allowed_choices = set(attribute.allowed_choices))
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"): return "integer" if type_name.lower() in ("date", "datetime", "time"): return "time" if type_name.lower() in ("double", "float", "long"): return "float" if type_name.lower() in ("list", "array"): return "list" if type_name.lower() in ("object", "dict"): return "object" if "array" in type_name.lower(): return "list" return "string"
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_methods_cache[language] = method if method: return method(name) else: return name module = importlib.import_module('.lang.%s' % language, package="monolithe.generators") if not hasattr(module, 'get_idiomatic_name'): cls.idiomatic_methods_cache[language] = None return name method = getattr(module, 'get_idiomatic_name') cls.idiomatic_methods_cache[language] = method return method(name)
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
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[language] = method if method: return method(type_name, sub_type) else: return type_name module = importlib.import_module('.lang.%s' % language, package="monolithe.generators") if not hasattr(module, 'get_type_name'): cls.type_methods_cache[language] = None return type_name method = getattr(module, 'get_type_name') cls.type_methods_cache[language] = method return method(type_name, sub_type)
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
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 "List" elif type_name == "float": return "float" else: return "String"
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, root_api=self.api_root, api_prefix=self.api_prefix, product_name=self._product_name, name=self._name, header=self.header_content, version_string=self._api_version_string, package_prefix=self._package_prefix, library_version=self.library_version)
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" % st if type_name == "integer": return "int" if type_name == "time": return "float64" return "interface{}"
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, root_api=self.api_root, api_prefix=self.api_prefix, product_name=self._product_name, name=self._name, header=self.header_content, version_string=self._api_version_string, package_name=self._package_name)
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_section(section): for attribute in self.attrs_defaults.options(section): defaults[attribute] = self.attrs_defaults.get(section, attribute) self.write(destination=self.output_directory, filename=filename, template_name="model.cs.tpl", specification=specification, specification_set=specification_set, version=self.api_version, name=self._name, class_prefix=self._class_prefix, product_accronym=self._product_accronym, override_content=override_content, superclass_name=superclass_name, header=self.header_content, version_string=self._api_version_string, package_name=self._package_name, attribute_defaults=defaults) return (filename, specification.entity_name)
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, filename=filename, template_name="fetcher.cs.tpl", specification=specification, specification_set=specification_set, class_prefix=self._class_prefix, product_accronym=self._product_accronym, override_content=override_content, header=self.header_content, name=self._name, version_string=self._api_version_string, package_name=self._package_name) return (filename, specification.entity_name_plural)
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 elif attribute.type == "object": attr_type = "Object" if self.attrs_types.has_option(specification.entity_name, attribute.local_name): type = self.attrs_types.get(specification.entity_name, attribute.local_name) if type: attr_type = type attribute.local_type = attr_type elif attribute.type == "list": if attribute.subtype == "enum": enum_subtype = attribute.local_name[0:1].upper() + attribute.local_name[1:] attribute.local_type = "System.Collections.Generic.List<E" + enum_subtype + ">" elif attribute.subtype == "object": attr_subtype = "JObject" if self.attrs_types.has_option(specification.entity_name, attribute.local_name): subtype = self.attrs_types.get(specification.entity_name, attribute.local_name) if subtype: attr_subtype = subtype attribute.local_type = "System.Collections.Generic.List<" + attr_subtype + ">" elif attribute.subtype == "entity": attribute.local_type = "System.Collections.Generic.List<JObject>" else: attribute.local_type = "System.Collections.Generic.List<String>"
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_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 None else None data["max_value"] = int(self.max_value) if self.max_value is not None else None data["min_length"] = int(self.min_length) if self.min_length is not None else None data["min_value"] = int(self.min_value) if self.min_value is not None else None data["orderable"] = self.orderable data["read_only"] = self.read_only data["required"] = self.required data["transient"] = self.transient data["unique"] = self.unique data["uniqueScope"] = self.unique_scope if self.unique_scope and len(self.unique_scope) else None data["subtype"] = self.subtype if self.subtype and len(self.subtype) else None data["userlabel"] = self.userlabel if self.userlabel and len(self.userlabel) else None return data
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 else "BaseObject" defaults = {} section = specification.entity_name if self.attrs_defaults.has_section(section): for attribute in self.attrs_defaults.options(section): defaults[attribute] = self.attrs_defaults.get(section, attribute) entity_includes = self._get_entity_list_filter(self.inventory_entities, section, "includes") entity_excludes = self._get_entity_list_filter(self.inventory_entities, section, "excludes") entity_name_attr = "id" if self.inventory_entities.has_section(section): if self.inventory_entities.has_option(section, "name"): entity_name_attr = self.inventory_entities.get(section, "name") self.write(destination=output_directory, filename=filename, template_name=template_file, specification=specification, specification_set=specification_set, version=self.api_version, name=self._name, class_prefix=self._class_prefix, product_accronym=self._product_accronym, override_content=override_content, superclass_name=superclass_name, header=self.header_content, version_string=self._api_version_string, package_name=package_name, attribute_defaults=defaults, entity_name_attr=entity_name_attr, root_api=self.api_root, entity_includes=entity_includes, entity_excludes=entity_excludes) return (filename, specification.entity_name)
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.write(destination=destination, filename=filename, template_name=template_file, header=self.header_content, specification=specification, package_name=package_name, enum_name=enum_name, attribute=attribute) return (filename, specification.entity_name)
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) f.close()
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 passed to the template
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", version=self.api_version, product_accronym=self._product_accronym, class_prefix=self._class_prefix, root_api=self.api_root, api_prefix=self.api_prefix, override_content=override_content, header=self.header_content)
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, header=self.header_content)
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 == self.api_root else "NURESTObject" self.write(destination=self.output_directory, filename=filename, template_name="model.py.tpl", specification=specification, specification_set=specification_set, version=self.api_version, class_prefix=self._class_prefix, product_accronym=self._product_accronym, override_content=override_content, superclass_name=superclass_name, constants=constants, header=self.header_content) self.model_filenames[filename] = specification.entity_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_prefix, product_accronym=self._product_accronym, header=self.header_content)
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(destination=destination, filename=filename, template_name="fetcher.py.tpl", specification=specification, specification_set=specification_set, class_prefix=self._class_prefix, product_accronym=self._product_accronym, override_content=override_content, header=self.header_content) self.fetcher_filenames[filename] = specification.entity_name_plural
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" % (name, choice.upper())] = choice return constants
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, enterprise=self.enterprise, version=self.apiversion, specification=configuration.specification, sdk_identifier=self.sdk_identifier, monolithe_config=self.monolithe_config, parent_resource=configuration.parent_resource_name, parent_id=configuration.parent_id, default_values=configuration.default_values) result.add_report(configuration.specification.rest_name + ".spec", runner.run()) return result
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): new_data = [] if name in annotation_list: data_list = column(data, i + 1)[1:] for k in data_list: temp_data = {} for j in annotation_list[name]: if k == j['id']: temp_data['y'] = k temp_data['dataLabels'] = {'enabled': True, 'format': j['value']} else: temp_data['y'] = k new_data.append(temp_data) series = {"name": name, "data": new_data} else: series = {"name": name, "data": column(data, i + 1)[1:]} if 'colors' in options and len(options['colors']) > i: series['color'] = options['colors'][i] serieses.append(series) else: for i, name in enumerate(series_names): series = {"name": name, "data": column(data, i+1)[1:]} # If colors was passed then add color for the serieses if 'colors' in options and len(options['colors']) > i: series['color'] = options['colors'][i] serieses.append(series) serieses = self.add_series_options(serieses) return serieses
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], ] sd = SimpleDataSource(data) hc = BaseHighCharts(sd) hc.get_series() would be [{"name": "Sales", "data": [1000, 1170, 660, 1030]}, {"name": "Expenses", "data": [400, 460, 1120, 540]} ....]
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) encoding = self.options.get('encoding', env.config.source_encoding) with io.open(abspath, 'rt', encoding=encoding) as stream: spec = yaml.load(stream, _YamlOrderedLoader) self.spec = spec self.paths = spec[self.path_path] self.definitions = spec[self.models_path] self.openapi_version = spec.get('swagger', None) or spec['openapi'] self.options.setdefault('uri', 'file://%s' % abspath)
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