INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Return nodes in the path between a and b going from parent to child NOT including a | def path(self, a_hash, b_hash):
"""Return nodes in the path between 'a' and 'b' going from
parent to child NOT including 'a' """
def _path(a, b):
if a is b:
return [a]
else:
assert len(a.children) == 1
return [a] + _path(a.... |
Index of the last occurrence of x in the sequence. | def _rindex(mylist: Sequence[T], x: T) -> int:
"""Index of the last occurrence of x in the sequence."""
return len(mylist) - mylist[::-1].index(x) - 1 |
\ Returns a message consisting of header frames delimiter frame and payload frames. The payload frames may be given as sequences of bytes ( raw ) or as Message s. | def raw_to_delimited(header: Header, raw_payload: RawPayload) -> DelimitedMsg:
"""\
Returns a message consisting of header frames, delimiter frame, and payload frames.
The payload frames may be given as sequences of bytes (raw) or as `Message`s.
"""
return tuple(header) + (b'',) + tuple(raw_payload) |
\ Returns a message consisting of header frames delimiter frame and payload frames. The payload frames may be given as sequences of bytes ( raw ) or as Message s. | def to_delimited(header: Header, payload: Payload, side: CommSide) -> DelimitedMsg:
"""\
Returns a message consisting of header frames, delimiter frame, and payload frames.
The payload frames may be given as sequences of bytes (raw) or as `Message`s.
"""
return raw_to_delimited(header, [side.seriali... |
\ From a message consisting of header frames delimiter frame and payload frames return a tuple ( header payload ). The payload frames may be returned as sequences of bytes ( raw ) or as Message s. | def raw_from_delimited(msgs: DelimitedMsg) -> RawMsgs:
"""\
From a message consisting of header frames, delimiter frame, and payload frames, return a tuple `(header, payload)`.
The payload frames may be returned as sequences of bytes (raw) or as `Message`s.
"""
delim = _rindex(msgs, b'')
return ... |
\ From a message consisting of header frames delimiter frame and payload frames return a tuple ( header payload ). The payload frames may be returned as sequences of bytes ( raw ) or as Message s. | def from_delimited(msgs: DelimitedMsg, side: CommSide) -> Msgs:
"""\
From a message consisting of header frames, delimiter frame, and payload frames, return a tuple `(header, payload)`.
The payload frames may be returned as sequences of bytes (raw) or as `Message`s.
"""
header, raw_payload = raw_fro... |
Creates a figure with * \ * \ * kwargs * with a window title * title *. | def figure(title=None, **kwargs):
"""
Creates a figure with *\*\*kwargs* with a window title *title*.
Returns class :class:`matplotlib.figure.Figure`.
"""
fig = _figure(**kwargs)
if title is not None:
fig.canvas.set_window_title(title)
return fig |
Create and save an admin user. | def create_admin(username='admin', email='admin@admin.com', password='admin'):
"""Create and save an admin user.
:param username:
Admin account's username. Defaults to 'admin'
:param email:
Admin account's email address. Defaults to 'admin@admin.com'
:param password:
Admin acc... |
Returns a list of the messages from the django MessageMiddleware package contained within the given response. This is to be used during unit testing when trying to see if a message was set properly in a view. | def messages_from_response(response):
"""Returns a list of the messages from the django MessageMiddleware
package contained within the given response. This is to be used during
unit testing when trying to see if a message was set properly in a view.
:param response: HttpResponse object, likely obtaine... |
Sets up the: class: AdminSite and creates a user with the appropriate privileges. This should be called from the inheritor s: class: TestCase. setUp method. | def initiate(self):
"""Sets up the :class:`AdminSite` and creates a user with the
appropriate privileges. This should be called from the inheritor's
:class:`TestCase.setUp` method.
"""
self.site = admin.sites.AdminSite()
self.admin_user = create_admin(self.USERNAME, self... |
Authenticates the superuser account via the web login. | def authorize(self):
"""Authenticates the superuser account via the web login."""
response = self.client.login(username=self.USERNAME,
password=self.PASSWORD)
self.assertTrue(response)
self.authed = True |
Does a django test client get against the given url after logging in the admin first. | def authed_get(self, url, response_code=200, headers={}, follow=False):
"""Does a django test client ``get`` against the given url after
logging in the admin first.
:param url:
URL to fetch
:param response_code:
Expected response code from the URL fetch. This va... |
Does a django test client post against the given url after logging in the admin first. | def authed_post(self, url, data, response_code=200, follow=False,
headers={}):
"""Does a django test client ``post`` against the given url after
logging in the admin first.
:param url:
URL to fetch
:param data:
Dictionary to form contents to post
... |
This method is used for testing links that are in the change list view of the django admin. For the given instance and field name the HTML link tags in the column are parsed for a URL and then invoked with: class: AdminToolsMixin. authed_get. | def visit_admin_link(self, admin_model, instance, field_name,
response_code=200, headers={}):
"""This method is used for testing links that are in the change list
view of the django admin. For the given instance and field name, the
HTML link tags in the column are parsed for a URL a... |
Returns the value displayed in the column on the web interface for a given instance. | def field_value(self, admin_model, instance, field_name):
"""Returns the value displayed in the column on the web interface for
a given instance.
:param admin_model:
Instance of a :class:`admin.ModelAdmin` object that is responsible
for displaying the change list
... |
Returns the names of the fields/ columns used by the given admin model. | def field_names(self, admin_model):
"""Returns the names of the fields/columns used by the given admin
model.
:param admin_model:
Instance of a :class:`admin.ModelAdmin` object that is responsible
for displaying the change list
:returns:
List of field... |
Opens a nested tunnel first to * user1 * @ * server1 * then to * user2 * @ * server2 * for accessing on * port *. | def githubtunnel(user1, server1, user2, server2, port, verbose, stanford=False):
"""
Opens a nested tunnel, first to *user1*@*server1*, then to *user2*@*server2*, for accessing on *port*.
If *verbose* is true, prints various ssh commands.
If *stanford* is true, shifts ports up by 1.
Attempts to g... |
Highest value of input image. | def imgmax(self):
"""
Highest value of input image.
"""
if not hasattr(self, '_imgmax'):
imgmax = _np.max(self.images[0])
for img in self.images:
imax = _np.max(img)
if imax > imgmax:
imgmax = imax
s... |
Lowest value of input image. | def imgmin(self):
"""
Lowest value of input image.
"""
if not hasattr(self, '_imgmin'):
imgmin = _np.min(self.images[0])
for img in self.images:
imin = _np.min(img)
if imin > imgmin:
imgmin = imin
se... |
spawns a greenlet that does not print exceptions to the screen. if you use this function you MUST use this module s join or joinall otherwise the exception will be lost | def spawn(func, *args, **kwargs):
""" spawns a greenlet that does not print exceptions to the screen.
if you use this function you MUST use this module's join or joinall otherwise the exception will be lost """
return gevent.spawn(wrap_uncaught_greenlet_exceptions(func), *args, **kwargs) |
Returns usage string with no trailing whitespace. | def _usage(prog_name=os.path.basename(sys.argv[0])):
'''Returns usage string with no trailing whitespace.'''
spacer = ' ' * len('usage: ')
usage = prog_name + ' -b LIST [-S SEPARATOR] [file ...]\n' \
+ spacer + prog_name + ' -c LIST [-S SEPERATOR] [file ...]\n' \
+ spacer + prog_name \
... |
Setup argparser to process arguments and generate help | def _parse_args(args):
"""Setup argparser to process arguments and generate help"""
# parser uses custom usage string, with 'usage: ' removed, as it is
# added automatically via argparser.
parser = argparse.ArgumentParser(description="Remove and/or rearrange "
+ "se... |
Processes command line arguments and file i/ o | def main(args=sys.argv[1:]):
'''Processes command line arguments and file i/o'''
if not args:
sys.stderr.write(_usage() + '\n')
sys.exit(4)
else:
parsed = _parse_args(args)
# Set delim based on whether or not regex is desired by user
delim = parsed.delimiter if parsed.regex ... |
Returns axes * x y * for a given image * img * to be used with: func: scisalt. matplotlib. NonUniformImage. | def NonUniformImage_axes(img):
"""
Returns axes *x, y* for a given image *img* to be used with :func:`scisalt.matplotlib.NonUniformImage`.
Returns
-------
x, y : float, float
"""
xmin = 0
xmax = img.shape[1]-1
ymin = 0
ymax = img.shape[0]-1
x = _np.linspace(xmin, xmax, img.s... |
View to be used in the django admin for changing a: class: RankedModel object s rank. See: func: admin_link_move_up and: func: admin_link_move_down for helper functions to incoroprate in your admin models. | def move(request, content_type_id, obj_id, rank):
"""View to be used in the django admin for changing a :class:`RankedModel`
object's rank. See :func:`admin_link_move_up` and
:func:`admin_link_move_down` for helper functions to incoroprate in your
admin models.
Upon completion this view sends the ... |
Opens connection to S3 returning bucket and key | def open_s3(bucket):
"""
Opens connection to S3 returning bucket and key
"""
conn = boto.connect_s3(options.paved.s3.access_id, options.paved.s3.secret)
try:
bucket = conn.get_bucket(bucket)
except boto.exception.S3ResponseError:
bucket = conn.create_bucket(bucket)
return buc... |
Upload a local file to S3. | def upload_s3(file_path, bucket_name, file_key, force=False, acl='private'):
"""Upload a local file to S3.
"""
file_path = path(file_path)
bucket = open_s3(bucket_name)
if file_path.isdir():
# Upload the contents of the dir path.
paths = file_path.listdir()
paths_keys = list... |
Download a remote file from S3. | def download_s3(bucket_name, file_key, file_path, force=False):
"""Download a remote file from S3.
"""
file_path = path(file_path)
bucket = open_s3(bucket_name)
file_dir = file_path.dirname()
file_dir.makedirs()
s3_key = bucket.get_key(file_key)
if file_path.exists():
file_data... |
Creates an ical. ics file for an event using python - card - me. | def create_ical(request, slug):
""" Creates an ical .ics file for an event using python-card-me. """
event = get_object_or_404(Event, slug=slug)
# convert dates to datetimes.
# when we change code to datetimes, we won't have to do this.
start = event.start_date
start = datetime.datetime(start.ye... |
Returns a list view of all comments for a given event. Combines event comments and update comments in one list. | def event_all_comments_list(request, slug):
"""
Returns a list view of all comments for a given event.
Combines event comments and update comments in one list.
"""
event = get_object_or_404(Event, slug=slug)
comments = event.all_comments
page = int(request.GET.get('page', 99999)) # feed emp... |
Returns a list view of updates for a given event. If the event is over it will be in chronological order. If the event is upcoming or still going it will be in reverse chronological order. | def event_update_list(request, slug):
"""
Returns a list view of updates for a given event.
If the event is over, it will be in chronological order.
If the event is upcoming or still going,
it will be in reverse chronological order.
"""
event = get_object_or_404(Event, slug=slug)
updates... |
Displays list of videos for given event. | def video_list(request, slug):
"""
Displays list of videos for given event.
"""
event = get_object_or_404(Event, slug=slug)
return render(request, 'video/video_list.html', {
'event': event,
'video_list': event.eventvideo_set.all()
}) |
Public form to add an event. | def add_event(request):
""" Public form to add an event. """
form = AddEventForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
instance.sites = settings.SITE_ID
instance.submitted_by = request.user
instance.approved = True
instance.slug ... |
Adds a memory to an event. | def add_memory(request, slug):
""" Adds a memory to an event. """
event = get_object_or_404(Event, slug=slug)
form = MemoryForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.event = event
... |
Helper function that actually processes and saves the upload ( s ). Segregated out for readability. | def process_upload(upload_file, instance, form, event, request):
"""
Helper function that actually processes and saves the upload(s).
Segregated out for readability.
"""
caption = form.cleaned_data.get('caption')
upload_name = upload_file.name.lower()
if upload_name.endswith('.jpg') or uploa... |
Find the parent python path that contains the __main__ s file directory | def _get_search_path(main_file_dir, sys_path):
'''
Find the parent python path that contains the __main__'s file directory
:param main_file_dir: __main__'s file directory
:param sys_path: paths list to match directory against (like sys.path)
'''
# List to gather candidate parent paths
paths... |
Try different strategies to found the path containing the __main__ s file. Will try strategies in the following order: 1. Building file s path with PWD env var. 2. Building file s path from absolute file s path. 3. Buidling file s path from real file s path. | def _try_search_paths(main_globals):
'''
Try different strategies to found the path containing the __main__'s file.
Will try strategies, in the following order:
1. Building file's path with PWD env var.
2. Building file's path from absolute file's path.
3. Buidling file's path from r... |
Find parent python path of __main__. From there solve the package containing __main__ import it and set __package__ variable. | def _solve_pkg(main_globals):
'''
Find parent python path of __main__. From there solve the package
containing __main__, import it and set __package__ variable.
:param main_globals: globals dictionary in __main__
'''
# find __main__'s file directory and search path
main_dir, search_path = _... |
Log at debug level: param msg: message to log | def _log_debug(msg):
'''
Log at debug level
:param msg: message to log
'''
if _log_level <= DEBUG:
if _log_level == TRACE:
traceback.print_stack()
_log(msg) |
Enables explicit relative import in sub - modules when ran as __main__: param log_level: module s inner logger level ( equivalent to logging pkg ) | def init(log_level=ERROR):
'''
Enables explicit relative import in sub-modules when ran as __main__
:param log_level: module's inner logger level (equivalent to logging pkg)
'''
global _initialized
if _initialized:
return
else:
_initialized = True
# find caller's frame
... |
Enables explicit relative import in sub - modules when ran as __main__: param log_level: module s inner logger level ( equivalent to logging pkg ) | def _init(frame, log_level=ERROR):
'''
Enables explicit relative import in sub-modules when ran as __main__
:param log_level: module's inner logger level (equivalent to logging pkg)
'''
global _log_level
_log_level = log_level
# now we have access to the module globals
main_globals = fra... |
Use the reduced chi square to unscale: mod: scipy s scaled: func: scipy. optimize. curve_fit. * \ * args * and * \ * \ * kwargs * are passed through to: func: scipy. optimize. curve_fit. The tuple * popt pcov chisq_red * is returned where * popt * is the optimal values for the parameters * pcov * is the estimated covar... | def curve_fit_unscaled(*args, **kwargs):
"""
Use the reduced chi square to unscale :mod:`scipy`'s scaled :func:`scipy.optimize.curve_fit`. *\*args* and *\*\*kwargs* are passed through to :func:`scipy.optimize.curve_fit`. The tuple *popt, pcov, chisq_red* is returned, where *popt* is the optimal values for the p... |
Fits a gaussian to a slice of an image * img * specified by * xslice * x - coordinates and * yslice * y - coordinates. * res_x * and * res_y * specify image resolution in x and y. * avg_e_func * is a function that returns the energy of the image as a function of x. It should have the form: | def fitimageslice(img, res_x, res_y, xslice, yslice, avg_e_func=None, h5file=None, plot=False):
"""
Fits a gaussian to a slice of an image *img* specified by *xslice* x-coordinates and *yslice* y-coordinates. *res_x* and *res_y* specify image resolution in x and y. *avg_e_func* is a function that returns the en... |
: returns: a JSON - representation of the object | def encode(python_object, indent=None, large_object=False):
""":returns: a JSON-representation of the object"""
# sorted keys is easier to read; however, Python-2.7.2 does not have this feature
kwargs = dict(indent=indent)
if can_dumps_sort_keys():
kwargs.update(sort_keys=True)
try:
... |
Inserts Interpreter Library of imports into sketch in a very non - consensual way | def __register_library(self, module_name: str, attr: str, fallback: str = None):
"""Inserts Interpreter Library of imports into sketch in a very non-consensual way"""
# Import the module Named in the string
try:
module = importlib.import_module(module_name)
# If module is n... |
Sets the beam moments directly. | def set_moments(self, sx, sxp, sxxp):
"""
Sets the beam moments directly.
Parameters
----------
sx : float
Beam moment where :math:`\\text{sx}^2 = \\langle x^2 \\rangle`.
sxp : float
Beam moment where :math:`\\text{sxp}^2 = \\langle x'^2 \\rangle`... |
Sets the beam moments indirectly using Courant - Snyder parameters. | def set_Courant_Snyder(self, beta, alpha, emit=None, emit_n=None):
"""
Sets the beam moments indirectly using Courant-Snyder parameters.
Parameters
----------
beta : float
Courant-Snyder parameter :math:`\\beta`.
alpha : float
Courant-Snyder param... |
Courant - Snyder parameter: math: \\ beta. | def beta(self):
"""
Courant-Snyder parameter :math:`\\beta`.
"""
beta = _np.sqrt(self.sx)/self.emit
return beta |
Given a slice object return appropriate values for use in the range function | def normalize_slice(slice_obj, length):
"""
Given a slice object, return appropriate values for use in the range function
:param slice_obj: The slice object or integer provided in the `[]` notation
:param length: For negative indexing we need to know the max length of the object.
"""
if isinsta... |
Helper to add error to messages field. It fills placeholder with extra call parameters or values from message_value map. | def error(self, error_code, value, **kwargs):
"""
Helper to add error to messages field. It fills placeholder with extra call parameters
or values from message_value map.
:param error_code: Error code to use
:rparam error_code: str
:param value: Value checked
:pa... |
File copy that support compress and decompress of zip files | def copy(src, dst):
"""File copy that support compress and decompress of zip files"""
(szip, dzip) = (src.endswith(".zip"), dst.endswith(".zip"))
logging.info("Copy: %s => %s"%(src, dst))
if szip and dzip:#If both zipped, we can simply use copy
shutil.copy2(src, dst)
elif szip:
wit... |
Apply to the catalog the changesets in the metafile list changesets | def apply_changesets(args, changesets, catalog):
"""Apply to the 'catalog' the changesets in the metafile list 'changesets'"""
tmpdir = tempfile.mkdtemp()
tmp_patch = join(tmpdir, "tmp.patch")
tmp_lcat = join(tmpdir, "tmp.lcat")
for node in changesets:
remove(tmp_patch)
copy(node.... |
Validate that an event with this name on this date does not exist. | def clean(self):
"""
Validate that an event with this name on this date does not exist.
"""
cleaned = super(EventForm, self).clean()
if Event.objects.filter(name=cleaned['name'], start_date=cleaned['start_date']).count():
raise forms.ValidationError(u'This event appea... |
When entering the context spawns a greenlet that sleeps for interval seconds between callback executions. When leaving the context stops the greenlet. The yielded object is the GeventLoop object so the loop can be stopped from within the context. | def loop_in_background(interval, callback):
"""
When entering the context, spawns a greenlet that sleeps for `interval` seconds between `callback` executions.
When leaving the context stops the greenlet.
The yielded object is the `GeventLoop` object so the loop can be stopped from within the context.
... |
Main loop - used internally. | def _loop(self):
"""Main loop - used internally."""
while True:
try:
with uncaught_greenlet_exception_context():
self._loop_callback()
except gevent.GreenletExit:
break
if self._stop_event.wait(self._interval):
... |
Starts the loop. Calling a running loop is an error. | def start(self):
"""
Starts the loop. Calling a running loop is an error.
"""
assert not self.has_started(), "called start() on an active GeventLoop"
self._stop_event = Event()
# note that we don't use safe_greenlets.spawn because we take care of it in _loop by ourselves
... |
Stops a running loop and waits for it to end if timeout is set. Calling a non - running loop is an error.: param timeout: time ( in seconds ) to wait for the loop to end after signalling it. None is to block till it ends.: return: True if the loop stopped False if still stopping. | def stop(self, timeout=None):
"""
Stops a running loop and waits for it to end if timeout is set. Calling a non-running loop is an error.
:param timeout: time (in seconds) to wait for the loop to end after signalling it. ``None`` is to block till it
ends.
:return: True if the loo... |
Kills the running loop and waits till it gets killed. | def kill(self):
"""Kills the running loop and waits till it gets killed."""
assert self.has_started(), "called kill() on a non-active GeventLoop"
self._stop_event.set()
self._greenlet.kill()
self._clear() |
Used to plot a set of coordinates. | def NonUniformImage(x, y, z, ax=None, fig=None, cmap=None, alpha=None, scalex=True, scaley=True, add_cbar=True, **kwargs):
"""
Used to plot a set of coordinates.
Parameters
----------
x, y : :class:`numpy.ndarray`
1-D ndarrays of lengths N and M, respectively, specifying pixel centers
... |
Fix common spacing errors caused by LaTeX s habit of using an inter - sentence space after any full stop. | def _sentence_to_interstitial_spacing(self):
"""Fix common spacing errors caused by LaTeX's habit
of using an inter-sentence space after any full stop."""
not_sentence_end_chars = [' ']
abbreviations = ['i.e.', 'e.g.', ' v.',
' w.', ' wh.']
titles = ['Prof.', 'Mr.', ... |
Transform hyphens to various kinds of dashes | def _hyphens_to_dashes(self):
"""Transform hyphens to various kinds of dashes"""
problematic_hyphens = [(r'-([.,!)])', r'---\1'),
(r'(?<=\d)-(?=\d)', '--'),
(r'(?<=\s)-(?=\s)', '---')]
for problem_case in problematic_hyphens:
self._... |
Replace target with replacement | def _str_replacement(self, target, replacement):
"""Replace target with replacement"""
self.data = self.data.replace(target, replacement) |
Regex substitute target with replacement | def _regex_replacement(self, target, replacement):
"""Regex substitute target with replacement"""
match = re.compile(target)
self.data = match.sub(replacement, self.data) |
Call the Sphinx Makefile with the specified targets. | def sphinx_make(*targets):
"""Call the Sphinx Makefile with the specified targets.
`options.paved.docs.path`: the path to the Sphinx folder (where the Makefile resides).
"""
sh('make %s' % ' '.join(targets), cwd=options.paved.docs.path) |
Upload the docs to a remote location via rsync. | def rsync_docs():
"""Upload the docs to a remote location via rsync.
`options.paved.docs.rsync_location`: the target location to rsync files to.
`options.paved.docs.path`: the path to the Sphinx folder (where the Makefile resides).
`options.paved.docs.build_rel`: the path of the documentation
... |
Push Sphinx docs to github_ gh - pages branch. | def ghpages():
'''Push Sphinx docs to github_ gh-pages branch.
1. Create file .nojekyll
2. Push the branch to origin/gh-pages
after committing using ghp-import_
Requirements:
- easy_install ghp-import
Options:
- `options.paved.docs.*` is not used
- `options.sphinx.docroot... |
Open your web browser and display the generated html documentation. | def showhtml():
"""Open your web browser and display the generated html documentation.
"""
import webbrowser
# copy from paver
opts = options
docroot = path(opts.get('docroot', 'docs'))
if not docroot.exists():
raise BuildFailure("Sphinx documentation root (%s) does not exist."
... |
Sets up a figure with a number of rows ( * rows * ) and columns ( * cols * ) * \ * \ * kwargs * passes through to: class: matplotlib. figure. Figure. | def setup_figure(rows=1, cols=1, **kwargs):
"""
Sets up a figure with a number of rows (*rows*) and columns (*cols*), *\*\*kwargs* passes through to :class:`matplotlib.figure.Figure`.
.. versionchanged:: 1.3
Supports *\*\*kwargs* pass-through to :class:`matplotlib.figure.Figure`.
.. vers... |
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):
self._validate()
"""
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)... |
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._game.answer_str
return "{0} The correct answer was {1}. Please start a new ... |
Parse the copy inside value and look for shortcodes in this format:: <p > Here s an attachment</ p > <p > [ attachment 1 ] </ p > Replace the shortcode with a full image video or audio element or download link: param obj: The object against which attachments are saved: param width: The width of images or audio/ video t... | def attachments(value, obj, width = WIDTH):
"""
Parse the copy inside ``value`` and look for shortcodes in this format::
<p>Here's an attachment</p>
<p>[attachment 1]</p>
Replace the shortcode with a full image, video or audio element, or download link
:param obj: The obje... |
Tries to minimize the length of CSS code passed as parameter. Returns string. | def minify(self, css):
"""Tries to minimize the length of CSS code passed as parameter. Returns string."""
css = css.replace("\r\n", "\n") # get rid of Windows line endings, if they exist
for rule in _REPLACERS[self.level]:
css = re.compile(rule[0], re.MULTILINE|re.UNICODE|re.DOTALL).sub(rul... |
Adds a polite colorbar that steals space so: func: matplotlib. pyplot. tight_layout works nicely. | def colorbar(ax, im, fig=None, loc="right", size="5%", pad="3%"):
"""
Adds a polite colorbar that steals space so :func:`matplotlib.pyplot.tight_layout` works nicely.
.. versionadded:: 1.3
Parameters
----------
ax : :class:`matplotlib.axis.Axis`
The axis to plot to.
im : :class:`m... |
Converts a quadrupole: math: B_des into a geometric focusing strength: math: K. | def BDES2K(bdes, quad_length, energy):
"""
Converts a quadrupole :math:`B_des` into a geometric focusing strength :math:`K`.
Parameters
----------
bdes : float
The magnet value of :math:`B_des`.
quad_length : float
The length of the quadrupole in meters.
energy : float
... |
Return an open file - object to the index file | def get_or_create_index(self, index_ratio, index_width):
"""Return an open file-object to the index file"""
if not self.index_path.exists() or not self.filepath.stat().st_mtime == self.index_path.stat().st_mtime:
create_index(self.filepath, self.index_path, index_ratio=index_ratio, index_wid... |
Create the tasks on the server | def create(self, server):
"""Create the tasks on the server"""
for chunk in self.__cut_to_size():
server.post(
'tasks_admin',
chunk.as_payload(),
replacements={
'slug': chunk.challenge.slug}) |
Update existing tasks on the server | def update(self, server):
"""Update existing tasks on the server"""
for chunk in self.__cut_to_size():
server.put(
'tasks_admin',
chunk.as_payload(),
replacements={
'slug': chunk.challenge.slug}) |
Reconcile this collection with the server. | def reconcile(self, server):
"""
Reconcile this collection with the server.
"""
if not self.challenge.exists(server):
raise Exception('Challenge does not exist on server')
existing = MapRouletteTaskCollection.from_server(server, self.challenge)
same = []
... |
Prompts the user for yes or no. | def yn_prompt(msg, default=True):
"""
Prompts the user for yes or no.
"""
ret = custom_prompt(msg, ["y", "n"], "y" if default else "n")
if ret == "y":
return True
return False |
Prompts the user with custom options. | def custom_prompt(msg, options, default):
"""
Prompts the user with custom options.
"""
formatted_options = [
x.upper() if x == default else x.lower() for x in options
]
sure = input("{0} [{1}]: ".format(msg, "/".join(formatted_options)))
if len(sure) == 0:
return default
... |
Reading the configure file and adds non - existing attributes to args | def read(args):
"""Reading the configure file and adds non-existing attributes to 'args'"""
if args.config_file is None or not isfile(args.config_file):
return
logging.info("Reading configure file: %s"%args.config_file)
config = cparser.ConfigParser()
config.read(args.config_file)
if ... |
Writing the configure file with the attributes in args | def write(args):
"""Writing the configure file with the attributes in 'args'"""
logging.info("Writing configure file: %s"%args.config_file)
if args.config_file is None:
return
#Let's add each attribute of 'args' to the configure file
config = cparser.ConfigParser()
config.add_section("... |
Helper function for tests. Spawns a memcached process attached to sock. Returns Popen instance. Terminate with p. terminate (). Note: sock parameter is not checked and command is executed as shell. Use only if you trust that sock parameter. You ve been warned. | def _spawn_memcached(sock):
"""Helper function for tests. Spawns a memcached process attached to sock.
Returns Popen instance. Terminate with p.terminate().
Note: sock parameter is not checked, and command is executed as shell.
Use only if you trust that sock parameter. You've been warned.
"""
p = subprocess.Pope... |
Dump ( return ) a dict representation of the GameObject. This is a Python dict and is NOT serialized. NB: the answer ( a DigitWord object ) and the mode ( a GameMode object ) are converted to python objects of a list and dict respectively. | def dump(self):
"""
Dump (return) a dict representation of the GameObject. This is a Python
dict and is NOT serialized. NB: the answer (a DigitWord object) and the
mode (a GameMode object) are converted to python objects of a list and
dict respectively.
:return: python <... |
Load the representation of a GameObject from a Python <dict > representing the game object. | def load(self, source=None):
"""
Load the representation of a GameObject from a Python <dict> representing
the game object.
:param source: a Python <dict> as detailed above.
:return:
"""
if not source:
raise ValueError("A valid dictionary must be pas... |
Create a new instance of a game. Note a mode MUST be provided and MUST be of type GameMode. | def new(self, mode):
"""
Create a new instance of a game. Note, a mode MUST be provided and MUST be of
type GameMode.
:param mode: <required>
"""
dw = DigitWord(wordtype=mode.digit_type)
dw.random(mode.digits)
self._key = str(uuid.uuid4())
self.... |
The beam emittance: math: \\ langle x x \\ rangle. | def emit_measured(self):
"""
The beam emittance :math:`\\langle x x' \\rangle`.
"""
return _np.sqrt(self.spotsq*self.divsq-self.xxp**2) |
Bumps the Version given a target | def bump(self, target):
"""
Bumps the Version given a target
The target can be either MAJOR, MINOR or PATCH
"""
if target == 'patch':
return Version(self.major, self.minor, self.patch + 1)
if target == 'minor':
return Version(self.major, self.mino... |
Returns a copy of this object | def clone(self):
"""
Returns a copy of this object
"""
t = Tag(self.version.major, self.version.minor, self.version.patch)
if self.revision is not None:
t.revision = self.revision.clone()
return t |
Returns a Tag with a given revision | def with_revision(self, label, number):
"""
Returns a Tag with a given revision
"""
t = self.clone()
t.revision = Revision(label, number)
return t |
Parses a string into a Tag | def parse(s):
"""
Parses a string into a Tag
"""
try:
m = _regex.match(s)
t = Tag(int(m.group('major')),
int(m.group('minor')),
int(m.group('patch')))
return t \
if m.group('label') is None \
... |
Returns a new Tag containing the bumped target and/ or the bumped label | def yield_tag(self, target=None, label=None):
"""
Returns a new Tag containing the bumped target and/or the bumped label
"""
if target is None and label is None:
raise ValueError('`target` and/or `label` must be specified')
if label is None:
return self._y... |
Tiles open figures. | def tile():
"""Tiles open figures."""
figs = plt.get_fignums()
# Keep track of x, y, size for figures
x = 0
y = 0
# maxy = 0
toppad = 21
size = np.array([0, 0])
if ( len(figs) != 0 ):
fig = plt.figure(figs[0])
screen = fig.canvas.window.get_sc... |
Generate a new array with numbers interpolated between the numbers of the input array. Extrapolates elements to the left and right sides to get the exterior border as well. Parameters ---------- | def linspaceborders(array):
"""
Generate a new array with numbers interpolated between the numbers of the input array. Extrapolates elements to the left and right sides to get the exterior border as well.
Parameters
----------
array : :class:`numpy.ndarray`
The original array.
Ret... |
On - axis beam density: math: n_ { b 0 }. | def nb0(self):
"""
On-axis beam density :math:`n_{b,0}`.
"""
return self.N_e / (4*_np.sqrt(3) * _np.pi * self.sig_x * self.sig_y * self.sig_xi) |
Driving force term:: math: r = - k \\ left ( \\ frac { 1 - e^ { - r^2/ 2 { \\ sigma_r } ^2 }} { r } \\ right ) | def k(self):
"""
Driving force term: :math:`r'' = -k \\left( \\frac{1-e^{-r^2/2{\\sigma_r}^2}}{r} \\right)`
"""
try:
return self._k
except AttributeError:
self._k = _np.sqrt(_np.pi/8) * e**2 * self.nb0 * self.sig_y / ( e0 * self.m * c**2)
retur... |
Small - angle driving force term:: math: r = - k_ { small } r. | def k_small(self):
"""
Small-angle driving force term: :math:`r'' = -k_{small} r`.
Note: :math:`k_{small} = \\frac{k}{2{\\sigma_r^2}}`
"""
return self.k * _np.sqrt(2/_np.pi) / self.sig_y |
When a Comment is added updates the Update to set last_updated time | def update_time(sender, **kwargs):
"""
When a Comment is added, updates the Update to set "last_updated" time
"""
comment = kwargs['instance']
if comment.content_type.app_label == "happenings" and comment.content_type.name == "Update":
from .models import Update
item = Update.objects... |
new_game () creates a new game. Docs TBC. | def new_game(self, mode=None):
"""
new_game() creates a new game. Docs TBC.
:return: JSON String containing the game object.
"""
# Create a placeholder Game object
self._g = GameObject()
# Validate game mode
_mode = mode or "normal"
logging.deb... |
load_game () takes a JSON string representing a game object and calls the underlying game object ( _g ) to load the JSON. The underlying object will handle schema validation and transformation. | def load_game(self, jsonstr):
"""
load_game() takes a JSON string representing a game object and calls the underlying
game object (_g) to load the JSON. The underlying object will handle schema validation
and transformation.
:param jsonstr: A valid JSON string representing a Gam... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.