_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q53000 | Renderer.draw_line | train | def draw_line(self, x1, y1, x2, y2):
"""Draw a line on the current rendering target.
Args:
x1 (int): The x coordinate of the start point.
y1 (int): The y coordinate of the start point.
x2 (int): The x coordinate of the end point.
y2 (int): The y coordinat... | python | {
"resource": ""
} |
q53001 | Renderer.draw_lines | train | def draw_lines(self, *points):
"""Draw a series of connected lines on the current rendering target.
Args:
*points (Point): The points along the lines.
Raises:
SDLError: If an error is encountered.
"""
point_array = ffi.new('SDL_Point[]', len(points))
... | python | {
"resource": ""
} |
q53002 | Renderer.draw_point | train | def draw_point(self, x, y):
"""Draw a point on the current rendering target.
Args:
x (int): The x coordinate of the point.
y (int): The y coordinate of the point.
Raises:
SDLError: If an error is encountered.
"""
check_int_err(lib.SDL_RenderD... | python | {
"resource": ""
} |
q53003 | Renderer.draw_points | train | def draw_points(self, *points):
"""Draw multiple points on the current rendering target.
Args:
*points (Point): The points to draw.
Raises:
SDLError: If an error is encountered.
"""
point_array = ffi.new('SDL_Point[]', len(points))
for i, p in en... | python | {
"resource": ""
} |
q53004 | Renderer.draw_rect | train | def draw_rect(self, rect):
"""Draw a rectangle on the current rendering target.
Args:
rect (Rect): The destination rectangle, or None to outline the entire rendering target.
Raises:
SDLError: If an error is encountered.
"""
check_int_err(lib.SDL_RenderDr... | python | {
"resource": ""
} |
q53005 | Renderer.draw_rects | train | def draw_rects(self, *rects):
"""Draw some number of rectangles on the current rendering target.
Args:
*rects (Rect): The destination rectangles.
Raises:
SDLError: If an error is encountered.
"""
rect_array = ffi.new('SDL_Rect[]', len(rects))
for... | python | {
"resource": ""
} |
q53006 | Renderer.fill_rect | train | def fill_rect(self, rect):
"""Fill a rectangle on the current rendering target with the drawing color.
Args:
rect (Rect): The destination rectangle, or None to fill the entire rendering target.
Raises:
SDLError: If an error is encountered.
"""
check_int_... | python | {
"resource": ""
} |
q53007 | Renderer.fill_rects | train | def fill_rects(self, *rects):
"""Fill some number of rectangles on the current rendering target with the drawing color.
Args:
*rects (Rect): The destination rectangles.
Raises:
SDLError: If an error is encountered.
"""
rect_array = ffi.new('SDL_Rect[]', ... | python | {
"resource": ""
} |
q53008 | Renderer.copy | train | def copy(self, texture, source_rect=None, dest_rect=None, rotation=0, center=None, flip=lib.SDL_FLIP_NONE):
"""Copy a portion of the source texture to the current rendering target, rotating it by angle around the given center.
Args:
texture (Texture): The source texture.
source_... | python | {
"resource": ""
} |
q53009 | Texture.from_surface | train | def from_surface(renderer, surface):
"""Create a texture from an existing surface.
Args:
surface (Surface): The surface containing pixel data used to fill the texture.
Returns:
Texture: A texture containing the pixels from surface.
Raises:
SDLError:... | python | {
"resource": ""
} |
q53010 | main | train | def main(argv=None):
"""Main entry point for the cdstar CLI."""
args = docopt(__doc__, version=pycdstar.__version__, argv=argv, options_first=True)
subargs = [args['<command>']] + args['<args>']
if args['<command>'] in ['help', None]:
cmd = None
if len(subargs) > 1:
cmd = CO... | python | {
"resource": ""
} |
q53011 | start_agent | train | def start_agent(agent, recp, desc, allocation_id=None, *args, **kwargs):
'''
Tells remote host agent to start agent identified by desc.
The result value of the fiber is IRecipient.
'''
f = fiber.Fiber()
f.add_callback(agent.initiate_protocol, IRecipient(recp), desc,
allocation... | python | {
"resource": ""
} |
q53012 | BaseInvalidValueHandler.handle_invalid_value | train | def handle_invalid_value(self, message, exc_info, context):
# type: (Text, bool, dict) -> Any
"""
Handles an invalid value.
:param message:
Error message.
:param exc_info:
Whether to include output from :py:func:``sys.exc_info``.
:param context:... | python | {
"resource": ""
} |
q53013 | BaseInvalidValueHandler.handle_exception | train | def handle_exception(self, message, exc):
# type: (Text, Exception) -> Any
"""
Handles an uncaught exception.
"""
return self.handle_invalid_value(
message = message,
exc_info = True,
context = getattr(exc, 'context', {}),
) | python | {
"resource": ""
} |
q53014 | deep_get | train | def deep_get(d, *keys, default=None):
""" Recursive safe search in a dictionary of dictionaries.
Args:
d: the dictionary to work with
*keys: the list of keys to work with
default: the default value to return if the recursive search did not succeed
Returns:
The value wich wa... | python | {
"resource": ""
} |
q53015 | ADComputer.computer | train | def computer(self, base_dn, samaccountname, attributes=()):
"""Produces a single, populated ADComputer object through the object factory.
Does not populate attributes for the caller instance.
:param str base_dn: The base DN to search within
:param str samaccountname: The computer's sAMA... | python | {
"resource": ""
} |
q53016 | ADComputer.computers | train | def computers(self, base_dn, samaccountnames=(), attributes=()):
"""Gathers a list of ADComputer objects
:param str base_dn: The base DN to search within
:param list samaccountnames: A list of computer names for which objects will be
created, defaults to all computers if unspecified... | python | {
"resource": ""
} |
q53017 | source_get | train | def source_get(method_name):
"""
Creates a getter that will drop the current value,
and call the source's method with specified name
using the context's key as first argument.
@param method_name: the name of a method belonging to the source.
@type method_name: str
"""
def source_get(_va... | python | {
"resource": ""
} |
q53018 | source_attr | train | def source_attr(attr_name):
"""
Creates a getter that will drop the current value
and retrieve the source's attribute with specified name.
@param attr_name: the name of an attribute belonging to the source.
@type attr_name: str
"""
def source_attr(_value, context, **_params):
value ... | python | {
"resource": ""
} |
q53019 | model_get | train | def model_get(method_name):
"""
Creates a getter that will drop the current value,
and call the model's method with specified name
using the context's key as first argument.
@param method_name: the name of a method belonging to the model.
@type method_name: str
"""
def model_get(_value,... | python | {
"resource": ""
} |
q53020 | model_attr | train | def model_attr(attr_name):
"""
Creates a getter that will drop the current value
and retrieve the model's attribute with specified name.
@param attr_name: the name of an attribute belonging to the model.
@type attr_name: str
"""
def model_attr(_value, context, **_params):
value = ge... | python | {
"resource": ""
} |
q53021 | model_getattr | train | def model_getattr():
"""
Creates a getter that will drop the current value
and retrieve the model's attribute with the context key as name.
"""
def model_getattr(_value, context, **_params):
value = getattr(context["model"], context["key"])
return _attr(value)
return model_geta... | python | {
"resource": ""
} |
q53022 | action_get | train | def action_get(method_name):
"""
Creates a getter that will drop the current value,
and call the action's method with specified name
using the context's key as first argument.
@param method_name: the name of a method belonging to the action.
@type method_name: str
"""
def action_get(_va... | python | {
"resource": ""
} |
q53023 | action_attr | train | def action_attr(attr_name):
"""
Creates a getter that will drop the current value
and retrieve the action's attribute with specified name.
@param attr_name: the name of an attribute belonging to the action.
@type attr_name: str
"""
def action_attr(_value, context, **_params):
value ... | python | {
"resource": ""
} |
q53024 | action_getattr | train | def action_getattr():
"""
Creates a getter that will drop the current value
and retrieve the action's attribute with the context key as name.
"""
def action_getattr(_value, context, **_params):
value = getattr(context["action"], context["key"])
return _attr(value)
return action... | python | {
"resource": ""
} |
q53025 | view_get | train | def view_get(method_name):
"""
Creates a getter that will drop the current value,
and call the view's method with specified name
using the context's key as first argument.
@param method_name: the name of a method belonging to the view.
@type method_name: str
"""
def view_get(_value, con... | python | {
"resource": ""
} |
q53026 | view_attr | train | def view_attr(attr_name):
"""
Creates a getter that will drop the current value
and retrieve the view's attribute with specified name.
@param attr_name: the name of an attribute belonging to the view.
@type attr_name: str
"""
def view_attr(_value, context, **_params):
value = getatt... | python | {
"resource": ""
} |
q53027 | value_get | train | def value_get(method_name):
"""
Creates a getter that will call value's method with specified name
using the context's key as first argument.
@param method_name: the name of a method belonging to the value.
@type method_name: str
"""
def value_get(value, context, **_params):
method ... | python | {
"resource": ""
} |
q53028 | value_attr | train | def value_attr(attr_name):
"""
Creates a getter that will retrieve value's attribute
with specified name.
@param attr_name: the name of an attribute belonging to the value.
@type attr_name: str
"""
def value_attr(value, context, **_params):
value = getattr(value, attr_name)
... | python | {
"resource": ""
} |
q53029 | value_getattr | train | def value_getattr():
"""
Creates a getter that will retrieve the value's attribute
with the context key as name.
"""
def value_getattr(value, context, **_params):
value = getattr(value, context["key"])
return _attr(value)
return source_getattr | python | {
"resource": ""
} |
q53030 | ProgressBar.show | train | def show(self, progress, msg=None):
"""
Show the progress bar and set it to `progress` tuple or value.
Args:
progress (tuple / int / float): Tuple ``(done / len(all))`` or
the direct percentage value as int / float.
msg (str, default None): Alternative ba... | python | {
"resource": ""
} |
q53031 | ProgressBar.reset | train | def reset(self):
"""
Reset the progressbar to 0, hide it and set original text message at
background.
"""
self.hide()
self.tag.class_name = "progress-bar progress-bar-striped active"
self.tag.aria_valuemin = 0
self.tag.style.width = "{}%".format(0)
... | python | {
"resource": ""
} |
q53032 | check_response | train | async def check_response(response, valid_response_codes):
"""Check the response for correctness."""
if response.status == 204:
return True
if response.status in valid_response_codes:
_js = await response.json()
return _js
else:
raise PvApiResponseStatusError(response.stat... | python | {
"resource": ""
} |
q53033 | TopoSet.update | train | def update(self, iterable):
"""Update with an ordered iterable of items.
Args:
iterable: An ordered iterable of items. The relative
order of the items in this iterable will be respected
in the TopoSet (in the absence of cycles).
"""
for pair in ... | python | {
"resource": ""
} |
q53034 | ADObject.to_dict | train | def to_dict(self):
"""Prepare a minimal dictionary with keys mapping to attributes for
the current instance.
"""
o_copy = copy.copy(self)
# Remove some stuff that is not likely related to AD attributes
for attribute in dir(self):
if attribute == 'logger' or a... | python | {
"resource": ""
} |
q53035 | ADObject.samaccountname | train | def samaccountname(self, base_dn, distinguished_name):
"""Retrieve the sAMAccountName for a specific DistinguishedName
:param str base_dn: The base DN to search within
:param list distinguished_name: The base DN to search within
:param list attributes: Object attributes to populate, def... | python | {
"resource": ""
} |
q53036 | ADObject.samaccountnames | train | def samaccountnames(self, base_dn, distinguished_names):
"""Retrieve the sAMAccountNames for the specified DNs
:param str base_dn: The base DN to search within
:param list distinguished_name: A list of distinguished names for which to
retrieve sAMAccountNames
:return: Key/v... | python | {
"resource": ""
} |
q53037 | ADObject._object_factory | train | def _object_factory(self, search_result):
"""Given a single search result, create and return an object
:param tuple search_result: a single search result returned by an LDAP query,
position 0 is the DN and position 1 is a dictionary of key/value pairs
:return: A single AD object in... | python | {
"resource": ""
} |
q53038 | handle_message | train | def handle_message(received_message, control_plane_sockets, data_plane_sockets):
"""
Handle a LISP message. The default handle method determines the type
of message and delegates it to the more specific method
"""
logger.debug(u"Handling message #{0} ({1}) from {2}".format(received_message.message_n... | python | {
"resource": ""
} |
q53039 | Agency.on_master_missing | train | def on_master_missing(self):
'''
Tries to spawn a master agency if the slave agency failed to connect
for several times. To avoid several slave agencies spawning the master
agency a file lock is used
'''
self.info("We could not contact the master agency, starting a new on... | python | {
"resource": ""
} |
q53040 | merge | train | def merge(root, head, update, head_source=None):
"""
This function instantiate a ``Merger`` object using a configuration in
according to the ``source`` value of head and update params.
Then it run the merger on the three files provided in input.
Params
root(dict): the last common parent jso... | python | {
"resource": ""
} |
q53041 | get_configuration | train | def get_configuration(head, update, head_source=None):
"""
This function return the right configuration for the inspire_merge
function in according to the given sources. Both parameters can not be None.
Params:
head(dict): the HEAD record
update(dict): the UPDATE record
head_sou... | python | {
"resource": ""
} |
q53042 | OutputPicker.set | train | def set(cls, values):
"""
Set the elements from the data obtained from REST API.
Args:
values (dict): Dict with ``mrc``, ``oai``, ``dc`` and ``fn`` keys.
"""
cls.mrc_out_el.text = values.get("mrc", "")
cls.oai_out_el.text = values.get("oai", "")
cls.d... | python | {
"resource": ""
} |
q53043 | OutputPicker.bind_download_buttons | train | def bind_download_buttons(cls):
"""
Bind buttons to callbacks.
"""
def on_click(ev):
button_el = ev.target
form_el = button_el.parent.parent.parent
# this allows to use disabled <textearea>, which is normally not
# sent
content... | python | {
"resource": ""
} |
q53044 | OutputPicker.reset | train | def reset(cls):
"""
Reset the datasets and interface to default values.
"""
cls.hide()
cls.values = None
cls.filename = "fn"
cls.dc_out_el.text = ""
cls.oai_out_el.text = ""
cls.mrc_out_el.text = "" | python | {
"resource": ""
} |
q53045 | Treal.start_capture | train | def start_capture(self):
"""Begin listening for output from the stenotype machine."""
if not self._connect():
log.warning('Treal is not connected')
self._error()
return
super(Treal, self).start_capture() | python | {
"resource": ""
} |
q53046 | Treal.stop_capture | train | def stop_capture(self):
"""Stop listening for output from the stenotype machine."""
super(Treal, self).stop_capture()
if self._machine:
self._machine.close()
self._stopped() | python | {
"resource": ""
} |
q53047 | vertical_strip | train | def vertical_strip(width=10, height=100, color=rgb(100, 100, 100),
subtlety=0.1):
"""
Draws a subtle vertical gradient strip.
"""
cairo_color = color / rgb(255, 255, 255)
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
ctx = cairo.Context(surface)
ctx.s... | python | {
"resource": ""
} |
q53048 | is_filter_type | train | def is_filter_type(target):
# type: (Any) -> Union[bool, Text]
"""
Returns whether the specified object can be registered as a filter.
:return:
Returns ``True`` if the object is a filter.
Otherwise, returns a string indicating why it is not valid.
"""
if not is_class(target):
... | python | {
"resource": ""
} |
q53049 | do_cleanup | train | def do_cleanup(connection, host_agent_id):
'''
Performs cleanup after the host agent who left his descriptor in database.
Deletes the descriptor and the descriptors of the partners he was hosting.
'''
desc = yield safe_get(connection, host_agent_id)
if isinstance(desc, host.Descriptor):
... | python | {
"resource": ""
} |
q53050 | AgentMixin._fix_alert_poster | train | def _fix_alert_poster(self, state, shard):
'''
Called after agent has switched a shard. Alert poster needs an update
in this case, bacause otherwise its posting to lobby instead of the
shard exchange.
'''
recp = recipient.Broadcast(AlertPoster.protocol_id, shard)
... | python | {
"resource": ""
} |
q53051 | compute_schedules | train | def compute_schedules(courses=None, excluded_times=(), free_sections_only=True, problem=None, return_generator=False, section_constraint=None):
"""
Returns all possible schedules for the given courses.
"""
s = Scheduler(free_sections_only, problem, constraint=section_constraint)
s.exclude_times(*tup... | python | {
"resource": ""
} |
q53052 | TimeRange.conflicts_with | train | def conflicts_with(self, section):
"Returns True if the given section conflicts with this time range."
for p in section.periods:
t = (p.int_days, p.start, p.end)
if t in self:
return True
return False | python | {
"resource": ""
} |
q53053 | Scheduler.exclude_time | train | def exclude_time(self, start, end, days):
"""Added an excluded time by start, end times and the days.
``start`` and ``end`` are in military integer times (e.g. - 1200 1430).
``days`` is a collection of integers or strings of fully-spelt, lowercased days
of the week.
"""... | python | {
"resource": ""
} |
q53054 | Scheduler.find_schedules | train | def find_schedules(self, courses=None, return_generator=False):
"""Returns all the possible course combinations. Assumes no duplicate courses.
``return_generator``: If True, returns a generator instead of collection. Generators
are friendlier to your memory and save computation time if not ... | python | {
"resource": ""
} |
q53055 | Scheduler.time_conflict | train | def time_conflict(self, schedule):
"""Internal use. Determines when the given time range conflicts with the set of
excluded time ranges.
"""
if is_nil(schedule):
return True
for timerange in self._excluded_times:
if timerange.conflicts_with(schedule):
... | python | {
"resource": ""
} |
q53056 | Scheduler.create_constraints | train | def create_constraints(self, courses):
"""Internal use. Creates all constraints in the problem instance for the given
courses.
"""
for i, course1 in enumerate(courses):
for j, course2 in enumerate(courses):
if i <= j:
continue
... | python | {
"resource": ""
} |
q53057 | const | train | def const(const):
'''Convenience wrapper to yield the value of a constant'''
try:
return getattr(_c, const)
except AttributeError:
raise FSQEnvError(errno.EINVAL, u'No such constant:'\
u' {0}'.format(const))
except TypeError:
raise TypeError(errno.E... | python | {
"resource": ""
} |
q53058 | set_const | train | def set_const(const, val):
'''Convenience wrapper to reliably set the value of a constant from
outside of package scope'''
try:
cur = getattr(_c, const)
except AttributeError:
raise FSQEnvError(errno.ENOENT, u'no such constant:'\
u' {0}'.format(const))
ex... | python | {
"resource": ""
} |
q53059 | make_request | train | def make_request(url, data, on_complete):
"""
Make AJAX request to `url` with given POST `data`. Call `on_complete`
callback when complete.
Args:
url (str): URL.
data (dict): Dictionary with POST data.
on_complete (ref): Reference to function / method which will be called
... | python | {
"resource": ""
} |
q53060 | func_on_enter | train | def func_on_enter(func):
"""
Register the `func` as a callback reacting only to ENTER.
Note:
This function doesn't bind the key to the element, just creates sort of
filter, which ignores all other events.
"""
def function_after_enter_pressed(ev):
ev.stopPropagation()
... | python | {
"resource": ""
} |
q53061 | Timer.get | train | def get(self):
"""Return the number of seconds elapsed since object creation,
or since last call to this function, whichever is more recent."""
elapsed = datetime.now() - self._previous
self._previous += elapsed
return elapsed.total_seconds() | python | {
"resource": ""
} |
q53062 | ConnectionManager.register_connection | train | def register_connection(self, alias, api_key, base_url, timeout=5):
"""
Create and register a new connection.
:param alias: The alias of the connection. If not changed with `switch_connection`,
the connection with default 'alias' is used by the resources.
:para... | python | {
"resource": ""
} |
q53063 | cprint | train | def cprint(msg, reset=True, template=ColorTemplate):
"""Same as cformat but prints a string.
"""
print(cformat(msg, reset, template)) | python | {
"resource": ""
} |
q53064 | ExecutionContext.parse_xml_node | train | def parse_xml_node(self, node):
'''Parse an xml.dom Node object representing an execution context into
this object.
'''
self.id = node.getAttributeNS(RTS_NS, 'id')
self.kind = node.getAttributeNS(RTS_NS, 'kind')
if node.hasAttributeNS(RTS_NS, 'rate'):
self.ra... | python | {
"resource": ""
} |
q53065 | ExecutionContext.parse_yaml | train | def parse_yaml(self, y):
'''Parse a YAML spefication of an execution context into this
object.
'''
self.id = y['id']
self.kind = y['kind']
if 'rate' in y:
self.rate = float(y['rate'])
else:
self.rate = 0.0
self._participants = []
... | python | {
"resource": ""
} |
q53066 | ExecutionContext.save_xml | train | def save_xml(self, doc, element):
'''Save this execution context into an xml.dom.Element object.'''
element.setAttributeNS(XSI_NS, XSI_NS_S + 'type', 'rtsExt:execution_context_ext')
element.setAttributeNS(RTS_NS, RTS_NS_S + 'id', self.id)
element.setAttributeNS(RTS_NS, RTS_NS_S + 'kind',... | python | {
"resource": ""
} |
q53067 | ExecutionContext.to_dict | train | def to_dict(self):
'''Save this execution context into a dictionary.'''
d = {'id': self.id,
'kind': self.kind}
if self.rate != 0.0:
d['rate'] = self.rate
participants = []
for p in self.participants:
participants.append(p.to_dict())
... | python | {
"resource": ""
} |
q53068 | alphanum_key | train | def alphanum_key(string):
"""Return a comparable tuple with extracted number segments.
Adapted from: http://stackoverflow.com/a/2669120/176978
"""
convert = lambda text: int(text) if text.isdigit() else text
return [convert(segment) for segment in re.split('([0-9]+)', string)] | python | {
"resource": ""
} |
q53069 | clone | train | def clone(item, exclude=None, update=None):
"""Return a clone of the SQLA object.
:param item: The SQLA object to copy the attributes from.
:param exclude: If provided, should be an iterable that contains the names
attributes to exclude from the copy. The attributes `created_at` and
`id` ar... | python | {
"resource": ""
} |
q53070 | fetch_request_ids | train | def fetch_request_ids(item_ids, cls, attr_name, verification_list=None):
"""Return a list of cls instances for all the ids provided in item_ids.
:param item_ids: The list of ids to fetch objects for
:param cls: The class to fetch the ids from
:param attr_name: The name of the attribute for exception pu... | python | {
"resource": ""
} |
q53071 | get_queue_func | train | def get_queue_func(request):
"""Establish the connection to rabbitmq."""
def cleanup(request):
conn.close()
def queue_func(**kwargs):
return conn.channel().basic_publish(
exchange='', body=json.dumps(kwargs), routing_key=queue,
properties=pika.BasicProperties(deliver... | python | {
"resource": ""
} |
q53072 | prev_next_group | train | def prev_next_group(project, group):
"""Return adjacent group objects or None for the given project and group.
The previous and next group objects are relative to sort order of the
project's groups with respect to the passed in group.
"""
# TODO: Profile and optimize this query if necessary
gr... | python | {
"resource": ""
} |
q53073 | prepare_renderable | train | def prepare_renderable(request, test_case_result, is_admin):
"""Return a completed Renderable."""
test_case = test_case_result.test_case
file_directory = request.registry.settings['file_directory']
sha1 = test_case_result.diff.sha1 if test_case_result.diff else None
kwargs = {'number': test_case.id,... | python | {
"resource": ""
} |
q53074 | DBThing.run | train | def run(self, value, errors, request):
"""Return the object if valid and available, otherwise None."""
value = self.id_validator(value, errors, request)
if errors:
return None
if self.fetch_by:
thing = self.cls.fetch_by(**{self.fetch_by: value})
else:
... | python | {
"resource": ""
} |
q53075 | ViewableDBThing.run | train | def run(self, value, errors, request):
"""Return thing, but abort validation if request.user cannot view."""
thing = super(ViewableDBThing, self).run(value, errors, request)
if errors:
return None
if not thing.can_view(request.user):
message = 'Insufficient permis... | python | {
"resource": ""
} |
q53076 | define_standalone_options | train | def define_standalone_options(parser, extra_options=None):
'''
Adds the options specific to the database connection.
Parses the agency configuration files and uses its configuration as the
default values.
'''
c = config.parse_service_config()
parser.add_option('--dbhost', '-H', action='stor... | python | {
"resource": ""
} |
q53077 | view_aterator | train | def view_aterator(connection, callback, view, view_keys=dict(),
args=tuple(), kwargs=dict(), per_page=15,
consume_errors=True):
'''
Asynchronous iterator for the view. Downloads a view in pages
and calls the callback for each row.
This helps avoid transfering data in ... | python | {
"resource": ""
} |
q53078 | main | train | def main(host, port, timeout, itimeout, qsize, backlog, maxtry, bsize, verbose, logfile=None, logcfgfile=None, cfgfile=None):
"""Simple python implementation of a socks5 proxy server. """
dict_cfg = {}
if cfgfile:
dict_cfg = app_config.get_config_by_file(cfgfile)
def get_param(key, param, defa... | python | {
"resource": ""
} |
q53079 | _get_config_dirs | train | def _get_config_dirs():
"""Return a list of directories where config files may be located.
The following directories are returned::
$XDG_CONFIG_HOME/rapport/ ($XDG_CONFIG_HOME defaults to ~/.config)
/etc/rapport/
"""
config_dirs = [
USER_CONFIG_DIR,
os.path.join("/", "etc",... | python | {
"resource": ""
} |
q53080 | find_config_files | train | def find_config_files():
"""Return a list of default configuration files.
"""
config_files = []
for config_dir in _get_config_dirs():
path = os.path.join(config_dir, "rapport.conf")
if os.path.exists(path):
config_files.append(path)
return list(filter(bool, config_file... | python | {
"resource": ""
} |
q53081 | get_version | train | def get_version(package_name, version_file='_version.py'):
"""Retrieve the package version from a version file in the package root."""
filename = os.path.join(os.path.dirname(__file__), package_name, version_file)
with open(filename, 'rb') as fp:
return fp.read().decode('utf8').split('=')[1].strip("... | python | {
"resource": ""
} |
q53082 | read_kw_file | train | def read_kw_file():
"""
Read content of the file containing keyword informations in JSON. File is
packed using BZIP.
Returns:
list: List of dictionaries containing keywords.
"""
self_path = os.path.dirname(__file__)
kw_list_path = join(self_path, "../templates/keyword_list.json.bz2"... | python | {
"resource": ""
} |
q53083 | build_kw_dict | train | def build_kw_dict(kw_list):
"""
Build keyword dictionary from raw keyword data. Ignore invalid or
invalidated records.
Args:
kw_list (list): List of dicts from :func:`read_kw_file`.
Returns:
OrderedDict: dictionary with keyword data.
"""
kw_dict = OrderedDict()
sorted_l... | python | {
"resource": ""
} |
q53084 | extract_extension | train | def extract_extension(path):
"""
Reads a file path and returns the extension or None if the path
contains no extension.
:Parameters:
path : str
A filesystem path
"""
filename = os.path.basename(path)
parts = filename.split(".")
if len(parts) == 1:
return file... | python | {
"resource": ""
} |
q53085 | normalize_path | train | def normalize_path(path_or_f):
"""
Verifies that a file exists at a given path and that the file has a
known extension type.
:Parameters:
path_or_f : `str` | `file`
the path to a dump file or a file handle
"""
if hasattr(path_or_f, "read"):
return path_or_f
else... | python | {
"resource": ""
} |
q53086 | writer | train | def writer(path):
"""
Creates a compressed file writer from for a path with a specified
compression type.
"""
filename, extension = extract_extension(path)
if extension in FILE_WRITERS:
writer_func = FILE_WRITERS[extension]
return writer_func(path)
else:
raise Runtime... | python | {
"resource": ""
} |
q53087 | Display.get_desktop_size | train | def get_desktop_size(self):
"""Get the size of the desktop display"""
_ptr = ffi.new('SDL_DisplayMode *')
check_int_err(lib.SDL_GetDesktopDisplayMode(self._index, _ptr))
return (_ptr.w, _ptr.h) | python | {
"resource": ""
} |
q53088 | TAF_datetime_to_datetime_object | train | def TAF_datetime_to_datetime_object(
datetime_string = None,
datetime_for_year_and_month = None # e.g. datetime.datetime.utcnow()
):
"""
Preprocess datetimes to change hours from 24 to 00, incrementing the date
as necessary.
"""
if datetime_string.endswith("24"):
... | python | {
"resource": ""
} |
q53089 | Request.api_url | train | def api_url(self):
'''return the api url of this request'''
return pathjoin(Request.path, self.id, url=self.bin.api_url) | python | {
"resource": ""
} |
q53090 | record_used | train | def record_used(kind, hash):
"""
Indicates a cachefile with the name 'hash' of a particular kind has been used so it will note be deleted on the next purge.
:param str kind: The kind of cachefile. One of 'cache', 'seeds', or 'evs'
:param str hash: The hash for the call descriptor, expected value descri... | python | {
"resource": ""
} |
q53091 | delete_io | train | def delete_io( hash ):
"""
Deletes records associated with a particular hash
:param str hash: The hash
:rtype int: The number of records deleted
"""
global CACHE_
load_cache(True)
record_used('cache', hash)
num_deleted = len(CACHE_['cache'].get(hash, []))
if hash in CACHE_['cac... | python | {
"resource": ""
} |
q53092 | delete_from_directory_by_hashes | train | def delete_from_directory_by_hashes(cache_type, hashes):
"""
Deletes all cache files corresponding to a list of hashes from a directory
:param str directory: The type of cache to delete files for.
:param list(str) hashes: The hashes to delete the files for
"""
global CACHE_
if hashes == '*... | python | {
"resource": ""
} |
q53093 | read_all | train | def read_all():
"""
Reads all the hashes and returns them in a dictionary by type
:rtype: dict
:returns: A dictionary of sets of hashes by type
"""
global CACHE_
load_cache(True)
evs = CACHE_['evs'].keys()
cache = CACHE_['cache'].keys()
seeds = CACHE_['seeds'].keys()
return ... | python | {
"resource": ""
} |
q53094 | purge | train | def purge():
"""
Deletes all the cached files since the last call to reset_used that have not been used.
"""
all_hashes = read_all()
used_hashes = read_used()
for kind, hashes in used_hashes.items():
hashes = set(hashes)
to_remove = set(all_hashes[kind]).difference(hashes)
... | python | {
"resource": ""
} |
q53095 | save_stack | train | def save_stack(stack):
"""
Saves a stack object to a flatfile.
:param caliendo.hooks.CallStack stack: The stack to save.
"""
global CACHE_
serialized = pickle.dumps(stack, PPROT)
CACHE_['stacks']["{0}.{1}".format(stack.module, stack.caller)] = serialized
write_out() | python | {
"resource": ""
} |
q53096 | load_stack | train | def load_stack(stack):
"""
Loads the saved state of a CallStack and returns a whole instance given an instance with incomplete state.
:param caliendo.hooks.CallStack stack: The stack to load
:returns: A CallStack previously built in the context of a patch call.
:rtype: caliendo.hooks.CallStack
... | python | {
"resource": ""
} |
q53097 | delete_stack | train | def delete_stack(stack):
"""
Deletes a stack that was previously saved.load_stack
:param caliendo.hooks.CallStack stack: The stack to delete.
"""
global CACHE_
key = "{0}.{1}".format(stack.module, stack.caller)
if key in CACHE_['stacks']:
del CACHE_['stacks'][key]
write_out(... | python | {
"resource": ""
} |
q53098 | Pipe._write | train | def _write(self, what):
"""writes something to the Purr pipe"""
try:
open(self.pipefile, "a").write(what)
except:
print("Error writing to %s:" % self.pipefile)
traceback.print_exc() | python | {
"resource": ""
} |
q53099 | Pipe.title | train | def title(self, title, show=False):
"""writes a title tag to the Purr pipe"""
self._write("title:%d:%s\n" % (int(show), title))
return self | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.