INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
save_game () asks the underlying game object ( _g ) to dump the contents of itself as JSON and then returns the JSON to | def save_game(self):
"""
save_game() asks the underlying game object (_g) to dump the contents of
itself as JSON and then returns the JSON to
:return: A JSON representation of the game object
"""
logging.debug("save_game called.")
logging.debug("Validating game ... |
guess () allows a guess to be made. Before the guess is made the method checks to see if the game has been won lost or there are no tries remaining. It then creates a return object stating the number of bulls ( direct matches ) cows ( indirect matches ) an analysis of the guess ( a list of analysis objects ) and a stat... | def guess(self, *args):
"""
guess() allows a guess to be made. Before the guess is made, the method
checks to see if the game has been won, lost, or there are no tries
remaining. It then creates a return object stating the number of bulls
(direct matches), cows (indirect matches)... |
Simple method to form a start again message and give the answer in readable form. | def _start_again(self, message=None):
"""Simple method to form a start again message and give the answer in readable form."""
logging.debug("Start again message delivered: {}".format(message))
the_answer = self._get_text_answer()
return "{0} The correct answer was {1}. Please start a ne... |
A helper method to provide validation of the game object ( _g ). If the game object does not exist or if ( for any reason ) the object is not a GameObject then an exception will be raised. | def _validate_game_object(self, op="unknown"):
"""
A helper method to provide validation of the game object (_g). If the
game object does not exist or if (for any reason) the object is not a GameObject,
then an exception will be raised.
:param op: A string describing the operati... |
Adds useful global items to the context for use in templates. | def extra_context(request):
"""Adds useful global items to the context for use in templates.
* *request*: the request object
* *HOST*: host name of server
* *IN_ADMIN*: True if you are in the django admin area
"""
host = os.environ.get('DJANGO_LIVE_TEST_SERVER_ADDRESS', None) \
or reque... |
Adds options to: func: scipy. fftpack. rfft: | def fft(values, freq=None, timestamps=None, fill_missing=False):
"""
Adds options to :func:`scipy.fftpack.rfft`:
* *freq* is the frequency the samples were taken at
* *timestamps* is the time the samples were taken, to help with filling in missing data if *fill_missing* is true
"""
# ==========... |
Create the challenge on the server | def create(self, server):
"""Create the challenge on the server"""
return server.post(
'challenge_admin',
self.as_payload(),
replacements={'slug': self.slug}) |
Update existing challenge on the server | def update(self, server):
"""Update existing challenge on the server"""
return server.put(
'challenge_admin',
self.as_payload(),
replacements={'slug': self.slug}) |
Check if a challenge exists on the server | def exists(self, server):
"""Check if a challenge exists on the server"""
try:
server.get(
'challenge',
replacements={'slug': self.slug})
except Exception:
return False
return True |
Retrieve a challenge from the MapRoulette server: type server | def from_server(cls, server, slug):
"""Retrieve a challenge from the MapRoulette server
:type server
"""
challenge = server.get(
'challenge',
replacements={'slug': slug})
return cls(
**challenge) |
Extends: func: logthing. utils. default_logging_dict with django specific values. | def django_logging_dict(log_dir, handlers=['file'], filename='debug.log'):
"""Extends :func:`logthing.utils.default_logging_dict` with django
specific values.
"""
d = default_logging_dict(log_dir, handlers, filename)
d['handlers'].update({
'mail_admins':{
'level':'ERROR',
... |
Returns position data. | def get_position(self, position_id):
"""
Returns position data.
http://dev.wheniwork.com/#get-existing-position
"""
url = "/2/positions/%s" % position_id
return self.position_from_json(self._get_resource(url)["position"]) |
Returns a list of positions. | def get_positions(self):
"""
Returns a list of positions.
http://dev.wheniwork.com/#listing-positions
"""
url = "/2/positions"
data = self._get_resource(url)
positions = []
for entry in data['positions']:
positions.append(self.position_from_j... |
Creates a position | def create_position(self, params={}):
"""
Creates a position
http://dev.wheniwork.com/#create-update-position
"""
url = "/2/positions/"
body = params
data = self._post_resource(url, body)
return self.position_from_json(data["position"]) |
Prints to the elog. Parameters ---------- | def print2elog(author='', title='', text='', link=None, file=None, now=None):
"""
Prints to the elog.
Parameters
----------
author : str, optional
Author of the elog.
title : str, optional
Title of the elog.
link : str, optional
Path to a thumbnail.
file : s... |
Similar to Python s built - in open () function. | def fopen(name, mode='r', buffering=-1):
"""Similar to Python's built-in `open()` function."""
f = _fopen(name, mode, buffering)
return _FileObjectThreadWithContext(f, mode, buffering) |
Print Source Lines of Code and export to file. | def sloccount():
'''Print "Source Lines of Code" and export to file.
Export is hudson_ plugin_ compatible: sloccount.sc
requirements:
- sloccount_ should be installed.
- tee and pipes are used
options.paved.pycheck.sloccount.param
.. _sloccount: http://www.dwheeler.com/sloccount/
.... |
passive check of python programs by pyflakes. | def pyflakes():
'''passive check of python programs by pyflakes.
requirements:
- pyflakes_ should be installed. ``easy_install pyflakes``
options.paved.pycheck.pyflakes.param
.. _pyflakes: http://pypi.python.org/pypi/pyflakes
'''
# filter out subpackages
packages = [x for x in opti... |
Gaussian function of the form: math: \\ frac { 1 } { \\ sqrt { 2 \\ pi } \\ sigma } e^ { - \\ frac { ( x - \\ mu ) ^2 } { 2 \\ sigma^2 }}. | def gaussian(x, mu, sigma):
"""
Gaussian function of the form :math:`\\frac{1}{\\sqrt{2 \\pi}\\sigma} e^{-\\frac{(x-\\mu)^2}{2\\sigma^2}}`.
.. versionadded:: 1.5
Parameters
----------
x : float
Function variable :math:`x`.
mu : float
Mean of the Gaussian function.
sigma... |
Handle HTTP exception | def http_exception_error_handler(
exception):
"""
Handle HTTP exception
:param werkzeug.exceptions.HTTPException exception: Raised exception
A response is returned, as formatted by the :py:func:`response` function.
"""
assert issubclass(type(exception), HTTPException), type(exception)... |
Returns True if the value given is a valid CSS colour i. e. matches one of the regular expressions in the module or is in the list of predetefined values by the browser. | def is_colour(value):
"""Returns True if the value given is a valid CSS colour, i.e. matches one
of the regular expressions in the module or is in the list of
predetefined values by the browser.
"""
global PREDEFINED, HEX_MATCH, RGB_MATCH, RGBA_MATCH, HSL_MATCH, HSLA_MATCH
value = value.strip()
... |
Formats time as the string HH: MM: SS. | def format_time(seconds):
"""Formats time as the string "HH:MM:SS"."""
timedelta = datetime.timedelta(seconds=int(seconds))
mm, ss = divmod(timedelta.seconds, 60)
if mm < 60:
return "%02d:%02d" % (mm, ss)
hh, mm = divmod(mm, 60)
if hh < 24:
retur... |
Flat plate frictional resistance of the ship according to ITTC formula. ref: https:// ittc. info/ media/ 2021/ 75 - 02 - 02 - 02. pdf | def frictional_resistance_coef(length, speed, **kwargs):
"""
Flat plate frictional resistance of the ship according to ITTC formula.
ref: https://ittc.info/media/2021/75-02-02-02.pdf
:param length: metres length of the vehicle
:param speed: m/s speed of the vehicle
:param kwargs: optional could... |
Reynold number utility function that return Reynold number for vehicle at specific length and speed. Optionally it can also take account of temperature effect of sea water. | def reynolds_number(length, speed, temperature=25):
"""
Reynold number utility function that return Reynold number for vehicle at specific length and speed.
Optionally, it can also take account of temperature effect of sea water.
Kinematic viscosity from: http://web.mit.edu/seawater/2017_MIT_Seawat... |
Froude number utility function that return Froude number for vehicle at specific length and speed. | def froude_number(speed, length):
"""
Froude number utility function that return Froude number for vehicle at specific length and speed.
:param speed: m/s speed of the vehicle
:param length: metres length of the vehicle
:return: Froude number of the vehicle (dimensionless)
"""
g = 9.80665 ... |
Residual resistance coefficient estimation from slenderness function prismatic coefficient and Froude number. | def residual_resistance_coef(slenderness, prismatic_coef, froude_number):
"""
Residual resistance coefficient estimation from slenderness function, prismatic coefficient and Froude number.
:param slenderness: Slenderness coefficient dimensionless :math:`L/(∇^{1/3})` where L is length of ship, ∇ is displace... |
Assign values for the main dimension of a ship. | def dimension(self, length, draught, beam, speed,
slenderness_coefficient, prismatic_coefficient):
"""
Assign values for the main dimension of a ship.
:param length: metres length of the vehicle
:param draught: metres draught of the vehicle
:param beam: metres b... |
Return resistance of the vehicle. | def resistance(self):
"""
Return resistance of the vehicle.
:return: newton the resistance of the ship
"""
self.total_resistance_coef = frictional_resistance_coef(self.length, self.speed) + \
residual_resistance_coef(self.slenderness_coefficient,
... |
Return the maximum deck area of the ship | def maximum_deck_area(self, water_plane_coef=0.88):
"""
Return the maximum deck area of the ship
:param water_plane_coef: optional water plane coefficient
:return: Area of the deck
"""
AD = self.beam * self.length * water_plane_coef
return AD |
Total propulsion power of the ship. | def prop_power(self, propulsion_eff=0.7, sea_margin=0.2):
"""
Total propulsion power of the ship.
:param propulsion_eff: Shaft efficiency of the ship
:param sea_margin: Sea margin take account of interaction between ship and the sea, e.g. wave
:return: Watts shaft propulsion pow... |
Change the font size for the title x and y labels and x and y tick labels for axis * ax * to * fontsize *. | def axesfontsize(ax, fontsize):
"""
Change the font size for the title, x and y labels, and x and y tick labels for axis *ax* to *fontsize*.
"""
items = ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels())
for item in items:
item.set_fontsize(fontsize) |
Scale the number of tick labels in x and y by * x_fraction * and * y_fraction * respectively. | def less_labels(ax, x_fraction=0.5, y_fraction=0.5):
"""
Scale the number of tick labels in x and y by *x_fraction* and *y_fraction* respectively.
"""
nbins = _np.size(ax.get_xticklabels())
ax.locator_params(nbins=_np.floor(nbins*x_fraction), axis='x')
nbins = _np.size(ax.get_yticklabels())
... |
Configure the api to use given url and token or to get them from the Config. | def configure(self, url=None, token=None, test=False):
"""
Configure the api to use given url and token or to get them from the
Config.
"""
if url is None:
url = Config.get_value("url")
if token is None:
token = Config.get_value("token")
... |
Send zipfile to TMC for given exercise | def send_zip(self, exercise, file, params):
"""
Send zipfile to TMC for given exercise
"""
resp = self.post(
exercise.return_url,
params=params,
files={
"submission[file]": ('submission.zip', file)
},
data={
... |
Ensures that the request url is valid. Sometimes we have URLs that the server gives that are preformatted sometimes we need to form our own. | def _make_url(self, slug):
"""
Ensures that the request url is valid.
Sometimes we have URLs that the server gives that are preformatted,
sometimes we need to form our own.
"""
if slug.startswith("http"):
return slug
return "{0}{1}".format(self.server_... |
Does HTTP request sending/ response validation. Prevents RequestExceptions from propagating | def _do_request(self, method, slug, **kwargs):
"""
Does HTTP request sending / response validation.
Prevents RequestExceptions from propagating
"""
# ensure we are configured
if not self.configured:
self.configure()
url = self._make_url(slug)
... |
Extract json from a response. Assumes response is valid otherwise. Internal use only. | def _to_json(self, resp):
"""
Extract json from a response.
Assumes response is valid otherwise.
Internal use only.
"""
try:
json = resp.json()
except ValueError as e:
reason = "TMC Server did not send valid JSON: {0}"
... |
wraps ( instancemethod ) returns a function not an instancemethod so its repr () is all messed up ; we want the original repr to show up in the logs therefore we do this trick | def _normalize_instancemethod(instance_method):
"""
wraps(instancemethod) returns a function, not an instancemethod so its repr() is all messed up;
we want the original repr to show up in the logs, therefore we do this trick
"""
if not hasattr(instance_method, 'im_self'):
return instance_met... |
Wrapper for gevent. joinall if the greenlet that waits for the joins is killed it kills all the greenlets it joins for. | def safe_joinall(greenlets, timeout=None, raise_error=False):
"""
Wrapper for gevent.joinall if the greenlet that waits for the joins is killed, it kills all the greenlets it
joins for.
"""
greenlets = list(greenlets)
try:
gevent.joinall(greenlets, timeout=timeout, raise_error=raise_erro... |
Plots an array of * images * to a single window of size * figsize * with * rows * and * columns *. | def imshow_batch(images, cbar=True, show=True, pdf=None, figsize=(16, 12), rows=2, columns=2, cmap=None, **kwargs):
"""
Plots an array of *images* to a single window of size *figsize* with *rows* and *columns*.
* *cmap*: Specifies color map
* *cbar*: Add color bars
* *show*: If false, dismisses eac... |
Creates an error from the given code and args and kwargs. | def error(code: int, *args, **kwargs) -> HedgehogCommandError:
"""
Creates an error from the given code, and args and kwargs.
:param code: The acknowledgement code
:param args: Exception args
:param kwargs: Exception kwargs
:return: the error for the given acknowledgement code
"""
# TOD... |
Creates an error Acknowledgement message. The message s code and message are taken from this exception. | def to_message(self):
"""
Creates an error Acknowledgement message.
The message's code and message are taken from this exception.
:return: the message representing this exception
"""
from .messages import ack
return ack.Acknowledgement(self.code, self.args[0] if ... |
Clean up extra files littering the source tree. | def clean(options, info):
"""Clean up extra files littering the source tree.
options.paved.clean.dirs: directories to search recursively
options.paved.clean.patterns: patterns to search for and remove
"""
info("Cleaning patterns %s", options.paved.clean.patterns)
for wd in options.paved.clean.d... |
print paver options. | def printoptions():
'''print paver options.
Prettified by json.
`long_description` is removed
'''
x = json.dumps(environment.options,
indent=4,
sort_keys=True,
skipkeys=True,
cls=MyEncoder)
print(x) |
\ Parses a binary protobuf message into a Message object. | def parse(self, data: RawMessage) -> Message:
"""\
Parses a binary protobuf message into a Message object.
"""
try:
return self.receiver.parse(data)
except KeyError as err:
raise UnknownCommandError from err
except DecodeError as err:
r... |
Sets up a figure of size * figsize * with a number of rows ( * rows * ) and columns ( * cols * ). \ * \ * kwargs passed through to: meth: matplotlib. figure. Figure. add_subplot. | def setup_axes(rows=1, cols=1, figsize=(8, 6), expand=True, tight_layout=None, **kwargs):
"""
Sets up a figure of size *figsize* with a number of rows (*rows*) and columns (*cols*). \*\*kwargs passed through to :meth:`matplotlib.figure.Figure.add_subplot`.
.. versionadded:: 1.2
Parameters
--------... |
Creates a DCCGraph a root: class: Node: and the node s associated data class instance. This factory is used to get around the chicken - and - egg problem of the DCCGraph and Nodes within it having pointers to each other. | def factory(cls, data_class, **kwargs):
"""Creates a ``DCCGraph``, a root :class:`Node`: and the node's
associated data class instance. This factory is used to get around
the chicken-and-egg problem of the ``DCCGraph`` and ``Nodes`` within
it having pointers to each other.
:par... |
Creates a DCCGraph and corresponding nodes. The root_args parm is a dictionary specifying the parameters for creating a: class: Node and its corresponding: class: BaseNodeData subclass from the data_class specified. The children parm is an iterable containing pairs of dictionaries and iterables where the dictionaries s... | def factory_from_graph(cls, data_class, root_args, children):
"""Creates a ``DCCGraph`` and corresponding nodes. The root_args parm
is a dictionary specifying the parameters for creating a :class:`Node`
and its corresponding :class:`BaseNodeData` subclass from the
data_class specified. ... |
Searches the data nodes that are associated with this graph using the key word arguments as a filter and returns a: class: django. db. models. query. QuerySet of the attached: class: Node objects. | def find_nodes(self, **kwargs):
"""Searches the data nodes that are associated with this graph using
the key word arguments as a filter and returns a
:class:`django.db.models.query.QuerySet`` of the attached
:class:`Node` objects.
:param kwargs:
filter arguments app... |
Creates a new Node based on the extending class and adds it as a child to this Node. | def add_child(self, **kwargs):
"""Creates a new ``Node`` based on the extending class and adds it as
a child to this ``Node``.
:param kwargs:
arguments for constructing the data object associated with this
``Node``
:returns:
extender of the ``Node``... |
Adds the given node as a child to this one. No new nodes are created only connections are made.: param node: a Node object to connect | def connect_child(self, node):
"""Adds the given node as a child to this one. No new nodes are
created, only connections are made.
:param node:
a ``Node`` object to connect
"""
if node.graph != self.graph:
raise AttributeError('cannot connect nod... |
Returns a list of the ancestors of this node. | def ancestors(self):
"""Returns a list of the ancestors of this node."""
ancestors = set([])
self._depth_ascend(self, ancestors)
try:
ancestors.remove(self)
except KeyError:
# we weren't ancestor of ourself, that's ok
pass
return list(... |
Returns a list of the ancestors of this node but does not pass the root node even if the root has parents due to cycles. | def ancestors_root(self):
"""Returns a list of the ancestors of this node but does not pass the
root node, even if the root has parents due to cycles."""
if self.is_root():
return []
ancestors = set([])
self._depth_ascend(self, ancestors, True)
try:
... |
Returns a list of descendents of this node. | def descendents(self):
"""Returns a list of descendents of this node."""
visited = set([])
self._depth_descend(self, visited)
try:
visited.remove(self)
except KeyError:
# we weren't descendent of ourself, that's ok
pass
return list(vis... |
Returns a list of descendents of this node if the root node is in the list ( due to a cycle ) it will be included but will not pass through it. | def descendents_root(self):
"""Returns a list of descendents of this node, if the root node is in
the list (due to a cycle) it will be included but will not pass
through it.
"""
visited = set([])
self._depth_descend(self, visited, True)
try:
visited.... |
Returns True if it is legal to remove this node and still leave the graph as a single connected entity not splitting it into a forest. Only nodes with no children or those who cause a cycle can be deleted. | def can_remove(self):
"""Returns True if it is legal to remove this node and still leave the
graph as a single connected entity, not splitting it into a forest.
Only nodes with no children or those who cause a cycle can be deleted.
"""
if self.children.count() == 0:
r... |
Removes the node from the graph. Note this does not remove the associated data object. See: func: Node. can_remove for limitations on what can be deleted. | def remove(self):
"""Removes the node from the graph. Note this does not remove the
associated data object. See :func:`Node.can_remove` for limitations
on what can be deleted.
:returns:
:class:`BaseNodeData` subclass associated with the deleted Node
:raises Attri... |
Removes the node and all descendents without looping back past the root. Note this does not remove the associated data objects. | def prune(self):
"""Removes the node and all descendents without looping back past the
root. Note this does not remove the associated data objects.
:returns:
list of :class:`BaseDataNode` subclassers associated with the
removed ``Node`` objects.
"""
targ... |
Returns a list of nodes that would be removed if prune were called on this element. | def prune_list(self):
"""Returns a list of nodes that would be removed if prune were called
on this element.
"""
targets = self.descendents_root()
try:
targets.remove(self.graph.root)
except ValueError:
# root wasn't in the target list, no problem
... |
Called to verify that the given rule can become a child of the current node. | def _child_allowed(self, child_rule):
"""Called to verify that the given rule can become a child of the
current node.
:raises AttributeError:
if the child is not allowed
"""
num_kids = self.node.children.count()
num_kids_allowed = len(self.rule.children)
... |
Add a child path in the: class: Flow graph using the given: class: Rule subclass. This will create a new child: class: Node in the associated: class: Flow object s state graph with a new: class: FlowNodeData instance attached. The: class: Rule must be allowed at this stage of the flow according to the hierarchy of rule... | def add_child_rule(self, child_rule):
"""Add a child path in the :class:`Flow` graph using the given
:class:`Rule` subclass. This will create a new child :class:`Node` in
the associated :class:`Flow` object's state graph with a new
:class:`FlowNodeData` instance attached.
... |
Adds a connection to an existing rule in the: class Flow graph. The given: class Rule subclass must be allowed to be connected at this stage of the flow according to the hierarchy of rules. | def connect_child(self, child_node):
"""Adds a connection to an existing rule in the :class`Flow` graph.
The given :class`Rule` subclass must be allowed to be connected at
this stage of the flow according to the hierarchy of rules.
:param child_node:
``FlowNodeData`` to att... |
Returns True if there is a: class: State object that uses this Flow | def in_use(self):
"""Returns True if there is a :class:`State` object that uses this
``Flow``"""
state = State.objects.filter(flow=self).first()
return bool(state) |
Factory method for a running state based on a flow. Creates and returns a State object and calls the associated: func: Rule. on_enter method. | def start(self, flow):
"""Factory method for a running state based on a flow. Creates and
returns a ``State`` object and calls the associated
:func:`Rule.on_enter` method.
:param flow:
:class:`Flow` which defines this state machine
:returns:
newly crea... |
Proceeds to the next step in the flow. Calls the associated: func: Rule. on_leave method for the for the current rule and the: func: Rule. on_enter for the rule being entered. If the current step in the flow is multipath then a valid: class: Rule subclass must be passed into this call. | def next_state(self, rule=None):
"""Proceeds to the next step in the flow. Calls the associated
:func:`Rule.on_leave` method for the for the current rule and the
:func:`Rule.on_enter` for the rule being entered. If the current step
in the flow is multipath then a valid :class:`Rule` su... |
Returns location data. | def get_location(self, location_id):
"""
Returns location data.
http://dev.wheniwork.com/#get-existing-location
"""
url = "/2/locations/%s" % location_id
return self.location_from_json(self._get_resource(url)["location"]) |
Returns a list of locations. | def get_locations(self):
"""
Returns a list of locations.
http://dev.wheniwork.com/#listing-locations
"""
url = "/2/locations"
data = self._get_resource(url)
locations = []
for entry in data['locations']:
locations.append(self.location_from_j... |
The: math: X weighted properly by the errors from * y_error * | def X(self):
"""
The :math:`X` weighted properly by the errors from *y_error*
"""
if self._X is None:
X = _copy.deepcopy(self.X_unweighted)
# print 'X shape is {}'.format(X.shape)
for i, el in enumerate(X):
X[i, :] = el/self.y_error[i]
... |
The: math: X weighted properly by the errors from * y_error * | def y(self):
"""
The :math:`X` weighted properly by the errors from *y_error*
"""
if self._y is None:
self._y = self.y_unweighted/self.y_error
return self._y |
Using the result of the linear least squares the result of: math: X_ { ij } \\ beta_i | def y_fit(self):
"""
Using the result of the linear least squares, the result of :math:`X_{ij}\\beta_i`
"""
if self._y_fit is None:
self._y_fit = _np.dot(self.X_unweighted, self.beta)
return self._y_fit |
The result: math: \\ beta of the linear least squares | def beta(self):
"""
The result :math:`\\beta` of the linear least squares
"""
if self._beta is None:
# This is the linear least squares matrix formalism
self._beta = _np.dot(_np.linalg.pinv(self.X) , self.y)
return self._beta |
The covariance matrix for the result: math: \\ beta | def covar(self):
"""
The covariance matrix for the result :math:`\\beta`
"""
if self._covar is None:
self._covar = _np.linalg.inv(_np.dot(_np.transpose(self.X), self.X))
return self._covar |
The reduced chi - square of the linear least squares | def chisq_red(self):
"""
The reduced chi-square of the linear least squares
"""
if self._chisq_red is None:
self._chisq_red = chisquare(self.y_unweighted.transpose(), _np.dot(self.X_unweighted, self.beta), self.y_error, ddof=3, verbose=False)
return self._chisq_red |
Create the task on the server | def create(self, server):
"""Create the task on the server"""
if len(self.geometries) == 0:
raise Exception('no geometries')
return server.post(
'task_admin',
self.as_payload(),
replacements={
'slug': self.__challenge__.slug,
... |
Update existing task on the server | def update(self, server):
"""Update existing task on the server"""
return server.put(
'task_admin',
self.as_payload(),
replacements={
'slug': self.__challenge__.slug,
'identifier': self.identifier}) |
Retrieve a task from the server | def from_server(cls, server, slug, identifier):
"""Retrieve a task from the server"""
task = server.get(
'task',
replacements={
'slug': slug,
'identifier': identifier})
return cls(**task) |
Formats a string with color | def formatter(color, s):
""" Formats a string with color """
if no_coloring:
return s
return "{begin}{s}{reset}".format(begin=color, s=s, reset=Colors.RESET) |
Reloads all attributes from the database.: param fields: ( optional ) args list of fields to reload: param max_depth: ( optional ) depth of dereferencing to follow.. versionadded:: 0. 1. 2.. versionchanged:: 0. 6 Now chainable.. versionchanged:: 0. 9 Can provide specific fields to reload | def reload(self, *fields, **kwargs):
"""Reloads all attributes from the database.
:param fields: (optional) args list of fields to reload
:param max_depth: (optional) depth of dereferencing to follow
.. versionadded:: 0.1.2
.. versionchanged:: 0.6 Now chainable
.. versio... |
Uses ImageMagick <http:// www. imagemagick. org/ > _ to convert an input * file_in * pdf to a * file_out * png. ( Untested with other formats. ) | def pdf2png(file_in, file_out):
"""
Uses `ImageMagick <http://www.imagemagick.org/>`_ to convert an input *file_in* pdf to a *file_out* png. (Untested with other formats.)
Parameters
----------
file_in : str
The path to the pdf file to be converted.
file_out : str
The path to t... |
Returns user profile data. | def get_user(self, user_id):
"""
Returns user profile data.
http://dev.wheniwork.com/#get-existing-user
"""
url = "/2/users/%s" % user_id
return self.user_from_json(self._get_resource(url)["user"]) |
Returns a list of users. | def get_users(self, params={}):
"""
Returns a list of users.
http://dev.wheniwork.com/#listing-users
"""
param_list = [(k, params[k]) for k in sorted(params)]
url = "/2/users/?%s" % urlencode(param_list)
data = self._get_resource(url)
users = []
... |
Attempt to set the virtualenv activate command if it hasn t been specified. | def _setVirtualEnv():
"""Attempt to set the virtualenv activate command, if it hasn't been specified.
"""
try:
activate = options.virtualenv.activate_cmd
except AttributeError:
activate = None
if activate is None:
virtualenv = path(os.environ.get('VIRTUAL_ENV', ''))
... |
Run the given command inside the virtual environment if available: | def shv(command, capture=False, ignore_error=False, cwd=None):
"""Run the given command inside the virtual environment, if available:
"""
_setVirtualEnv()
try:
command = "%s; %s" % (options.virtualenv.activate_cmd, command)
except AttributeError:
pass
return bash(command, capture... |
Recursively update the destination dict - like object with the source dict - like object. | def update(dst, src):
"""Recursively update the destination dict-like object with the source dict-like object.
Useful for merging options and Bunches together!
Based on:
http://code.activestate.com/recipes/499335-recursively-update-a-dictionary-without-hitting-py/#c1
"""
stack = [(dst, src)]
... |
Send the given arguments to pip install. | def pip_install(*args):
"""Send the given arguments to `pip install`.
"""
download_cache = ('--download-cache=%s ' % options.paved.pip.download_cache) if options.paved.pip.download_cache else ''
shv('pip install %s%s' % (download_cache, ' '.join(args))) |
When I Work GET method. Return representation of the requested resource. | def _get_resource(self, url, data_key=None):
"""
When I Work GET method. Return representation of the requested
resource.
"""
headers = {"Accept": "application/json"}
if self.token:
headers["W-Token"] = "%s" % self.token
response = WhenIWork_DAO().getU... |
When I Work PUT method. | def _put_resource(self, url, body):
"""
When I Work PUT method.
"""
headers = {"Content-Type": "application/json",
"Accept": "application/json"}
if self.token:
headers["W-Token"] = "%s" % self.token
response = WhenIWork_DAO().putURL(url, hea... |
When I Work POST method. | def _post_resource(self, url, body):
"""
When I Work POST method.
"""
headers = {"Content-Type": "application/json",
"Accept": "application/json"}
if self.token:
headers["W-Token"] = "%s" % self.token
response = WhenIWork_DAO().postURL(url, ... |
When I Work DELETE method. | def _delete_resource(self, url):
"""
When I Work DELETE method.
"""
headers = {"Content-Type": "application/json",
"Accept": "application/json"}
if self.token:
headers["W-Token"] = "%s" % self.token
response = WhenIWork_DAO().deleteURL(url, ... |
List shifts | def get_shifts(self, params={}):
"""
List shifts
http://dev.wheniwork.com/#listing-shifts
"""
param_list = [(k, params[k]) for k in sorted(params)]
url = "/2/shifts/?%s" % urlencode(param_list)
data = self._get_resource(url)
shifts = []
locations... |
Creates a shift | def create_shift(self, params={}):
"""
Creates a shift
http://dev.wheniwork.com/#create/update-shift
"""
url = "/2/shifts/"
body = params
data = self._post_resource(url, body)
shift = self.shift_from_json(data["shift"])
return shift |
Delete existing shifts. | def delete_shifts(self, shifts):
"""
Delete existing shifts.
http://dev.wheniwork.com/#delete-shift
"""
url = "/2/shifts/?%s" % urlencode(
{'ids': ",".join(str(s) for s in shifts)})
data = self._delete_resource(url)
return data |
Removes old events. This is provided largely as a convenience for maintenance purposes ( daily_cleanup ). if an Event has passed by more than X days as defined by Lapsed and has no related special events it will be deleted to free up the event name and remove clutter. For best results set this up to run regularly as a ... | def delete_past_events(self):
"""
Removes old events. This is provided largely as a convenience for maintenance
purposes (daily_cleanup). if an Event has passed by more than X days
as defined by Lapsed and has no related special events it will be deleted
to free up the event name... |
Determines if event ended recently ( within 5 days ). Useful for attending list. | def recently_ended(self):
"""
Determines if event ended recently (within 5 days).
Useful for attending list.
"""
if self.ended():
end_date = self.end_date if self.end_date else self.start_date
if end_date >= offset.date():
return True |
Returns combined list of event and update comments. | def all_comments(self):
"""
Returns combined list of event and update comments.
"""
ctype = ContentType.objects.get(app_label__exact="happenings", model__exact='event')
update_ctype = ContentType.objects.get(app_label__exact="happenings", model__exact='update')
update_ids... |
Returns chained list of event and update images. | def get_all_images(self):
"""
Returns chained list of event and update images.
"""
self_imgs = self.image_set.all()
update_ids = self.update_set.values_list('id', flat=True)
u_images = UpdateImage.objects.filter(update__id__in=update_ids)
return list(chain(self_i... |
Gets count of all images from both event and updates. | def get_all_images_count(self):
"""
Gets count of all images from both event and updates.
"""
self_imgs = self.image_set.count()
update_ids = self.update_set.values_list('id', flat=True)
u_images = UpdateImage.objects.filter(update__id__in=update_ids).count()
coun... |
Gets images and videos to populate top assets. | def get_top_assets(self):
"""
Gets images and videos to populate top assets.
Map is built separately.
"""
images = self.get_all_images()[0:14]
video = []
if supports_video:
video = self.eventvideo_set.all()[0:10]
return list(chain(images, vid... |
Wrapper for matplotlib. pyplot. plot ()/ errorbar (). | def plot_featured(*args, **kwargs):
"""
Wrapper for matplotlib.pyplot.plot() / errorbar().
Takes options:
* 'error': if true, use :func:`matplotlib.pyplot.errorbar` instead of :func:`matplotlib.pyplot.plot`. *\*args* and *\*\*kwargs* passed through here.
* 'fig': figure to use.
* 'figlabel': f... |
Decorated methods progress will be displayed to the user as a spinner. Mostly for slower functions that do some network IO. | def decorate(msg="", waitmsg="Please wait"):
"""
Decorated methods progress will be displayed to the user as a spinner.
Mostly for slower functions that do some network IO.
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.