_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q52300 | disable_notebook | train | def disable_notebook():
"""Disable automatic visualization of NumPy arrays in the IPython Notebook."""
try:
from IPython.core.getipython import get_ipython
except ImportError:
raise ImportError('This feature requires IPython 1.0+')
ip = get_ipython()
f = ip.display_formatter.formatte... | python | {
"resource": ""
} |
q52301 | _deserialize | train | def _deserialize(x, elementType, compress, relicReadBinFunc):
"""
Deserializes a bytearray @x, into an @element of the correct type,
using the a relic read_bin function and the specified @compressed flag.
This is the underlying implementation for deserialize G1, G2, and Gt.
"""
# Convert the byt... | python | {
"resource": ""
} |
q52302 | deserializeEc | train | def deserializeEc(x, compress=True):
"""
Deserialize binary string @x into an EC element.
"""
return _deserialize(x, ec1Element, compress, librelic.ec_read_bin_abi) | python | {
"resource": ""
} |
q52303 | formatPoint | train | def formatPoint(point, affine):
"""
Retrieves a string representation of @point
"""
# Affine coordinates: (x,y)
if affine:
fmt = "\tx:{}\n\ty:{}"
coords = [point.x, point.y]
# Projected coordinates: (x,y,z)
else:
fmt = "\tx:{}\n\ty:{}\n\tz:{}"
coords ... | python | {
"resource": ""
} |
q52304 | serializeEc | train | def serializeEc(P, compress=True):
"""
Generates a compact binary version of this point.
"""
return _serialize(P, compress, librelic.ec_size_bin_abi,
librelic.ec_write_bin_abi) | python | {
"resource": ""
} |
q52305 | find_templates | train | def find_templates():
"""
Load python modules from templates directory and get templates list
:return: list of tuples (pairs):
[(compiled regex, lambda regex_match: return message_data)]
"""
templates = []
templates_directory = (inspect.getsourcefile(lambda: 0).rstrip('__init__.py'... | python | {
"resource": ""
} |
q52306 | HtmlRenderer.tag | train | def tag(self, name, attrs=None, selfclosing=None):
"""Helper function to produce an HTML tag."""
if self.disable_tags > 0:
return
if name in self.linkable_tags and attrs and len(attrs) > 0:
for attrib in attrs:
if attrib[0] in self.linkable_attrs:
... | python | {
"resource": ""
} |
q52307 | HtmlRenderer.code_block | train | def code_block(self, node, entering):
'''Output Pygments if required else use default html5 output'''
if self.use_pygments:
self.cr()
info_words = node.info.split() if node.info else []
if len(info_words) > 0 and len(info_words[0]) > 0:
try:
... | python | {
"resource": ""
} |
q52308 | FrontmarkReader._parse | train | def _parse(self, text):
'''
Parse text with frontmatter, return metadata and content.
If frontmatter is not found, returns an empty metadata dictionary and original text content.
'''
# ensure unicode first
text = str(text).strip()
if not text.startswith(DELIMITER... | python | {
"resource": ""
} |
q52309 | FrontmarkReader._parse_metadata | train | def _parse_metadata(self, meta):
"""Return the dict containing document metadata"""
formatted_fields = self.settings['FORMATTED_FIELDS']
output = collections.OrderedDict()
for name, value in meta.items():
name = name.lower()
if name in formatted_fields:
... | python | {
"resource": ""
} |
q52310 | FrontmarkReader._render | train | def _render(self, text):
'''Render CommonMark with ettings taken in account'''
parser = commonmark.Parser()
ast = parser.parse(text)
renderer = HtmlRenderer(self)
html = renderer.render(ast)
return html | python | {
"resource": ""
} |
q52311 | find_divisors | train | def find_divisors(n):
""" Find all the positive divisors of the given integer n.
Args:
n (int): strictly positive integer
Returns:
A generator of all the positive divisors of n
Raises:
TypeError: if n is not an integer
ValueError: if n is negative
"""
if not... | python | {
"resource": ""
} |
q52312 | count_divisors | train | def count_divisors(n):
""" Count the number of divisors of an integer n
Args:
n (int): strictly positive integer
Returns:
The number of distinct divisors of n
Raises:
TypeError: if n is not an integer
ValueError: if n is negative
"""
if not isinstance(n, int... | python | {
"resource": ""
} |
q52313 | binomial_coefficient | train | def binomial_coefficient(n, k):
""" Calculate the binomial coefficient indexed by n and k.
Args:
n (int): positive integer
k (int): positive integer
Returns:
The binomial coefficient indexed by n and k
Raises:
TypeError: If either n or k is not an integer
Valu... | python | {
"resource": ""
} |
q52314 | eulers_totient | train | def eulers_totient(n):
""" Calculate the value of Euler's totient for a given integer
Args:
n (int): strictly positive integer
Returns:
The value of Euler's totient for n
Raises:
TypeError: If either n or k is not an integer
ValueError: If either n or k is negative, o... | python | {
"resource": ""
} |
q52315 | ConspectHandler.get | train | def get(cls):
"""
Get code selected by user.
Returns:
str: Code or None in case that user didn't selected anything yet.
"""
if cls.is_twoconspect:
return cls.subconspect_el.value or None
input_value = cls.input_el.value.strip()
# blank u... | python | {
"resource": ""
} |
q52316 | ConspectDescriptor.bind_switcher | train | def bind_switcher(cls):
"""
Bind the switch checkbox to functions for switching between types of
inputs.
"""
def show_two_conspect():
cls.is_twoconspect = True
# search by class
for el in cls.two_conspect_el:
el.style.display =... | python | {
"resource": ""
} |
q52317 | ConspectDescriptor.show_error | train | def show_error(cls, error=True):
"""
Show `error` around the conspect elements. If the `error` is ``False``,
hide it.
"""
if error:
cls.input_el.style.border = "2px solid red"
cls.conspect_el.style.border = "2px solid red"
cls.subconspect_el.st... | python | {
"resource": ""
} |
q52318 | ConspectDescriptor.init | train | def init(cls):
"""
Bind elements to callbacks.
"""
for el in cls.switcher_els:
el.checked = False
cls.bind_switcher()
cls._draw_conspects()
cls._create_searchable_typeahead() | python | {
"resource": ""
} |
q52319 | ConspectDescriptor.validate | train | def validate(cls):
"""
Make sure, that conspect element is properly selected. If not, show
error.
"""
if cls.get_dict():
cls.show_error(False)
return True
cls.show_error(True)
return False | python | {
"resource": ""
} |
q52320 | ConspectDescriptor.reset | train | def reset(cls):
"""
Reset the conspect elements to initial state.
"""
cls.input_el.value = ""
cls.subconspect_el.html = ""
cls.show_error(False) | python | {
"resource": ""
} |
q52321 | motioncheck | train | def motioncheck(ref_file, end_file, out_path=None, thres=5.0):
"""
Checks motion between structural scans of the same modality.
Ideally obtained at the beginning and end of a scanning session.
Parameters
----------
ref_file: nifti file
Nifti file of first localizer acquired at the beg... | python | {
"resource": ""
} |
q52322 | parse_from_args | train | def parse_from_args(synonyms):
'''
Parse an array of string from argparser
to SynonymSet
'''
syns_str = ''.join(synonyms)
syns_str = syns_str.replace(' ', '')
syn_set = SynonymSet()
# to check if we are parsing inside the parenthesis
inside_set = False
current_syn = ''
... | python | {
"resource": ""
} |
q52323 | parse_from_array | train | def parse_from_array(arr):
"""
Parse 2d array into synonym set
Every array inside arr is considered a set of synonyms
"""
syn_set = SynonymSet()
for synonyms in arr:
_set = set()
for synonym in synonyms:
_set.add(synonym)
syn_set.add_set(_set)
return s... | python | {
"resource": ""
} |
q52324 | Handle.open | train | def open(self):
"""
Open the connection if not already open.
:return: True
"""
try:
if self.conn.get_backend_pid():
return True
except psycopg2.InterfaceError as e:
if str(e) == "connection already closed":
# We alr... | python | {
"resource": ""
} |
q52325 | make_backup_files | train | def make_backup_files(*,
mongodump=MONGODB_DEFAULT_MONGODUMP,
hosts={},
host_defaults={},
dry_run=False,
**kwargs):
"""
Backup all specified databases into a gzipped tarball via mongodump
:param mo... | python | {
"resource": ""
} |
q52326 | _mongodump_exec | train | def _mongodump_exec(mongodump, address, port, user, passwd, db,
out_dir, auth_db, dry_run):
"""
Run mongodump on a database
:param address: server host name or IP address
:param port: server port
:param user: user name
:param passwd: password
:param db: database name
... | python | {
"resource": ""
} |
q52327 | verify_login | train | def verify_login(request):
"""Verifies the assertion and the csrf token in the given request.
Returns the email of the user if everything is valid, otherwise raises
a HTTPBadRequest"""
verifier = request.registry['persona.verifier']
try:
data = verifier.verify(request.POST['assertion'])
... | python | {
"resource": ""
} |
q52328 | login | train | def login(request):
"""View to check the persona assertion and remember the user"""
email = verify_login(request)
request.response.headers.extend(remember(request, email))
return {'redirect': request.POST.get('came_from', '/'), 'success': True} | python | {
"resource": ""
} |
q52329 | logout | train | def logout(request):
"""View to forget the user"""
request.response.headers.extend(forget(request))
return {'redirect': request.POST.get('came_from', '/')} | python | {
"resource": ""
} |
q52330 | forbidden | train | def forbidden(request):
"""A basic 403 view, with a login button"""
template = pkg_resources.resource_string('pyramid_persona', 'templates/forbidden.html').decode()
html = template % {'js': request.persona_js, 'button': request.persona_button}
return Response(html, status='403 Forbidden') | python | {
"resource": ""
} |
q52331 | Surface.load_bmp | train | def load_bmp(path):
"""Load a surface from a file.
Args:
path (str): Path to the BMP file to load.
Returns:
Surface: A surface containing the pixels loaded from the file.
Raises:
SDLError: If the file cannot be loaded.
"""
surface = ... | python | {
"resource": ""
} |
q52332 | Surface.blit | train | def blit(self, src_rect, dst_surf, dst_rect):
"""Performs a fast blit from the source surface to the destination surface.
This assumes that the source and destination rectangles are
the same size. If either src_rect or dst_rect are None, the entire
surface is copied. The final blit rec... | python | {
"resource": ""
} |
q52333 | peek | train | def peek(quantity, min_type=EventType.firstevent, max_type=EventType.lastevent):
"""Return events at the front of the event queue, within the specified minimum and maximum type,
and do not remove them from the queue.
Args:
quantity (int): The maximum number of events to return.
min_type (in... | python | {
"resource": ""
} |
q52334 | get | train | def get(quantity, min_type=EventType.firstevent, max_type=EventType.lastevent):
"""Return events at the front of the event queue, within the specified minimum and maximum type,
and remove them from the queue.
Args:
quantity (int): The maximum number of events to return.
min_type (int): The ... | python | {
"resource": ""
} |
q52335 | poll | train | def poll():
"""Polls for currently pending events.
Returns:
Iterable[Event]: Events from the event queue.
"""
event_ptr = ffi.new('SDL_Event *')
while lib.SDL_PollEvent(event_ptr):
yield Event._from_ptr(event_ptr)
event_ptr = ffi.new('SDL_Event *') | python | {
"resource": ""
} |
q52336 | ColorTable.separator | train | def separator(self):
"""
Generate a separator row using current column widths.
"""
cells = dict([(column, "-" * self.column_widths[column]) for column in self.columns])
return ColorRow(self, **cells) | python | {
"resource": ""
} |
q52337 | timer.get | train | def get(self):
""" Get the current timer value in seconds.
Returns: the elapsed time in seconds since the timer started or until the timer was stopped
"""
now = datetime.now()
if self._start_time:
if self._stop_time:
return (self._stop_time - self._st... | python | {
"resource": ""
} |
q52338 | make_trello_card | train | def make_trello_card(*args, **kwargs):
"""Generate a new Trello card"""
# Generate our card board and list
# DEV: board is never used...
# TODO: This is very backwards with needing a board to get a client...
# Might move to another lib
# https://github.com/sarumont/py-trello/blob/0.4.3/trello/... | python | {
"resource": ""
} |
q52339 | send_slack_message | train | def send_slack_message(channel, text):
"""Send a message to Slack"""
http = httplib2.Http()
return http.request(SLACK_MESSAGE_URL, 'POST', body=json.dumps({
'channel': channel,
'text': text,
})) | python | {
"resource": ""
} |
q52340 | bootstrap_stat | train | def bootstrap_stat(arr, stat=np.mean, n_iters=1000, alpha=0.05):
"""
Produce a boot-strap distribution of the mean of an array on axis 0
Parameters
---------
arr : ndarray
The array with data to be bootstrapped
stat : callable
The statistical function to call. will be called as ... | python | {
"resource": ""
} |
q52341 | separate_signals | train | def separate_signals(data, w_idx=[1, 2, 3]):
"""
Separate the water and non-water data from each other
Parameters
----------
data : nd array
FID signal with shape (transients, echos, coils, time-points)
w_idx : list (optional)
Indices into the 'transients' (0th) dimension of the data for... | python | {
"resource": ""
} |
q52342 | get_spectra | train | def get_spectra(data, filt_method=dict(lb=0.1, filt_order=256),
spect_method=dict(NFFT=1024, n_overlap=1023, BW=2),
phase_zero=None, line_broadening=None, zerofill=None):
"""
Derive the spectra from MRS data
Parameters
----------
data : nitime TimeSeries class instan... | python | {
"resource": ""
} |
q52343 | subtract_water | train | def subtract_water(w_sig, w_supp_sig):
"""
Subtract the residual water signal from the
Normalize the water-suppressed signal by the signal that is not
water-suppressed, to get rid of the residual water peak.
Parameters
----------
w_sig : array with shape (n_reps, n_echos, n_points)
... | python | {
"resource": ""
} |
q52344 | _two_func_initializer | train | def _two_func_initializer(freqs, signal):
"""
This is a helper function for heuristic estimation of the initial parameters
used in fitting dual peak functions
_do_two_lorentzian_fit
_do_two_gaussian_fit
"""
# Use the signal for a rough estimate of the parameters for initialization:
r_signal = n... | python | {
"resource": ""
} |
q52345 | _do_two_gaussian_fit | train | def _do_two_gaussian_fit(freqs, signal, bounds=None):
"""
Helper function for the two gaussian fit
"""
initial = _two_func_initializer(freqs, signal)
# Edit out the ones we want in the order we want them:
initial = (initial[0], initial[1],
initial[6], initial[7],
initial[2... | python | {
"resource": ""
} |
q52346 | fit_two_gaussian | train | def fit_two_gaussian(spectra, f_ppm, lb=3.6, ub=3.9):
"""
Fit a gaussian function to the difference spectra
This is useful for estimation of the Glx peak, which tends to have two
peaks.
Parameters
----------
spectra : array of shape (n_transients, n_points)
Typically the difference of the ... | python | {
"resource": ""
} |
q52347 | _do_scale_fit | train | def _do_scale_fit(freqs, signal, model, w=None):
"""
Perform a round of fitting to deal with over or under-estimation.
Scales curve on y-axis but preserves shape.
Parameters
----------
freqs : array
signal : array
The signal that the model is being fit to
model : array
The model bei... | python | {
"resource": ""
} |
q52348 | scalemodel | train | def scalemodel(model, scalefac):
"""
Given a scale factor, multiply by model to get scaled model
Parameters
----------
model : array
original model
scalefac : array of model.shape[0]
array of scalefactors
Returns
-------
scaledmodel : array
model scaled by scale factor
... | python | {
"resource": ""
} |
q52349 | integrate | train | def integrate(func, x, args=(), offset=0, drift=0):
"""
Integrate a function over the domain x
Parameters
----------
func : callable
A function from the domain x to floats. The first input to this function
has to be x, an array with values to evaluate for, running in monotonic
order... | python | {
"resource": ""
} |
q52350 | _get_date | train | def _get_date(day=None, month=None, year=None):
"""Returns a datetime object with optional params or today."""
now = datetime.date.today()
if day is None:
return now
try:
return datetime.date(
day=int(day),
month=int(month or now.month),
year=int(yea... | python | {
"resource": ""
} |
q52351 | main | train | def main():
"""Command line entry point."""
def help_exit():
raise SystemExit("usage: ddate [day] [month] [year]")
if "--help" in sys.argv or "-h" in sys.argv:
help_exit()
if len(sys.argv) == 2: # allow for 23-2-2014 style, be lazy/sloppy with it
for split_char in ".-/`,:;": ... | python | {
"resource": ""
} |
q52352 | doc_reader | train | def doc_reader(infile):
"""Parse docx and odf files."""
if infile.endswith('.docx'):
docid = 'word/document.xml'
else:
docid = 'content.xml'
try:
zfile = zipfile.ZipFile(infile)
except:
print('Sorry, can\'t open {}.'.format(infile))
return
body = ET.fromst... | python | {
"resource": ""
} |
q52353 | AgencyContractor._on_grant | train | def _on_grant(self, grant):
'''
Called upon receiving the grant. Than calls granted and sets
up reporter if necessary.
'''
self.set_timeout(grant.expiration_time, ContractState.expired,
self._run_and_terminate, self.contractor.cancelled,
... | python | {
"resource": ""
} |
q52354 | start_component | train | async def start_component(workload: CoroutineFunction[T], *args: Any, **kwargs: Any) -> Component[T]:
"""\
Starts the passed `workload` with additional `commands` and `events` pipes.
The workload will be executed as a task.
A simple example. Note that here, the component is exclusively reacting to comm... | python | {
"resource": ""
} |
q52355 | start_component_in_thread | train | async def start_component_in_thread(executor, workload: CoroutineFunction[T], *args: Any, loop=None, **kwargs: Any) -> Component[T]:
"""\
Starts the passed `workload` with additional `commands` and `events` pipes.
The workload will be executed on an event loop in a new thread; the thread is provided by `exe... | python | {
"resource": ""
} |
q52356 | Component.result | train | async def result(self) -> T:
"""\
Wait for the task's termination; either the result is returned or a raised exception is reraised.
If an event is sent before the task terminates, an `EventException` is raised with the event as argument.
"""
try:
event = await self.re... | python | {
"resource": ""
} |
q52357 | Component.request | train | async def request(self, value: Any) -> Any:
"""\
Sends a command to and receives the reply from the task.
"""
await self.send(value)
return await self.recv() | python | {
"resource": ""
} |
q52358 | Component.recv_event | train | async def recv_event(self) -> Any:
"""\
Receives an event from the task.
If the task terminates before another event, an exception is raised.
A normal return is wrapped in a `Success` exception,
other exceptions result in a `Failure` with the original exception as the cause.
... | python | {
"resource": ""
} |
q52359 | StaffMemberAdmin.get_formset | train | def get_formset(self, request, obj=None, **kwargs):
"""
Return a form, if the obj has a staffmember object, otherwise
return an empty form
"""
if obj is not None and self.model.objects.filter(user=obj).count():
return super(StaffMemberAdmin, self).get_formset(
... | python | {
"resource": ""
} |
q52360 | arg_bool | train | def arg_bool(name, default=False):
""" Fetch a query argument, as a boolean. """
v = request.args.get(name, '')
if not len(v):
return default
return v in BOOL_TRUISH | python | {
"resource": ""
} |
q52361 | arg_int | train | def arg_int(name, default=None):
""" Fetch a query argument, as an integer. """
try:
v = request.args.get(name)
return int(v)
except (ValueError, TypeError):
return default | python | {
"resource": ""
} |
q52362 | with_output | train | def with_output(verbosity=1):
"""
Decorator that configures output verbosity.
"""
def make_wrapper(func):
@wraps(func)
def wrapper(*args, **kwargs):
configure_output(verbosity=verbosity)
return func(*args, **kwargs)
return wrapper
return make_wrapper | python | {
"resource": ""
} |
q52363 | _puts | train | def _puts(message, level, **kwargs):
"""
Generate fabric-style output if and only if status output
has been selected.
"""
if not output.get(level):
return
print "[{hostname}] {message}".format(hostname=env.host_string,
message=message.format(**kw... | python | {
"resource": ""
} |
q52364 | configure_output | train | def configure_output(verbosity=0, output_levels=None, quiet=False):
"""
Configure verbosity level through Fabric's output managers.
Provides a default mapping from verbosity levels to output types.
:param verbosity: an integral verbosity level
:param output_levels: an optional mapping from Fabric ... | python | {
"resource": ""
} |
q52365 | Route.copy | train | def copy(self, **params):
'''Creates the new instance of the Route substituting the requested
parameters.'''
new_params = dict()
for name in ['owner', 'priority', 'key', 'final']:
new_params[name] = params.get(name, getattr(self, name))
return Route(**new_params) | python | {
"resource": ""
} |
q52366 | objwalk | train | def objwalk(obj, path=(), memo=None):
"""
Walks an arbitrary python pbject.
:param mixed obj: Any python object
:param tuple path: A tuple of the set attributes representing the path to the value
:param set memo: The list of attributes traversed thus far
:rtype <tuple<tuple>, <mixed>>: The pat... | python | {
"resource": ""
} |
q52367 | setattr_at_path | train | def setattr_at_path( obj, path, val ):
"""
Traverses a set of nested attributes to the value on an object
:param mixed obj: The object to set the attribute on
:param tuple path: The path to the attribute on the object
:param mixed val: The value at the attribute
:rtype None:
"""
target... | python | {
"resource": ""
} |
q52368 | truncate_attr_at_path | train | def truncate_attr_at_path( obj, path ):
"""
Traverses a set of nested attributes and truncates the value on an object
:param mixed obj: The object to set the attribute on
:param tuple path: The path to the attribute on the object
:rtype None:
"""
target = obj
last_attr = path[-1]
m... | python | {
"resource": ""
} |
q52369 | pickle_with_weak_refs | train | def pickle_with_weak_refs( o ):
"""
Pickles an object containing weak references.
:param mixed o: Any object
:rtype str: The pickled object
"""
if isinstance(o, types.GeneratorType):
o = [i for i in o]
walk = dict([ (path,val) for path, val in objwalk(o)])
for path, val in walk... | python | {
"resource": ""
} |
q52370 | user_input | train | def user_input(
field, default='', choices=None, password=False,
empty_ok=False, accept=False):
"""Prompt user for input until a value is retrieved or default
is accepted. Return the input.
Arguments:
*field* - Description of the input being prompted for.
*default* - Default value... | python | {
"resource": ""
} |
q52371 | value | train | def value(value_info, label=None, desc=None):
"""
Annotate the value information of the action being defined.
@param value_info: the value parameter information.
@type value_info: value.IValueInfo
@param label: the parameter label or None.
@type label: str or unicode or None
@param desc: the... | python | {
"resource": ""
} |
q52372 | param | train | def param(name, value_info, is_required=True, label=None, desc=None):
"""
Annotate a parameter of the action being defined.
@param name: name of the parameter defined.
@type name: unicode or str
@param value_info: the parameter value information.
@type value_info: value.IValueInfo
@param is_... | python | {
"resource": ""
} |
q52373 | Action._prepend_name | train | def _prepend_name(self, prefix, dict_):
'''changes the keys of the dictionary prepending them with "name."'''
return dict(['.'.join([prefix, name]), msg]
for name, msg in dict_.iteritems()) | python | {
"resource": ""
} |
q52374 | TimeUnit.duration | train | def duration(cls, seconds, first=True):
"""
Constructs a human readable string to indicate the time duration for the given seconds
:param int seconds:
:param bool first: Just return the first unit instead of all
:rtype: str
"""
num_units = []
for unit in... | python | {
"resource": ""
} |
q52375 | celery | train | def celery(function, *args, **kwargs):
'''
Calls ``function`` asynchronously by creating a pickling it and
calling it in a task.
'''
from .tasks import dill_callable
dilled_function = dill.dumps(function)
dill_callable.delay(dilled_function, *args, **kwargs) | python | {
"resource": ""
} |
q52376 | WebCache.getDatabaseFileSize | train | def getDatabaseFileSize(self):
""" Return the file size of the database as a pretty string. """
if DISABLE_PERSISTENT_CACHING:
return "?"
size = os.path.getsize(self.__db_filepath)
if size > 1000000000:
size = "%0.3fGB" % (size / 1000000000)
elif size > 1000000:
size = "%0.2fMB" % ... | python | {
"resource": ""
} |
q52377 | WebCache.purge | train | def purge(self):
""" Purge cache by removing obsolete items. """
purged_count = 0
if self.__expiration is not None:
with self.__connection:
if self.__caching_strategy is CachingStrategy.FIFO:
# dump least recently added rows
for post in (False, True):
purged_cou... | python | {
"resource": ""
} |
q52378 | ThreadedWebCache.waitResult | train | def waitResult(self):
""" Wait for the execution of the last enqueued job to be done, and return the result or raise an exception. """
self.thread.execute_queue.join()
try:
e = self.thread.exception_queue[threading.get_ident()].get_nowait()
except queue.Empty:
return self.thread.result_queue... | python | {
"resource": ""
} |
q52379 | ThreadedWebCache.callToThread | train | def callToThread(method):
""" Wrap call to method to send it to WebCacheThread. """
def func_wrapped(self, *args, **kwargs):
self.thread.execute_queue.put_nowait((threading.get_ident(), method, args, kwargs))
return self.waitResult()
return func_wrapped | python | {
"resource": ""
} |
q52380 | WebCacheThread.run | train | def run(self):
""" Thread loop. """
# construct WebCache object locally
thread_id, args, kwargs = self.execute_queue.get_nowait()
try:
cache_obj = WebCache(*args, **kwargs)
except Exception as e:
self.exception_queue[thread_id].put_nowait(e)
self.loop = False
self.execute_queue... | python | {
"resource": ""
} |
q52381 | SyntheticClassController._updateConstructorAndMembers | train | def _updateConstructorAndMembers(self):
"""We overwrite constructor and accessors every time because the constructor might have to consume all
members even if their decorator is below the "synthesizeConstructor" decorator and it also might need to update
the getters and setters because the naming convention has... | python | {
"resource": ""
} |
q52382 | which | train | def which(component, path_str):
'''helper method having same behaviour as "which" os command.'''
def is_exe(fpath):
return os.path.exists(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(component)
if fpath:
if is_exe(component):
return component
else:
... | python | {
"resource": ""
} |
q52383 | converter | train | def converter(type_name):
"""Get a given converter by name, or raise an exception."""
converter = TYPES.get(type_name)
if converter is None:
raise ConverterError('Unknown converter: %r' % type_name)
return converter() | python | {
"resource": ""
} |
q52384 | cast | train | def cast(type_name, value, **opts):
"""Convert a given string to the type indicated by ``type_name``.
If ``None`` is passed in, it will always be returned.
Optional arguments can include ``true_values`` and ``false_values`` to
describe boolean types, and ``format`` for dates.
"""
type_name, opt... | python | {
"resource": ""
} |
q52385 | stringify | train | def stringify(type_name, value, **opts):
"""Generate a string representation of the data in ``value``.
Based on the converter specified by ``type_name``. This is
guaranteed to yield a form which can easily be parsed by ``cast()``.
"""
type_name, opts = _field_options(type_name, opts)
return con... | python | {
"resource": ""
} |
q52386 | guesser | train | def guesser(types=GUESS_TYPES, strict=False):
"""Create a type guesser for multiple values."""
return TypeGuesser(types=types, strict=strict) | python | {
"resource": ""
} |
q52387 | mk_class_name | train | def mk_class_name(*parts):
"""Create a valid class name from a list of strings."""
cap = lambda s: s and (s[0].capitalize() + s[1:])
return "".join(["".join([cap(i)
for i in re.split("[\ \-\_\.]", str(p))])
for p in parts]) | python | {
"resource": ""
} |
q52388 | encode_simple | train | def encode_simple(d):
"""Encode strings in basic python objects."""
if isinstance(d, unicode):
return d.encode()
if isinstance(d, list):
return list(map(encode_simple, d))
if isinstance(d, dict):
return dict([(encode_simple(k), encode_simple(v)) for k, v in d.items()])
return... | python | {
"resource": ""
} |
q52389 | parse_radl | train | def parse_radl(data):
"""
Parse a RADL document in JSON.
Args.:
- data(str or list): document to parse.
Return(RADL): RADL object.
"""
if not isinstance(data, list):
if os.path.isfile(data):
f = open(data)
data = "".join(f.readlines())
f.close()
... | python | {
"resource": ""
} |
q52390 | dump_radl | train | def dump_radl(radl, enter="\n", indent=" "):
"""Dump a RADL document."""
indent = len(indent) if enter else None
sort_keys = indent is not None
separators = (",", ":" if indent is None else ": ")
return json.dumps(radlToSimple(radl), indent=indent, sort_keys=sort_keys, separators=separators) | python | {
"resource": ""
} |
q52391 | radlToSimple | train | def radlToSimple(radl_data):
"""
Return a list of maps whose values are only other maps or lists.
"""
aspects = (radl_data.ansible_hosts + radl_data.networks + radl_data.systems +
radl_data.configures + radl_data.deploys)
if radl_data.contextualize.items is not None:
aspects.... | python | {
"resource": ""
} |
q52392 | unique | train | def unique(series: pd.Series) -> pd.Series:
"""Test that the data items do not repeat."""
return ~series.duplicated(keep=False) | python | {
"resource": ""
} |
q52393 | primitives | train | def primitives():
"""
Perform primitive operations for profiling
"""
z = randomZ(orderG1())
# G1 operations
P,Q = randomG1(),randomG1()
R = generatorG1()
g1Add = P + Q
g1ScalarMultiply = z*P
g1GeneratorMultiply = z*R
g1Hash = hashG1(hash_in)
# G2 operations
P,Q = ra... | python | {
"resource": ""
} |
q52394 | protoFast | train | def protoFast():
"""
Runs the protocol but omits proof generation and verification.
"""
r, x = blind(m)
y,kw,tTilde = eval(w,t,x,msk,s)
z = deblind(r, y) | python | {
"resource": ""
} |
q52395 | get_access_flags_string | train | def get_access_flags_string(value):
"""
Transform an access flags to the corresponding string
:param value: the value of the access flags
:type value: int
:rtype: string
"""
buff = ""
for i in ACCESS_FLAGS:
if (i[0] & value) == i[0]:
buff += i[1] + " "
if... | python | {
"resource": ""
} |
q52396 | ProtoIdItem.get_shorty_idx_value | train | def get_shorty_idx_value(self):
"""
Return the string associated to the shorty_idx
:rtype: string
"""
if self.shorty_idx_value == None:
self.shorty_idx_value = self.CM.get_string(self.shorty_idx)
return self.shorty_idx_value | python | {
"resource": ""
} |
q52397 | ProtoIdItem.get_return_type_idx_value | train | def get_return_type_idx_value(self):
"""
Return the string associated to the return_type_idx
:rtype: string
"""
if self.return_type_idx_value == None:
self.return_type_idx_value = self.CM.get_type(self.return_type_idx)
return self.return_type_idx_val... | python | {
"resource": ""
} |
q52398 | ProtoIdItem.get_parameters_off_value | train | def get_parameters_off_value(self):
"""
Return the string associated to the parameters_off
:rtype: string
"""
if self.parameters_off_value == None:
params = self.CM.get_type_list(self.parameters_off)
self.parameters_off_value = '({})'.format(' '.j... | python | {
"resource": ""
} |
q52399 | FieldIdItem.get_type | train | def get_type(self):
"""
Return the type of the field
:rtype: string
"""
if self.type_idx_value == None:
self.type_idx_value = self.CM.get_type(self.type_idx)
return self.type_idx_value | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.