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 row_idx not in self._row_memo: self._row_memo[row_idx] = [ row[k] if k in row else self._default_value for k in self._column_name_list ] return self._row_memo[row_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 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 including ones which are the default value """
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_name_list[idx], v) for idx, v in enumerate(row) if v != self._default_value) return self._row_memo[row_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 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 FVM rotated from self """
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(self._row_name_list) for idx, r in enumerate(self.get_matrix().transpose()): fvm.add_row(r.tolist(), self._column_name_list[idx]) return fvm
<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(key)
<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 function. :param preprocess: :param string: :return: """
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)), Image.ANTIALIAS) else: img = Image.new('RGB', (WIDTH, HEIGHT), 'black') image = self.add_caption(img, caption) image = img 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 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('caller is not a file') return Path(filename)
<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) if not module: raise RuntimeError('caller is not a module') root_module_name = module.__name__.partition('.')[0] fullpath = sys.modules[root_module_name].__file__ return Path(fullpath)
<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 http_request: U{HTTPRequest<http://docs.djangoproject.com /en/dev/ref/request-response/#httprequest-objects>} @param request: The AMF Request. @type request: L{Envelope<pyamf.remoting.Envelope>} @rtype: L{Envelope<pyamf.remoting.Envelope>} """
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`` to a Parker Motion Gemini GV-6 or GT-6 servo/stepper motor drive. The only driver currently supported is the ``'ASCII_RS232'`` driver which corresponds to ``drivers.ASCII_RS232``. Parameters driver : str, optional The driver to communicate to the particular driver with, which includes the hardware connection and possibly the communications protocol. The only driver currently supported is the ``'ASCII_RS232'`` driver which corresponds to ``drivers.ASCII_RS232``. *args : additional positional arguments Additional positional arguments to pass onto the constructor for the driver. **keywords : additional keyword arguments Additional keyword arguments to pass onto the constructor for the driver. Returns ------- drivers : drivers The connected drivers class that is connected to the drive. Raises ------ NotImplementedError If the `driver` is not supported. See Also -------- drivers drivers.ASCII_RS232 """
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``, ``int``, and ``float`` parameters. Parameters name : str Name of the parameter to check. It is always the command to set it but without the value. tp : type {bool, int, float} The type of the parameter. timeout : number, optional Optional timeout in seconds to use when reading the response. A negative value or ``None`` indicates that the an infinite timeout should be used. max_retries : int, optional Maximum number of retries to do per command in the case of errors. Returns ------- value : bool, int, or float The value of the specified parameter. Raises ------ TypeError If 'tp' is not an allowed type (``bool``, ``int``, ``float``). CommandError If the command to retrieve the parameter returned an error. ValueError If the value returned to the drive cannot be converted to the proper type. See Also -------- _set_parameter : Set a parameter. """
# 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 name preceeded by an '*' and # then followed by a number which will have to be converted. response = self.driver.send_command(name, timeout=timeout, immediate=True, max_retries=max_retries) # If the response has an error, there are no response lines, or # the first response line isn't '*'+name; then there was an # error and an exception needs to be thrown. if self.driver.command_error(response) \ or len(response[4]) == 0 \ or not response[4][0].startswith('*' + name): raise CommandError('Couldn''t retrieve parameter ' + name) # Extract the string representation of the value, which is after # the '*'+name. value_str = response[4][0][(len(name)+1):] # Convert the value string to the appropriate type and return # it. Throw an error if it is not supported. if tp == bool: return (value_str == '1') elif tp == int: return int(value_str) elif tp == float: return float(value_str)
<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 ``bool``, ``int``, and ``float`` parameters. Parameters name : str Name of the parameter to set. It is always the command to set it when followed by the value. value : bool, int, or float Value to set the parameter to. tp : type {bool, int, float} The type of the parameter. timeout : number, optional Optional timeout in seconds to use when reading the response. A negative value or ``None`` indicates that the an infinite timeout should be used. max_retries : int, optional Maximum number of retries to do per command in the case of errors. Returns ------- success : bool Whether the last attempt to set the parameter was successful (``True``) or not (``False`` meaning it had an error). See Also -------- _get_parameter : Get a parameter. """
# 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 bools need to be a # '1' or a '0', it must be converted to int before going through # str. if tp == bool: value_str = str(int(bool(value))) elif tp == int: value_str = str(int(value)) elif tp == float: value_str = str(float(value)) # Immediately set the named parameter of the drive. The command # is just the parameter name followed by the value string. response = self.driver.send_command(name+value_str, \ timeout=timeout, immediate=True, max_retries=max_retries) # Return whether the setting was successful or not. return not self.driver.command_error(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_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 : int Which program to get. timeout : number, optional Optional timeout in seconds to use when reading the response. A negative value or ``None`` indicates that the an infinite timeout should be used. max_retries : int, optional Maximum number of retries to do per command in the case of errors. Returns ------- commands : list of str ``list`` of ``str`` commands making up the program. The trailing 'END' is removed. Empty if there was an error. Notes ----- The command sent to the drive is '!TPROG PROGn'. See Also -------- set_program_profile : Sets a program or profile. run_program_profile : Runs a program or profile. """
# 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 lines but strip the leading '*' first and the # 'END' at the end of the list. if self.driver.command_error(response) \ or len(response[4]) == 0: return [] else: if '*END' in response[4]: response[4].remove('*END') return [line[1:] for line in response[4]]
<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 (int) - Offset to the fixup array fx_count (int) - Number of elements in the fixup array entry_size (int) - Size of the MFT entry ''' fx_array = bin_view[fx_offset:fx_offset+(2 * fx_count)] #the array is composed of the signature + substitutions, so fix that fx_len = fx_count - 1 #we can infer the sector size based on the entry size sector_size = int(entry_size / fx_len) index = 1 position = (sector_size * index) - 2 while (position <= entry_size): if bin_view[position:position+2].tobytes() == fx_array[:2].tobytes(): #the replaced part must always match the signature! bin_view[position:position+2] = fx_array[index * 2:(index * 2) + 2] else: _MOD_LOGGER.error("Error applying the fixup array") raise FixUpError(f"Signature {fx_array[:2].tobytes()} does not match {bin_view[position:position+2].tobytes()} at offset {position}.") index += 1 position = (sector_size * index) - 2 _MOD_LOGGER.info("Fix up array applied successfully.")
<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() file_object.seek(0, 2) file_size = file_object.tell() file_object.seek(position, 0) return file_size
<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 return func if callable(value): return wrapper(value) return wrapper
<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 return func if callable(value): return wrapper(value) return wrapper
<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 true or false if the event could be handled here default code is given for this method, however subclasses must still override this method to insure the subclass has the correct behavior. """
# 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 not v(getattr(event, k, v)): break else: h.call_actions(event) if self._logger is not None: self._logger.debug("Handle event: {}.".format(event)) return True 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 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 ETC). actions - The methods which should be called when an event matching this specification is received. more than one action can be tied to a single event. This allows for secondary actions to occur along side already existing actions such as the down errow in the List. You can either pass the actions or action as a single parameter or as a list. kwargs - An arbitrary number of parameters which must be satisfied in order for the event to match. The keywords are directly matched with the instance variables found in the current event Each value for kwargs can optionally be a lambda which must evaluate to True in order for the match to work. Example: session.add_handler(pygame.QUIT, session.do_quit) session.add_handler(pygame.KEYDOWN, lambda: ao2.speak("You pressed the enter key."), key = pygame.K_RETURN) """
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, False otherwise. """
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 kwargs to be passed to self.add_handler. See the documentation for self.add_handler for examples. """
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 slightly different behavior, such as reasigning keys. handler - the handler object that the desired changes are made to. kwargs - the variable number of keyword arguments for the parameters that must match the properties of the corresponding event. """
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) self.event = handler.event
<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 different behavior, such as reasigning keys. handler - the handler object that the desired changes are made to. actions - The methods that are called when this handler is varified against the current event. """
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) self.event = handler.event
<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().C = 'US' cert.get_subject().ST = 'California' cert.get_subject().L = 'Los Angeles' cert.get_subject().O = 'Wright Anything Agency' cert.get_subject().OU = 'Law firm / talent agency' cert.get_subject().CN = '*.{dn}'.format(dn=self.site.domain.name) # Set the serial number, expiration and issued cert.set_serial_number(1000) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(315360000) cert.set_issuer(cert.get_subject()) # Map the key and sign our certificate cert.set_pubkey(key) cert.sign(key, digest) # Dump the PEM data and return a certificate container _cert = crypto.dump_certificate(crypto.FILETYPE_PEM, cert) _key = crypto.dump_privatekey(crypto.FILETYPE_PEM, key) return Certificate(_cert, _key, type, bits, digest)
<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 None, or is blank (all spaces) None is returned. If max_length > 0 and the stripped val is greater than max_length, val[:max_length] is returned. """
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 files will be collected from directory named 'static' under passed application:: ./blog/static/ This example is with an application named `blog`. URLs for static files in static directory will begin with /static/app_name/. so in blog app case, if the directory has css/main.css file, the file will be published like this:: yoursite.com/static/blog/css/main.css And you can get this URL by reversing form matching object:: matching.reverse('blog:static', path=['css', 'main.css']) """
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__}:static'.format(app=app) return Matching(static_pattern, static_app, static_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 be zero and the result is returned as a scalar. """
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(self.x, digits) self.y = round(self.y, 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 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 between 0 and 1. """
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: container to update :type toml_obj: tomlkit.container.Containers :param not_set: random UUID used to denote a value that has no default :type not_set: str """
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 metrics, estimates, parameters, etc. of the model (see "func") for each subsample. It is a <C x M> matrix, i.e. C=binocoeff(N,d) subsamples, and M parameters that are returned by the model. theta_full : ndarray The metrics, estimates, parameters, etc. of the model (see "func") for the full sample. It is a <1 x M> vecotr with the M parameters that are returned by the model. N : int The number of observations in the full sample. Is required for Delete-d Jackknife, i.e. d>1. (Default is N=None) d : int The number of observations to leave out for each Jackknife subsample, i.e. the subsample size is N-d. (The default is d=1 for the "Delete-1 Jackknife" procedure.) Returns: -------- pvalues : ndarray The two-sided P-values of the t-Score for each Jackknife estimate. (In Social Sciences pval<0.05 is referred as acceptable but it is usually better to look for p-values way closer to Zero. Just remove or replace a variable/feature with high pval>=pcritical and run the Jackknife again.) tscores : ndarray The t-Score for each Jackknife estimate. (As rule of thumb a value abs(tscore)>2 indicates a bad model parameter but jsut check the p-value.) theta_jack : ndarray The bias-corrected Jackknife Estimates (model parameter, metric, coefficient, etc.). Use the parameters for prediction. se_jack : ndarray The Jackknife Standard Error theta_biased : ndarray The biased Jackknife Estimate. Other Variables: These variables occur in the source code as intermediate results. Q : int The Number of independent variables of a model (incl. intercept). C : int The number of Jackknife subsamples if d>1. There are C=binocoeff(N,d) combinations. """
# 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: raise Exception(( "If d>1 then you must provide N (number of " "observations in the full sample)")) C = theta_subs.shape[0] inflation = ((N - d) / d) / C # The Jackknife Standard Error se_jack = np.sqrt( inflation * np.sum((theta_subs - theta_biased)**2, axis=0)) # The bias-corrected Jackknife Estimate theta_jack = N * theta_full - (N - 1) * theta_biased # The Jackknife t-Statistics tscores = theta_jack / se_jack # Two-sided P-values import scipy.stats Q = theta_subs.shape[1] pvalues = scipy.stats.t.sf(np.abs(tscores), N - Q - d) * 2 # done return pvalues, tscores, theta_jack, se_jack, theta_biased
<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 Other BS Text LLC' """
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 True reading = type(stack[-1]) self.sexp_string.write(c) if reading == tuple: if c in atom_end: atom = stack.pop() stack[-1].append(atom) reading = type(stack[-1]) if reading == list: if c == '(': stack.append([]) elif c == ')': stack[-2].append(stack.pop()) elif c == '"': stack.append('') elif c == "'": continue elif c in whitespace: continue else: stack.append(tuple()) elif reading == str: if c == '"': stack.pop() # escaped char coming up, so read ahead elif c == '\\': self.sexp_string.write(stream.read(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 name_to_vector(name): """ Convert `name` to the ASCII vector. Example: ['putsalek', 'franta', 'ing'] Args: name (str): Name which will be vectorized. Returns: list: Vector created from name. """
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 (str): Fisst name as string. second (str): Second name as string. Returns: float: Percentage of the similarity. """
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. Returns: obj/None: None if the publication was found in Aleph or `publication` \ if not. """
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.reactToAMQPMessage(aleph.SearchRequest(query), "") if not result.records: return publication # book is not in database # if there was results with this ISBN, compare titles of the books # (sometimes, there are different books with same ISBN because of human # errors) if isbn_query: for record in result.records: epub = record.epublication # try to match title of the book if compare_names(epub.nazev, publication.title) >= 80: return None # book already in database return publication # checks whether the details from returned EPublication match Publication's for record in result.records: epub = record.epublication # if the title doens't match, go to next record from aleph if not compare_names(epub.nazev, publication.title) >= 80: continue if not cmp_authors: return None # book already in database # compare authors names for author in epub.autori: # convert Aleph's author structure to string author_str = "%s %s %s" % ( author.firstName, author.lastName, author.title ) # normalize author data from `publication` pub_authors = map(lambda x: x.name, publication.authors) if type(pub_authors) not in [list, tuple, set]: pub_authors = [pub_authors] # try to compare authors from `publication` and Aleph for pub_author in pub_authors: if compare_names(author_str, pub_author) >= 50: return None # book already in database return publication
<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 string. :param next: The next string begin index. If None, the string index will not be updated. """
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 actual character that was escaped. """
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) # Append the conversion to the format self.fmt.append_conv(self.fmt._get_conversion(name, self.modifier)) # Clear the conversion data self.param_begin = None self.conv_begin = None self.modifier = None 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 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 remaining characters of the code. :param idx: The index at which the code _begins_. :returns: True if the code is valid, False otherwise. """
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.fmt.append_text(self.format[self.str_begin:]) # Convenience return return self.fmt
<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 begins. """
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 AddressConversion, etc. :param modifier: The format modifier applied to this conversion. :returns: An instance of bark.conversions.Conversion. """
# 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 cls._conversion_cache[conv_chr] = ep.load() break except (ImportError, pkg_resources.UnknownExtra): # Couldn't load it; odd... continue else: # Cache the negative result cls._conversion_cache[conv_chr] = None # Handle negative caching if cls._conversion_cache[conv_chr] is None: return conversions.StringConversion("(Unknown conversion '%%%s')" % conv_chr) # Instantiate the conversion return cls._conversion_cache[conv_chr](conv_chr, modifier)
<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 class Format. """
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): # Some characters get ignored if state.check_ignore(): continue if state == 'string': if char == '%': # Handle '%%' if format[idx:idx + 2] == '%%': # Add one % to the string context state.add_text(idx + 1, idx + 2) state.set_ignore(1) else: state.add_text(idx) state.conversion(idx) elif char == '\\': state.add_text(idx) state.escape(idx) elif state == 'escape': state.add_escape(idx + 1, char) state.pop_state(idx + 1) elif state == 'param': if char == '}': state.set_param(idx) state.pop_state() elif state == 'conv': if char == ')': state.set_conversion(idx) state.pop_state() # now in 'conversion' state.pop_state(idx + 1) # now in 'string' else: # state == 'conversion' if char in '<>': # Allowed for Apache compatibility, but ignored continue elif char == '!': state.set_reject() continue elif char == ',' and state.code_last: # Syntactically allowed ',' continue elif char.isdigit(): # True if the code is valid if state.set_code(idx): continue elif char == '{' and state.param_begin is None: state.param(idx + 1) continue elif char == '(' and state.conv_begin is None: state.conv(idx + 1) continue # OK, we have a complete conversion state.set_conversion(idx) state.pop_state(idx + 1) # Finish the parse and return the completed format return state.end_state()
<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 list of dictionary values needed by the convert() method. """
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: The webob Response object describing the response. :param data: The data dictionary list returned by the prepare() method. :returns: A string, the results of which are the desired conversion. """
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('-') return ''.join(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 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: valid_tags = None invalid = True break except (KeyError, TypeError) as e: # object is either missing the key or is not a dictionary type invalid = True break if debug: print name, not invalid and valid_tags is not None return not invalid and valid_tags 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 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( 'slug', css_class='small-12 medium-10' ), Column( 'order', css_class='small-12 medium-2' ), ), Row( Column( 'description', css_class='small-12' ), ), Row( Column( 'visible', css_class='small-12' ), ), ButtonHolderPanel( Submit('submit', _('Submit')), css_class='text-right', ), ) return helper
<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 if edit_mode: fieldsets.append( Row( Column( 'category', css_class='small-12' ), ), ) if for_moderator: fieldsets.append( Row( Column( 'sticky', css_class='small-12 medium-4' ), Column( 'announce', css_class='small-12 medium-4' ), Column( 'closed', css_class='small-12 medium-4' ), ), ) # First message is not in edit form if not edit_mode: fieldsets.append( Row( Column( 'text', css_class='small-12' ), ), ) if for_moderator: fieldsets.append( Row( Column( 'visible', css_class='small-12' ), ), ) # Threadwatch option is not in edit form if not edit_mode: fieldsets.append( Row( Column( 'threadwatch', css_class='small-12' ), ), ) fieldsets = fieldsets+[ ButtonHolderPanel( Submit('submit', _('Submit')), css_class='text-right', ), ] helper.layout = Layout(*fieldsets) return helper
<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 form if not edit_mode: fieldsets.append( Row( Column( 'threadwatch', css_class='small-12' ), ), ) fieldsets = fieldsets+[ ButtonHolderPanel( Submit('submit', _('Submit')), css_class='text-right', ), ] helper.layout = Layout(*fieldsets) return helper
<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' ), Column( Submit('submit', _('Submit')), css_class='small-12 medium-4 text-right' ), ), ), ) return helper
<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 are used as a callback to a chord or in link_error and is really just a hack to get around https://github.com/celery/celery/issues/2137 Usage: .. code-block:: python class Foo(models.Model): def __init__(self): self.bar = 1 @task def first(self): pass @task @ensure_self def last(self, results=None): print self.bar Then the following is performed: .. code-block:: python f = Foo() (f.first.s() | f.last.s(this=f)).apply_async() # prints 1 The important part here is that 'this' is passed into the last.s subtask. Hopefully issue 2137 is recognized as an issue and fixed and this hack is no longer required. """
@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, **kwargs) except KeyError: # 'this' wasn't passed, all we can do is assume normal innovation return func(*args, **kwargs) return inner
<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 input parameters. :param source: source object to process with fn. :param dict _globals: global objects by name. :param dict _locals: local objects by name. :return: fn processing result"""
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 intcode: list of byte code to use. :param newcodeobj: new code object with empty body. :param oldcodeobj: old code object. :return: new code object to produce."""
# 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), newcodeobj.co_names, newcodeobj.co_varnames, newcodeobj.co_filename, newcodeobj.co_name, newcodeobj.co_firstlineno, newcodeobj.co_lnotab, oldcodeobj.co_freevars, newcodeobj.co_cellvars ] if PY3: vargs.insert(1, newcodeobj.co_kwonlyargcount) # instanciate a new newcodeobj object result = type(newcodeobj)(*vargs) 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 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 line of the module (after everything is defined, but before test code). In modules that need modifiable globals, set builtin_only to True. :param morc: module or class to transform. :param bool builtin_only: only transform builtin objects. :param list stoplist: attribute names to not transform. :param function verbose: logger function which takes in parameter a message """
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 list(vars(morc).items()): if isinstance(val, FunctionType): newv = _make_constants( val, builtin_only, stoplist, verbose ) setattr(morc, k, newv) elif isinstance(val, type): _bind_all(val, builtin_only, stoplist, verbose) if isinstance(morc, dict): # allow: bind_all(globals()) for k, val in list(morc.items()): if isinstance(val, FunctionType): newv = _make_constants(val, builtin_only, stoplist, verbose) morc[k] = newv elif isinstance(val, type): _bind_all(val, builtin_only, stoplist, verbose) else: _bind_all(morc, 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 make_constants(builtin_only=False, stoplist=None, verbose=None): """Return a decorator for optimizing global references. Replaces global references with their currently defined values. If not defined, the dynamic (runtime) global lookup is left undisturbed. If builtin_only is True, then only builtins are optimized. Variable names in the stoplist are also left undisturbed. Also, folds constant attr lookups and tuples of constants. If verbose is True, prints each substitution as is occurs. :param bool builtin_only: only transform builtin objects. :param list stoplist: attribute names to not transform. :param function verbose: logger function which takes in parameter a message """
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 (easyci.vcs.base.Vcs) lock_object (Lock) wait (boolean) - whether to wait for the lock or error out Raises: Timeout """
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 homepage object. """
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