text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extend_rows(self, list_or_dict): """ Add multiple rows at once :param list_or_dict: a 2 dimensional structure for adding multiple rows at once :return: """
if isinstance(list_or_dict, list): for r in list_or_dict: self.add_row(r) else: for k,r in list_or_dict.iteritems(): self.add_row(r, k)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_row_list(self, row_idx): """ get a feature vector for the nth row :param row_idx: which row :return: a list of feature values, ordered by column_names ""...
try: row = self._rows[row_idx] except TypeError: row = self._rows[self._row_name_idx[row_idx]] if isinstance(row, list): extra = [ self._default_value ] * (len(self._column_name_list) - len(row)) return row + extra else: if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_row_dict(self, row_idx): """ Return a dictionary representation for a matrix row :param row_idx: which row :return: a dict of feature keys/values, not in...
try: row = self._rows[row_idx] except TypeError: row = self._rows[self._row_name_idx[row_idx]] if isinstance(row, dict): return row else: if row_idx not in self._row_memo: self._row_memo[row_idx] = dict((self._column_nam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_matrix(self): """ Use numpy to create a real matrix object from the data :return: the matrix representation of the fvm """
return np.array([ self.get_row_list(i) for i in range(self.row_count()) ])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transpose(self): """ Create a matrix, transpose it, and then create a new FVM :raise NotImplementedError: if all existing rows aren't keyed :return: a new FV...
if len(self._row_name_list) != len(self._rows): raise NotImplementedError("You can't rotate a FVM that doesn't have all rows keyed") fvm = FeatureVectorMatrix(default_value=self._default_value, default_to_hashed_rows=self._default_to_hashed_rows) fvm._update_internal_column_state(s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def keys(self): """ Returns all row keys :raise NotImplementedError: if all rows aren't keyed :return: all row keys """
if len(self._row_name_list) != len(self._rows): raise NotImplementedError("You can't get row keys for a FVM that doesn't have all rows keyed") return self.row_names()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def uni(key): '''as a crutch, we allow str-type keys, but they really should be unicode. ''' if isinstance(key, str): logger.warn('assuming utf8 on: %r', key) return unicode(key, 'utf-8') elif isinstance(key, unicode): return key else: raise NonUnicodeKeyError(ke...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert(self, string, preprocess = None): """ Swap characters from a script to transliteration and vice versa. Optionally sanitize string by using preprocess...
string = unicode(preprocess(string) if preprocess else string, encoding="utf-8") if self.regex: return self.regex.sub(lambda x: self.substitutes[x.group()], string).encode('utf-8') else: return string
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_image(self, image_file, caption): """ Create an image with a caption """
suffix = 'png' if image_file: img = Image.open(os.path.join(self.gallery, image_file)) width, height = img.size ratio = width/WIDTH img = img.resize((int(width // ratio), int(height // ratio)), Im...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_caption(self, image, caption, colour=None): """ Add a caption to the image """
if colour is None: colour = "white" width, height = image.size draw = ImageDraw.Draw(image) draw.font = self.font draw.font = self.font draw.text((width // 10, height//20), caption, fill=colour) return image
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def from_caller_file(): '''return a `Path` from the path of caller file''' import inspect curframe = inspect.currentframe() calframe = inspect.getouterframes(curframe, 2) filename = calframe[1].filename if not os.path.isfile(filename): raise RuntimeError('call...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def from_caller_module_root(): '''return a `Path` from module root which include the caller''' import inspect all_stack = list(inspect.stack()) curframe = inspect.currentframe() calframe = inspect.getouterframes(curframe, 2) module = inspect.getmodule(calframe[1].frame) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def commitreturn(self,qstring,vals=()): "commit and return result. This is intended for sql UPDATE ... RETURNING" with self.withcur() as cur: cur.execute(qstring,vals) return cur.fetchone()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getResponse(self, http_request, request): """ Processes the AMF request, returning an AMF response. @param http_request: The underlying HTTP Request. @type h...
response = remoting.Envelope(request.amfVersion) for name, message in request: http_request.amf_request = message processor = self.getProcessor(message) response[name] = processor(message, http_request=http_request) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_driver(driver='ASCII_RS232', *args, **keywords): """ Gets a driver for a Parker Motion Gemini drive. Gets and connects a particular driver in ``drivers``...
if driver.upper() == 'ASCII_RS232': return drivers.ASCII_RS232(*args, **keywords) else: raise NotImplementedError('Driver not supported: ' + str(driver))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_parameter(self, name, tp, timeout=1.0, max_retries=2): """ Gets the specified drive parameter. Gets a parameter from the drive. Only supports ``bool``, ...
# Raise a TypeError if tp isn't one of the valid types. if tp not in (bool, int, float): raise TypeError('Only supports bool, int, and float; not ' + str(tp)) # Sending a command of name queries the state for that # parameter. The response will have na...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_parameter(self, name, value, tp, timeout=1.0, max_retries=2): """ Sets the specified drive parameter. Sets a parameter on the drive. Only supports ``boo...
# Return False if tp isn't one of the valid types. if tp not in (bool, int, float): return False # Convert value to the string that the drive will expect. value # must first be converted to the proper type before getting # converted to str in the usual fasion. As bo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_program(self, n, timeout=2.0, max_retries=2): """ Get a program from the drive. Gets program 'n' from the drive and returns its commands. Parameters n : ...
# Send the 'TPROG PROGn' command to read the program. response = self.driver.send_command( \ 'TPROG PROG' + str(int(n)), timeout=timeout, \ immediate=True, max_retries=max_retries) # If there was an error, then return empty. Otherwise, return # the response line...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def motion_commanded(self): """ Whether motion is commanded or not. ``bool`` Can't be set. Notes ----- It is the value of the first bit of the 'TAS' command. """
rsp = self.driver.send_command('TAS', immediate=True) if self.driver.command_error(rsp) or len(rsp[4]) != 1 \ or rsp[4][0][0:4] != '*TAS': return False else: return (rsp[4][0][4] == '1')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def apply_fixup_array(bin_view, fx_offset, fx_count, entry_size): '''This function reads the fixup array and apply the correct values to the underlying binary stream. This function changes the bin_view in memory. Args: bin_view (memoryview of bytearray) - The binary stream fx_offset (in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_file_size(file_object): '''Returns the size, in bytes, of a file. Expects an object that supports seek and tell methods. Args: file_object (file_object) - The object that represents the file Returns: (int): size of the file, in bytes''' position = file_object.tell() fi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def context_processor(self, func): """ Decorate a given function to use as a context processor. :: @app.ps.jinja2.context_processor def my_context(): """
func = to_coroutine(func) self.providers.append(func) return func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, value): """ Register function to globals. """
if self.env is None: raise PluginException('The plugin must be installed to application.') def wrapper(func): name = func.__name__ if isinstance(value, str): name = value if callable(func): self.env.globals[name] = func ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter(self, value): """ Register function to filters. """
if self.env is None: raise PluginException('The plugin must be installed to application.') def wrapper(func): name = func.__name__ if isinstance(value, str): name = value if callable(func): self.env.filters[name] = func ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_event(self, event): """ An abstract method that must be overwritten by child classes used to handle events. event - the event to be handled returns tr...
# loop through the handlers associated with the event type. for h in self._events.get(event.type, []): # Iterate through the handler's dictionary of event parameters for k, v in h.params.items(): # get the value of event.k, if none, return v if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logger(self, logger): """Set the logger if is not None, and it is of type Logger."""
if logger is None or not isinstance(logger, Logger): raise ValueError("Logger can not be set to None, and must be of type logging.Logger") self._logger = logger
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_handler(self, type, actions, **kwargs): """ Add an event handler to be processed by this session. type - The type of the event (pygame.QUIT, pygame.KEYUP...
l = self._events.get(type, []) h = Handler(self, type, kwargs, actions) l.append(h) self._events[type] = l return h
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_handler(self, handler): """ Remove a handler from the list. handler - The handler (as returned by add_handler) to remove. Returns True on success, Fal...
try: self._events[handler.type].remove(handler) return True except ValueError: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_keydown(self, actions, **kwargs): """ Add a pygame.KEYDOWN event handler. actions - The methods to be called when this key is pressed. kwargs - The kwarg...
return self.add_handler(pygame.KEYDOWN, actions, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_keyup(self, actions, **kwargs): """See the documentation for self.add_keydown."""
return self.add_handler(pygame.KEYUP, actions, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_event_params(self, handler, **kwargs): """ This allows the client to change the parameters for an event, in the case that there is a desire for slight...
if not isinstance(handler, Handler): raise TypeError("given object must be of type Handler.") if not self.remove_handler(handler): raise ValueError("You must pass in a valid handler that already exists.") self.add_handler(handler.type, handler.actions, **kwargs) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_event_actions(self, handler, actions): """ This allows the client to change the actions for an event, in the case that there is a desire for slightly ...
if not isinstance(handler, Handler): raise TypeError("given object must be of type Handler.") if not self.remove_handler(handler): raise ValueError("You must pass in a valid handler that already exists.") self.add_handler(handler.type, actions, handler.params) s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, bits=2048, type=crypto.TYPE_RSA, digest='sha1'): """ Get a new self-signed certificate @type bits: int @type digest: str @rtype: Certificate """
self.log.debug('Creating a new self-signed SSL certificate') # Generate the key and ready our cert key = crypto.PKey() key.generate_key(type, bits) cert = crypto.X509() # Fill in some pseudo certificate information with a wildcard common name cert.get_subject()....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_compressed_string(val, max_length=0): """Converts val to a compressed string. A compressed string is one with no leading or trailing spaces. If val is Non...
if val is None or len(val) == 0: return None rval = " ".join(val.split()) if len(rval) == 0: return None if max_length == 0: return rval else: return rval[:max_length]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def incrementor(start=0, step=1): """Returns a function that first returns the start value, and returns previous value + step on each subsequent call. """
def fxn(_): """Returns the next value in the sequnce defined by [start::step)""" nonlocal start rval = start start += step return rval return fxn
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_static_matching(app, directory_serve_app=DirectoryApp): """ Creating a matching for WSGI application to serve static files for passed app. Static fi...
static_dir = os.path.join(os.path.dirname(app.__file__), 'static') try: static_app = directory_serve_app(static_dir, index_page='') except OSError: return None static_pattern = '/static/{app.__name__}/*path'.format(app=app) static_name = '{app.__name__}...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_static_app_matching(apps): """ Returning a matching containing applications to serve static files correspond to each passed applications. """
return reduce(lambda a, b: a + b, [generate_static_matching(app) for app in apps if app is not None])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def random(magnitude=1): """ Create a unit vector pointing in a random direction. """
theta = random.uniform(0, 2 * math.pi) return magnitude * Vector(math.cos(theta), math.sin(theta))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_rectangle(box): """ Create a vector randomly within the given rectangle. """
x = box.left + box.width * random.uniform(0, 1) y = box.bottom + box.height * random.uniform(0, 1) return Vector(x, y)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interpolate(self, target, extent): """ Move this vector towards the given towards the target by the given extent. The extent should be between 0 and 1. """
target = cast_anything_to_vector(target) self += extent * (target - self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def project(self, axis): """ Project this vector onto the given axis. """
projection = self.get_projection(axis) self.assign(projection)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dot_product(self, other): """ Return the dot product of the given vectors. """
return self.x * other.x + self.y * other.y
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def perp_product(self, other): """ Return the perp product of the given vectors. The perp product is just a cross product where the third dimension is taken to b...
return self.x * other.y - self.y * other.x
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rotate(self, angle): """ Rotate the given vector by an angle. Angle measured in radians counter-clockwise. """
x, y = self.tuple self.x = x * math.cos(angle) - y * math.sin(angle) self.y = x * math.sin(angle) + y * math.cos(angle)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def round(self, digits=0): """ Round the elements of the given vector to the given number of digits. """
# Meant as a way to clean up Vector.rotate() # For example: # V = Vector(1,0) # V.rotate(2*pi) # # V is now <1.0, -2.4492935982947064e-16>, when it should be # <1,0>. V.round(15) will correct the error in this example. self.x = round(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_scaled(self, magnitude): """ Return a unit vector parallel to this one. """
result = self.copy() result.scale(magnitude) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_interpolated(self, target, extent): """ Return a new vector that has been moved towards the given target by the given extent. The extent should be betwee...
result = self.copy() result.interpolate(target, extent) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_projection(self, axis): """ Return the projection of this vector onto the given axis. The axis does not need to be normalized. """
scale = axis.dot(self) / axis.dot(axis) return axis * scale
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_components(self, other): """ Break this vector into one vector that is perpendicular to the given vector and another that is parallel to it. """
tangent = self.get_projection(other) normal = self - tangent return normal, tangent
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_radians(self): """ Return the angle between this vector and the positive x-axis measured in radians. Result will be between -pi and pi. """
if not self: raise NullVectorError() return math.atan2(self.y, self.x)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_rotated(self, angle): """ Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. """
result = self.copy() result.rotate(angle) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_rounded(self, digits): """ Return a vector with the elements rounded to the given number of digits. """
result = self.copy() result.round(digits) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_radians(self, angle): """ Set the angle that this vector makes with the x-axis. """
self.x, self.y = math.cos(angle), math.sin(angle)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def grow(self, *padding): """ Grow this rectangle by the given padding on all sides. """
try: lpad, rpad, tpad, bpad = padding except ValueError: lpad = rpad = tpad = bpad = padding[0] self._bottom -= bpad self._left -= lpad self._width += lpad + rpad self._height += tpad + bpad return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def displace(self, vector): """ Displace this rectangle by the given vector. """
self._bottom += vector.y self._left += vector.x return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def round(self, digits=0): """ Round the dimensions of the given rectangle to the given number of digits. """
self._left = round(self._left, digits) self._bottom = round(self._bottom, digits) self._width = round(self._width, digits) self._height = round(self._height, digits)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set(self, shape): """ Fill this rectangle with the dimensions of the given shape. """
self.bottom, self.left = shape.bottom, shape.left self.width, self.height = shape.width, shape.height return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inside(self, other): """ Return true if this rectangle is inside the given shape. """
return ( self.left >= other.left and self.right <= other.right and self.top <= other.top and self.bottom >= other.bottom)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def touching(self, other): """ Return true if this rectangle is touching the given shape. """
if self.top < other.bottom: return False if self.bottom > other.top: return False if self.left > other.right: return False if self.right < other.left: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def contains(self, other): """ Return true if the given shape is inside this rectangle. """
return (self.left <= other.left and self.right >= other.right and self.top >= other.top and self.bottom <= other.bottom)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(self, nodes): """Given a stream of node data, try to parse the nodes according to the machine's graph."""
self.last_node_type = self.initial_node_type for node_number, node in enumerate(nodes): try: self.step(node) except Exception as ex: raise Exception("An error occurred on node {}".format(node_number)) from ex
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_name_for(self, dynamic_part): """ Return the name for the current dynamic field, accepting a limpyd instance for the dynamic part """
dynamic_part = self.from_python(dynamic_part) return super(DynamicRelatedFieldMixin, self).get_name_for(dynamic_part)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_to_toml_obj(self, toml_obj: tomlkit.container.Container, not_set: str): """ Updates the given container in-place with this ConfigValue :param toml_obj: c...
self._toml_add_description(toml_obj) self._toml_add_value_type(toml_obj) self._toml_add_comments(toml_obj) toml_obj.add(tomlkit.comment('')) self._toml_add_value(toml_obj, not_set)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jackknife_stats(theta_subs, theta_full, N=None, d=1): """Compute Jackknife Estimates, SE, Bias, t-scores, p-values Parameters: theta_subs : ndarray The metri...
# The biased Jackknife Estimate import numpy as np theta_biased = np.mean(theta_subs, axis=0) # Inflation Factor for the Jackknife Standard Error if d is 1: if N is None: N = theta_subs.shape[0] inflation = (N - 1) / N elif d > 1: if N is None: r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def space_out_camel_case(stringAsCamelCase): """ Adds spaces to a camel case string. Failure to space out string returns the original string. 'DMLS Services Othe...
pattern = re.compile(r'([A-Z][A-Z][a-z])|([a-z][A-Z])') if stringAsCamelCase is None: return None return pattern.sub(lambda m: m.group()[:1] + " " + m.group()[1:], stringAsCamelCase)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def slugify(text, length_limit=0, delimiter=u'-'): """Generates an ASCII-only slug of a string."""
result = [] for word in _punctuation_regex.split(text.lower()): word = _available_unicode_handlers[0](word) if word: result.append(word) slug = delimiter.join(result) if length_limit > 0: return slug[0:length_limit] return slug
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, stream): """ Will parse the stream until a complete sexp has been read. Returns True until state is complete. """
stack = self.stack while True: if stack[0]: # will be true once one sexp has been parsed self.rest_string = stream return False c = stream.read(1) if not c: # no more stream and no complete sexp return ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def name_to_vector(name): """ Convert `name` to the ASCII vector. Example: ['putsalek', 'franta', 'ing'] Args: name (str): Name which will be vectorized. Return...
if not isinstance(name, unicode): name = name.decode("utf-8") name = name.lower() name = unicodedata.normalize('NFKD', name).encode('ascii', 'ignore') name = "".join(filter(lambda x: x.isalpha() or x == " ", list(name))) return sorted(name.split(), key=lambda x: len(x), reverse=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare_names(first, second): """ Compare two names in complicated, but more error prone way. Algorithm is using vector comparison. Example: 100.0 50.0 Args:...
first = name_to_vector(first) second = name_to_vector(second) zipped = zip(first, second) if not zipped: return 0 similarity_factor = 0 for fitem, _ in zipped: if fitem in second: similarity_factor += 1 return (float(similarity_factor) / len(zipped)) * 100
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_publication(publication, cmp_authors=True): """ Filter publications based at data from Aleph. Args: publication (obj): :class:`.Publication` instance...
query = None isbn_query = False # there can be ISBN query or book title query if publication.optionals and publication.optionals.ISBN: query = aleph.ISBNQuery(publication.optionals.ISBN) isbn_query = True else: query = aleph.TitleQuery(publication.title) result = aleph...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_long_description(): """ Read the long description. """
here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst')) as readme: return readme.read() return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pop_state(self, idx=None): """ Pops off the most recent state. :param idx: If provided, specifies the index at which the next string begins. """
self.state.pop() if idx is not None: self.str_begin = idx
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_text(self, end, next=None): """ Adds the text from string beginning to the specified ending index to the format. :param end: The ending index of the stri...
if self.str_begin != end: self.fmt.append_text(self.format[self.str_begin:end]) if next is not None: self.str_begin = next
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_escape(self, idx, char): """ Translates and adds the escape sequence. :param idx: Provides the ending index of the escape sequence. :param char: The actu...
self.fmt.append_text(self.fmt._unescape.get( self.format[self.str_begin:idx], char))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_param(self, idx): """ Adds the parameter to the conversion modifier. :param idx: Provides the ending index of the parameter string. """
self.modifier.set_param(self.format[self.param_begin:idx])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_conversion(self, idx): """ Adds the conversion to the format. :param idx: The ending index of the conversion name. """
# First, determine the name if self.conv_begin: name = self.format[self.conv_begin:idx] else: name = self.format[idx] # Next, add the status code modifiers, as needed if self.codes: self.modifier.set_codes(self.codes, self.reject) #...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_code(self, idx): """ Sets a code to be filtered on for the conversion. Note that this also sets the 'code_last' attribute and configures to ignore the re...
code = self.format[idx:idx + 3] if len(code) < 3 or not code.isdigit(): return False self.codes.append(int(code)) self.ignore = 2 self.code_last = True return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def end_state(self): """ Wrap things up and add any final string content. """
# Make sure we append any trailing text if self.str_begin != len(self.format): if len(self.state) > 1 or self.state[-1] != 'string': self.fmt.append_text( "(Bad format string; ended in state %r)" % self.state[-1]) else: self.f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def conversion(self, idx): """ Switches into the 'conversion' state, used to parse a % conversion. :param idx: The format string index at which the conversion be...
self.state.append('conversion') self.str_begin = idx self.param_begin = None self.conv_begin = None self.modifier = conversions.Modifier() self.codes = [] self.reject = False self.code_last = False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_conversion(cls, conv_chr, modifier): """ Return a conversion given its character. :param conv_chr: The letter of the conversion, e.g., "a" for AddressCo...
# Do we need to look up the conversion? if conv_chr not in cls._conversion_cache: for ep in pkg_resources.iter_entry_points('bark.conversion', conv_chr): try: # Load the conversion class ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(cls, format): """ Parse a format string. Factory function for the Format class. :param format: The format string to parse. :returns: An instance of cla...
fmt = cls() # Return an empty Format if format is empty if not format: return fmt # Initialize the state for parsing state = ParseState(fmt, format) # Loop through the format string with a state-based parser for idx, char in enumerate(format): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_text(self, text): """ Append static text to the Format. :param text: The text to append. """
if (self.conversions and isinstance(self.conversions[-1], conversions.StringConversion)): self.conversions[-1].append(text) else: self.conversions.append(conversions.StringConversion(text))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare(self, request): """ Performs any preparations necessary for the Format. :param request: The webob Request object describing the request. :returns: A ...
data = [] for conv in self.conversions: data.append(conv.prepare(request)) return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert(self, request, response, data): """ Performs the desired formatting. :param request: The webob Request object describing the request. :param response...
result = [] for conv, datum in zip(self.conversions, data): # Only include conversion if it's allowed if conv.modifier.accept(response.status_code): result.append(conv.convert(request, response, datum)) else: result.append('-') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def FDR_BH(self, p): """Benjamini-Hochberg p-value correction for multiple hypothesis testing."""
p = np.asfarray(p) by_descend = p.argsort()[::-1] by_orig = by_descend.argsort() steps = float(len(p)) / np.arange(len(p), 0, -1) q = np.minimum(1, np.minimum.accumulate(steps * p[by_descend])) return q[by_orig]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_valid(self, name=None, debug=False): """ Check to see if the current xml path is to be processed. """
valid_tags = self.action_tree invalid = False for item in self.current_tree: try: if item in valid_tags or self.ALL_TAGS in valid_tags: valid_tags = valid_tags[item if item in valid_tags else self.ALL_TAGS] else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def category_helper(form_tag=True): """ Category's form layout helper """
helper = FormHelper() helper.form_action = '.' helper.attrs = {'data_abide': ''} helper.form_tag = form_tag helper.layout = Layout( Row( Column( 'title', css_class='small-12' ), ), Row( Column( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def thread_helper(form_tag=True, edit_mode=False, for_moderator=False): """ Thread's form layout helper """
helper = FormHelper() helper.form_action = '.' helper.attrs = {'data_abide': ''} helper.form_tag = form_tag fieldsets = [ Row( Column( 'subject', css_class='small-12' ), ), ] # Category field only in edit form...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post_helper(form_tag=True, edit_mode=False): """ Post's form layout helper """
helper = FormHelper() helper.form_action = '.' helper.attrs = {'data_abide': ''} helper.form_tag = form_tag fieldsets = [ Row( Column( 'text', css_class='small-12' ), ), ] # Threadwatch option is not in edit f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post_delete_helper(form_tag=True): """ Message's delete form layout helper """
helper = FormHelper() helper.form_action = '.' helper.attrs = {'data_abide': ''} helper.form_tag = form_tag helper.layout = Layout( ButtonHolderPanel( Row( Column( 'confirm', css_class='small-12 medium-8' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def permission_required_raise(perm, login_url=None, raise_exception=True): """ A permission_required decorator that raises by default. """
return permission_required(perm, login_url=login_url, raise_exception=raise_exception)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_self(func): """ Decorator that can be used to ensure 'self' is the first argument on a task method. This only needs to be used with task methods that ...
@wraps(func) def inner(*args, **kwargs): try: self = kwargs.pop('this') if len(args) >= 1 and self == args[0]: # Make the assumption that the first argument hasn't been passed in twice... raise KeyError() return func(self, *args, **kw...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def singleton_per_scope(_cls, _scope=None, _renew=False, *args, **kwargs): """Instanciate a singleton per scope."""
result = None singletons = SINGLETONS_PER_SCOPES.setdefault(_scope, {}) if _renew or _cls not in singletons: singletons[_cls] = _cls(*args, **kwargs) result = singletons[_cls] return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _safe_processing(nsafefn, source, _globals=None, _locals=None): """Do a safe processing of input fn in using SAFE_BUILTINS. :param fn: function to call with ...
if _globals is None: _globals = SAFE_BUILTINS else: _globals.update(SAFE_BUILTINS) return nsafefn(source, _globals, _locals)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getcodeobj(consts, intcode, newcodeobj, oldcodeobj): """Get code object from decompiled code. :param list consts: constants to add in the result. :param list...
# get code string if PY3: codestr = bytes(intcode) else: codestr = reduce(lambda x, y: x + y, (chr(b) for b in intcode)) # get vargs vargs = [ newcodeobj.co_argcount, newcodeobj.co_nlocals, newcodeobj.co_stacksize, newcodeobj.co_flags, codestr, tuple(consts), newc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind_all(morc, builtin_only=False, stoplist=None, verbose=None): """Recursively apply constant binding to functions in a module or class. Use as the last lin...
if stoplist is None: stoplist = [] def _bind_all(morc, builtin_only=False, stoplist=None, verbose=False): """Internal bind all decorator function. """ if stoplist is None: stoplist = [] if isinstance(morc, (ModuleType, type)): for k, val in lis...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_constants(builtin_only=False, stoplist=None, verbose=None): """Return a decorator for optimizing global references. Replaces global references with thei...
if stoplist is None: stoplist = [] if isinstance(builtin_only, type(make_constants)): raise ValueError("The bind_constants decorator must have arguments.") return lambda func: _make_constants(func, builtin_only, stoplist, verbose)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init(vcs): """Initialize the locking module for a repository """
path = os.path.join(vcs.private_dir(), 'locks') if not os.path.exists(path): os.mkdir(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lock(vcs, lock_object, wait=True): """A context manager that grabs the lock and releases it when done. This blocks until the lock can be acquired. Args: vcs ...
if wait: timeout = -1 else: timeout = 0 lock_path = _get_lock_path(vcs, lock_object) lock = filelock.FileLock(lock_path) with lock.acquire(timeout=timeout): yield
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def home_slug(): """ Returns the slug arg defined for the ``home`` urlpattern, which is the definitive source of the ``url`` field defined for an editable homepa...
prefix = get_script_prefix() slug = reverse("home") if slug.startswith(prefix): slug = '/' + slug[len(prefix):] try: return resolve(slug).kwargs["slug"] except KeyError: return slug