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 _parse(template): """Parse a top-level template string Expression. Any extraneous text is considered literal text. """
parser = Parser(template) parser.parse_expression() parts = parser.parts remainder = parser.string[parser.pos:] if remainder: parts.append(remainder) return Expression(parts)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evaluate(self, env): """Evaluate the symbol in the environment, returning a Unicode string. """
if self.ident in env.values: # Substitute for a value. return env.values[self.ident] else: # Keep original text. return self.original
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translate(self): """Compile the variable lookup."""
ident = self.ident expr = ex_rvalue(VARIABLE_PREFIX + ident) return [expr], set([ident]), 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 evaluate(self, env): """Evaluate the function call in the environment, returning a Unicode string. """
if self.ident in env.functions: arg_vals = [expr.evaluate(env) for expr in self.args] try: out = env.functions[self.ident](*arg_vals) except Exception as exc: # Function raised exception! Maybe inlining the name of # the except...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translate(self): """Compile the function call."""
varnames = set() ident = self.ident funcnames = set([ident]) arg_exprs = [] for arg in self.args: subexprs, subvars, subfuncs = arg.translate() varnames.update(subvars) funcnames.update(subfuncs) # Create a subexpression that joi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evaluate(self, env): """Evaluate the entire expression in the environment, returning a Unicode string. """
out = [] for part in self.parts: if isinstance(part, str): out.append(part) else: out.append(part.evaluate(env)) return u''.join(map(str, out))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translate(self): """Compile the expression to a list of Python AST expressions, a set of variable names used, and a set of function names. """
expressions = [] varnames = set() funcnames = set() for part in self.parts: if isinstance(part, str): expressions.append(ex_literal(part)) else: e, v, f = part.translate() expressions.extend(e) varna...
<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_argument_list(self): """Parse a list of arguments starting at ``pos``, returning a list of Expression objects. Does not modify ``parts``. Should leave ...
# Try to parse a subexpression in a subparser. expressions = [] while self.pos < len(self.string): subparser = Parser(self.string[self.pos:], in_argument=True) subparser.parse_expression() # Extract and advance past the parsed expression. expres...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def substitute(self, values={}, functions={}): """Evaluate the template given the values and functions. """
try: res = self.compiled(values, functions) except Exception: # Handle any exceptions thrown by compiled version. res = self.interpret(values, functions) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translate(self): """Compile the template to a Python function."""
expressions, varnames, funcnames = self.expr.translate() argnames = [] for varname in varnames: argnames.append(VARIABLE_PREFIX + varname) for funcname in funcnames: argnames.append(FUNCTION_PREFIX + funcname) func = compile_func( argnames, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def uri_from_parts(parts): "simple function to merge three parts into an uri" uri = "%s://%s%s" % (parts[0], parts[1], parts[2]) if parts[3]: extra = '?'+urlencode(parts[3]) uri += extra return uri
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def as_list(self): "return some attributes as a list" netloc = '' if self.vpath_connector: netloc = '(('+self.vpath_connector+'))' elif self.authority: netloc = self.authority else: netloc = self.netloc return [ self.scheme,...
<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_print(value, space = True, tab = False, crlf = False): """ Returns True if is print or False otherwise """
if not isinstance(value, basestring): return False regex = r'\x00-\x08\x0B\x0C\x0E-\x1F\x7F' if not space: regex += r'\x20' if tab: regex += r'\x09' if crlf: regex += r'\x0A\x0D' return re.match(r'[' + regex + ']', value, re.U) is 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 file_writelines_flush_sync(path, lines): """ Fill file at @path with @lines then flush all buffers (Python and system buffers) """
fp = open(path, 'w') try: fp.writelines(lines) flush_sync_file_object(fp) finally: fp.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def file_w_create_directories(filepath): """ Recursively create some directories if needed so that the directory where @filepath must be written exists, then ope...
dirname = os.path.dirname(filepath) if dirname and dirname != os.path.curdir and not os.path.isdir(dirname): os.makedirs(dirname) return open(filepath, 'w')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_transaction_status(self, transaction_id): """ Get the transaction current status. :param transaction_id: :return: """
url = "%s%s%s/status" % (self.api_endpoint, constants.TRANSACTION_STATUS_ENDPOINT, transaction_id) username = self.base.get_username() password = self.base.get_password(username=username, request_url=url) response = requests.get(url, auth=HTTPBasicAuth(username=username, password=pass...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def capture_sale(self, transaction_id, capture_amount, message=None): """ Capture existing preauth. :param transaction_id: :param capture_amount: :param message:...
request_data = { "amount": self.base.convert_decimal_to_hundreds(capture_amount), "currency": self.currency, "message": message } url = "%s%s%s/capture" % (self.api_endpoint, constants.TRANSACTION_STATUS_ENDPOINT, transaction_id) username = self.bas...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def caller_folder(): """ Returns the folder where the code of the caller's caller lives """
import inspect caller_file = inspect.stack()[2][1] if os.path.exists(caller_file): return os.path.abspath(os.path.dirname(caller_file)) else: return os.path.abspath(os.getcwd())
<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_dict(self): """ Response as dict :return: response :rtype: dict """
cache_info = None if self.cache_info: cache_info = self.cache_info.to_dict() return { 'cache_info': cache_info, 'html': self.html, 'scraped': self.scraped, 'raw': self.raw }
<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_dict(d): """ Response from dict :param d: Dict to load :type d: dict :return: response :rtype: Response """
if d is None: return None return Response( d.get('html'), CacheInfo.from_dict(d.get('cache_info')), d.get('scraped'), d.get('raw') )
<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_board_image_cv(self, board=None): """Return a cv image of the board or empty board if not provided."""
board = board or base.Board() # empty board by default tile_h, tile_w = self._TILE_SHAPE[0:2] board_shape = tile_h * 8, tile_w * 8, 3 board_image = numpy.zeros(board_shape, dtype=numpy.uint8) # place each tile on the image for (row, col), tile in board.positions_with_ti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _draw_swap_cv(self, board_image, swap): """Add a white tile border to indicate the swap."""
tile_h, tile_w = self._TILE_SHAPE[0:2] # get a single bounding box (row_1, col_1), (row_2, col_2) = swap t = tile_h * min(row_1, row_2) b = tile_h * (1 + max(row_1, row_2)) l = tile_w * min(col_1, col_2) r = tile_w * (1 + max(col_1, col_2)) top_left = (l,...
<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_cv_to_tk(self, image_cv): """Convert an OpenCV image to a tkinter PhotoImage"""
# convert BGR to RGB image_cv_rgb = data.cv2.cvtColor(image_cv, data.cv2.COLOR_BGR2RGB) # convert opencv to PIL image_pil = PIL_Image.fromarray(image_cv_rgb) # convert PIL to tkinter return ImageTk.PhotoImage(image_pil)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _scheduled_check_for_summaries(self): """Present the results if they have become available or timed out."""
if self._analysis_process is None: return # handle time out timed_out = time.time() - self._analyze_start_time > self.time_limit if timed_out: self._handle_results('Analysis timed out but managed\n' ' to get lower turn results.', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _next(self): """Get the next summary and present it."""
self.summaries.rotate(-1) current_summary = self.summaries[0] self._update_summary(current_summary)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _previous(self): """Get the previous summary and present it."""
self.summaries.rotate() current_summary = self.summaries[0] self._update_summary(current_summary)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_notification(self, message=None): """Update the message area with blank or a message."""
if message is None: message = '' message_label = self._parts['notification label'] message_label.config(text=message) self._base.update()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_summary(self, summary=None): """Update all parts of the summary or clear when no summary."""
board_image_label = self._parts['board image label'] # get content for update or use blanks when no summary if summary: # make a board image with the swap drawn on it # board, action, text = summary.board, summary.action, summary.text board_image_cv = self._c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(self): """Issue the request. Uses httplib2.Http support for handling redirects. Returns an httplib2.Response, which may be augmented by the proc_respons...
# Pre-process the request try: self.procstack.proc_request(self) except exc.ShortCircuit, e: self._debug("Request pre-processing short-circuited") # Short-circuited; we have an (already processed) response return e.response self._debug(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def proc_response(self, resp): """Process response hook. Process non-redirect responses received by the send() method. May augment the response. The default impl...
# Raise exceptions for error responses if resp.status >= 400: e = exc.exception_map.get(resp.status, exc.HTTPException) self._debug(" Response was a %d fault, raising %s", resp.status, e.__name__) raise e(resp)
<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_arguments(self): """ Add the label argument by default, no need to specify it in args. """
super(LabelCommand, self).add_arguments() self.parser.add_argument('labels', metavar=self.label, nargs="+")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _comparator(func): """ Decorator for EnumValue rich comparison methods. """
def comparator_wrapper(self, other): try: # [PATCH] The code was originally the following: # # assert self.enumtype == other.enumtype # result = func(self.index, other.index) # # which first statement causes an issue when seria...
<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(self, *keys, **kwargs): """ Return a new enumeration object extended with the specified items. """
this = copy.deepcopy(self) value_type = kwargs.get('value_type', EnumValue) if not keys: raise EnumEmptyError() keys = tuple(keys) values = [None] * len(keys) for i, key in enumerate(keys): value = value_type(this, i, key) values[i...
<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_preview(preview): ''' Verifies that the preview is a valid filetype ''' if not preview: return False if mimetype(preview) not in [ExportMimeType.PNG, ExportMimeType.PDF]: 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 options(self, data): """Generate folders to best match metadata. The results will be a single, perfectly matched folder, or the two nearest neighbours of an ...
if self.mapping_key(data) in self.keys: yield next(i for i in self.folders if i.metadata == data) else: index = bisect.bisect_left(self.keys, self.mapping_key(data)) posns = sorted(set([max(0, index - 1), index])) yield from (self.folders[i] for i in posn...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def widget_for(element): """Create a widget for a schema item """
view_type = _view_type_for_element(element) if view_type is None: raise KeyError('No view type for %r' % element) builder = view_widgets.get(view_type) if builder is None: raise KeyError('No widget type for %r' % view_type) return builder(element)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def projection(radius=5e-6, sphere_index=1.339, medium_index=1.333, wavelength=550e-9, pixel_size=1e-7, grid_size=(80, 80), center=(39.5, 39.5)): """Optical path...
# grid x = np.arange(grid_size[0]).reshape(-1, 1) y = np.arange(grid_size[1]).reshape(1, -1) cx, cy = center # sphere location rpx = radius / pixel_size r = rpx**2 - (x - cx)**2 - (y - cy)**2 # distance z = np.zeros_like(r) rvalid = r > 0 z[rvalid] = 2 * np.sqrt(r[rvalid]) *...
<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_first_builder_window(builder): """Get the first toplevel widget in a gtk.Builder hierarchy. This is mostly used for guessing purposes, and an explicit na...
for obj in builder.get_objects(): if isinstance(obj, gtk.Window): # first window return obj
<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_builder_toplevel(self, builder): """Get the toplevel widget from a gtk.Builder file. The main view implementation first searches for the widget named as ...
toplevel = builder.get_object(self.toplevel_name) if not gobject.type_is_a(toplevel, gtk.Window): toplevel = None if toplevel is None: toplevel = get_first_builder_window(builder) return toplevel
<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_bytes(s, encoding=None, errors='strict'): """Convert string to bytes."""
encoding = encoding or 'utf-8' if is_unicode(s): return s.encode(encoding, errors) elif is_strlike(s): return s else: if six.PY2: return str(s) else: return str(s).encode(encoding, errors)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unicode_left(s, width): """Cut unicode string from left to fit a given width."""
i = 0 j = 0 for ch in s: j += __unicode_width_mapping[east_asian_width(ch)] if width < j: break i += 1 return s[:i]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unicode_right(s, width): """Cut unicode string from right to fit a given width."""
i = len(s) j = 0 for ch in reversed(s): j += __unicode_width_mapping[east_asian_width(ch)] if width < j: break i -= 1 return s[i:]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def schema_factory(schema_name, **schema_nodes): """Schema Validation class factory. Args: schema_name(str): The namespace of the schema. schema_nodes(dict): T...
schema_dict = dict() schema_dict.update(schema_nodes) def cls_repr(self): # pragma: no cover return "<{} instance at: 0x{:x}>".format(self.__class__, id(self)) def cls_str(self): # pragma: no cover return "<{} instance, attributes:{}>".format( self.__class__.__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 serialize(self, *fields): """Serialize Nodes and attributes """
if fields: if not set(fields).issubset(self.data_nodes): raise SchemaError('Invalid field for serialization: {}'.format(set(fields).difference(self.data_nodes))) return OrderedDict([(k, getattr(self, k)) for k in fields]) return OrderedDict([(k, getattr(self, 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 setup_logger(debug, color): """Configure the logger."""
if debug: log_level = logging.DEBUG else: log_level = logging.INFO logger = logging.getLogger('exifread') stream = Handler(log_level, debug, color) logger.addHandler(stream) logger.setLevel(log_level)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sanitize(configuration, error_fn): """ Run all availalbe sanitizers across a configuration. Arguments: configuration - a full project configuration error_fn ...
for name, sanitize_fn in _SANITIZERS.items(): sanitize_fn(configuration, lambda warning, n=name: error_fn(n, warning))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def s2n(self, offset, length, signed=0): """ Convert slice to integer, based on sign and endian flags. Usually this offset is assumed to be relative to the begin...
self.file.seek(self.offset + offset) sliced = self.file.read(length) if self.endian == 'I': val = s2n_intel(sliced) else: val = s2n_motorola(sliced) # Sign extension? if signed: msb = 1 << (8 * length - 1) if val & msb:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def n2s(self, offset, length): """Convert offset to string."""
s = '' for dummy in range(length): if self.endian == 'I': s += chr(offset & 0xFF) else: s = chr(offset & 0xFF) + s offset = offset >> 8 return 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 _next_ifd(self, ifd): """Return the pointer to next IFD."""
entries = self.s2n(ifd, 2) next_ifd = self.s2n(ifd + 2 + 12 * entries, 4) if next_ifd == ifd: return 0 else: return next_ifd
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_ifd(self): """Return the list of IFDs in the header."""
i = self._first_ifd() ifds = [] while i: ifds.append(i) i = self._next_ifd(i) return ifds
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_tiff_thumbnail(self, thumb_ifd): """ Extract uncompressed TIFF thumbnail. Take advantage of the pre-existing layout in the thumbnail IFD as much as p...
thumb = self.tags.get('Thumbnail Compression') if not thumb or thumb.printable != 'Uncompressed TIFF': return entries = self.s2n(thumb_ifd, 2) # this is header plus offset to IFD ... if self.endian == 'M': tiff = 'MM\x00*\x00\x00\x00\x08' 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 extract_jpeg_thumbnail(self): """ Extract JPEG thumbnail. (Thankfully the JPEG data is stored as a unit.) """
thumb_offset = self.tags.get('Thumbnail JPEGInterchangeFormat') if thumb_offset: self.file.seek(self.offset + thumb_offset.values[0]) size = self.tags['Thumbnail JPEGInterchangeFormatLength'].values[0] self.tags['JPEGThumbnail'] = self.file.read(size) # Some...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _canon_decode_tag(self, value, mn_tags): """ Decode Canon MakerNote tag based on offset within tag. See http://www.burren.cx/david/canon.html by David Burren...
for i in range(1, len(value)): tag = mn_tags.get(i, ('Unknown', )) name = tag[0] if len(tag) > 1: val = tag[1].get(value[i], 'Unknown') else: val = value[i] try: logger.debug(" %s %s %s", i, name, hex(va...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _canon_decode_camera_info(self, camera_info_tag): """ Decode the variable length encoded camera info section. """
model = self.tags.get('Image Model', None) if not model: return model = str(model.values) camera_info_tags = None for (model_name_re, tag_desc) in makernote.canon.CAMERA_INFO_MODEL_MAP.items(): if re.search(model_name_re, model): camera_i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def on_widget__configure_event(self, widget, event): ''' Called when size of drawing area changes. ''' if event.x < 0 and event.y < 0: # Widget has not been allocated a size yet, so do nothing. return self.resize(event.width, event.height)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def render_label(self, cairo_context, shape_id, text=None, label_scale=.9): ''' Draw label on specified shape. Parameters ---------- cairo_context : cairo.Context Cairo context to draw text width. Can be preconfigured, for example, to set font style, etc...
<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_ui(self): """Create the user interface create_ui is a method called during the Delegate's initialisation process, to create, add to, or modify any UI ...
self.entry = gtk.Entry() self.widget.add(self.entry)
<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_hash(file_path, block_size=1024, hasher=None): """ Generate hash for given file :param file_path: Path to file :type file_path: str :param block_siz...
if hasher is None: hasher = hashlib.md5() with open(file_path, 'rb') as f: while True: buffer = f.read(block_size) if len(buffer) <= 0: break hasher.update(buffer) return hasher.hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resource_get_list(self): """ Get list of this plugins resources and a hash to check for file changes (It is recommended to keep a in memory representation of...
if not self._resources: return self.resource_update_list() res = [] with self._resource_lock: for key in self._resources: res.append((key, self._resources[key]['hash'])) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resource_update_list(self, reset=False): """ Update internal struct of resource, hash list and get diff (Warning: Resource names have to be unique!!) :param ...
if not self._resource_path: raise PluginException("No resource path set") if not os.path.isdir(self._resource_path): raise PluginException( u"Resource path directory '{}' not found".format( self._resource_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 resource_get(self, resource_name): """ Return resource info :param resource_name: Resource name as returned by resource_get_list() :type resource_name: str :...
try: with self._resource_lock: res = self._resources[resource_name] except KeyError: return {} return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def special_mode(v): """decode Olympus SpecialMode tag in MakerNote"""
mode1 = { 0: 'Normal', 1: 'Unknown', 2: 'Fast', 3: 'Panorama', } mode2 = { 0: 'Non-panoramic', 1: 'Left to right', 2: 'Right to left', 3: 'Bottom to top', 4: 'Top to bottom', } if not v or (v[0] not in mode1 or v[2] not in mode...
<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_call(obj, methname, *args, **kwargs): """ Safely calls the method with the given methname on the given object. Remaining positional and keyword argumen...
meth = getattr(obj, methname, None) if meth is None or not callable(meth): return return meth(*args, **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 proc_response(self, resp, startidx=None): """ Post-process a response through all processors in the stack, in reverse order. For convenience, returns the res...
# If we're empty, bail out early if not self: return resp # Select appropriate starting index if startidx is None: startidx = len(self) for idx in range(startidx, -1, -1): _safe_call(self[idx], 'proc_response', resp) # Return the 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 find_config(): """Find a build cache somewhere in a parent directory."""
previous = "" current = os.getcwd() while previous != current: check_path = os.path.join(current, "build.cache") if os.path.isfile(check_path): return check_path else: previous = current current = os.path.dirname(current) raise Exception("Can'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_cache(force=False, cache_file=None): """ Load a build cache, updating it if necessary. A cache is considered outdated if any of its inputs have change...
if not cache_file: cache_file = find_config() cache_config = devpipeline_configure.parser.read_config(cache_file) cache = devpipeline_configure.cache._CachedConfig(cache_config, cache_file) if force or _is_outdated(cache_file, cache): cache = devpipeline_configure.config.process_config(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def app(environ, start_response): """Function called by the WSGI server."""
r = HttpRequestHandler(environ, start_response, Router).dispatch() return 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 make_job(job_name, **kwargs): """ Decorator to create a Job from a function. Give a job name and add extra fields to the job. @make_job("ExecuteDecJob", comm...
def wraps(func): kwargs['process'] = func job = type(job_name, (Job,), kwargs) globals()[job_name] = job return job return wraps
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_safe(str_or_bytes, encoding='utf-8', errors='ignore', output=sys.stdout, newline='\n'): """ Print unicode or bytes universally. :param str_or_bytes: st...
writer = output.buffer if hasattr(output, 'buffer') else output # When the input type is bytes, verify it can be decoded with the specified encoding. decoded = str_or_bytes if is_unicode(str_or_bytes) else to_unicode(str_or_bytes, encoding, errors) encoded = to_bytes(decoded, encoding, errors) wr...
<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_verified(self, msg_info): """ expects "msg_info" to have the field 'files_containers_id' This call already executes "update_last_checked_time" so it does...
assert hasattr(msg_info, 'files_containers_id') with self._session_resource as session: session.execute( update(FilesDestinations) .where(FilesDestinations.file_containers_id == msg_info.files_containers_id) .values(verification_info=m...
<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_uploaded_container(self, msg_info): """ returns 0 if it doesn't correspond to an uploaded container -1 if it corresponds to an uploaded container but it i...
results = { 'BAD': -1, 'NOT_FCB': 0, 'OK': 1 } for part in msg_info.msg_body.walk(): if part.is_multipart(): continue """ if part.get('Content-Disposition') is None: print("no content dispo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def abort(self, count=2, timeout=60): ''' Send an abort sequence using CAN bytes. ''' for counter in xrange(0, count): self.putc(CAN, timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def send(self, stream, retry=16, timeout=60, quiet=0, callback=None): ''' Send a stream via the XMODEM protocol. >>> stream = file('/etc/issue', 'rb') >>> print modem.send(stream) True Returns ``True`` upon succesful transmission or ``False`` in case of ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def recv(self, stream, crc_mode=1, retry=16, timeout=60, delay=1, quiet=0): ''' Receive a stream via the XMODEM protocol. >>> stream = file('/etc/issue', 'wb') >>> print modem.recv(stream) 2342 Returns the number of bytes received on success or ``None`` in c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def calc_crc(self, data, crc=0): ''' Calculate the Cyclic Redundancy Check for a given block of data, can also be used to update a CRC. >>> crc = modem.calc_crc('hello') >>> crc = modem.calc_crc('world', crc) >>> hex(crc) '0xd5e3' ''' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def combobox_set_model_from_list(cb, items): """Setup a ComboBox or ComboBoxEntry based on a list of strings."""
cb.clear() model = gtk.ListStore(str) for i in items: model.append([i]) cb.set_model(model) if type(cb) == gtk.ComboBoxEntry: cb.set_text_column(0) elif type(cb) == gtk.ComboBox: cell = gtk.CellRendererText() cb.pack_start(cell, True) cb.add_attribute(cel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def LastOf(*subcons): """ Create an adapter which uses only the last construct. If first argument is a string it will be the name. """
name = "seq" if isinstance(subcons[0], six.string_types): name = subcons[0] subcons = subcons[1:] return IndexingAdapter(Sequence(name, *subcons), -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 _make_scm(current_target): """ Create an Scm for a component. Arguments component - The component being operated on. """
# pylint: disable=protected-access tool_key = devpipeline_core.toolsupport.choose_tool_key( current_target, devpipeline_scm._SCM_TOOL_KEYS ) return devpipeline_core.toolsupport.tool_builder( current_target.config, tool_key, devpipeline_scm.SCMS, current_target )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkout_task(current_target): """ Update or a local checkout. Arguments target - The target to operate on. """
try: scm = _make_scm(current_target) src_dir = current_target.config.get("dp.src_dir") shared_dir = current_target.config.get("dp.src_dir_shared") scm.checkout(repo_dir=src_dir, shared_dir=shared_dir) scm.update(repo_dir=src_dir) except devpipeline_core.toolsupport.Missi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def proc_response(self, resp): """Process JSON data found in the response."""
# Try to interpret any JSON try: resp.obj = json.loads(resp.body) self._debug(" Received entity: %r", resp.obj) except ValueError: resp.obj = None self._debug(" No received entity; body %r", resp.body) # Now, call superclass method for...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _attach_obj(self, req, obj): """Helper method to attach obj to req as JSON data."""
# Attach the object to the request json.dump(obj, req) # Also set the content-type header req['content-type'] = self._content_type
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_module_egg_path(module_path): """ Find the path of the deployed egg package that may contain the specified module path. @param module_path: the path of ...
if module_path.find('.egg') == -1: return None _module_absolute_path = os.path.abspath(module_path) egg_paths = [os.path.relpath(_module_absolute_path, egg_path) for egg_path in [egg_path for egg_path in sys.path if REGEX_EGG_PACKAGE_PATH.match(egg_path) \ and _...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tmpl_shorten(text, max_size=32): """Shorten the given text to ``max_size`` * synopsis: ``%shorten{text}`` or ``%shorten{text,max_size}`` * example: ``%shorte...
max_size = int(max_size) if len(text) <= max_size: return text text = textwrap.wrap(text, max_size)[0] import re text = re.sub(r'\W+$', '', text) return text.strip()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tmpl_time(text, fmt, cur_fmt): """Format a time value using `strftime`. * synopsis: ``%time{date_time,format,curformat}`` * description: Return the date and ...
return time.strftime(fmt, time.strptime(text, cur_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 download_binaries(package_dir=False): """Download all binaries for the current platform Parameters package_dir: bool If set to `True`, the binaries will be d...
# bhfield # make sure the binary is available on the system paths = _bhfield.fetch.get_binaries() if package_dir: # Copy the binaries to the `resources` directory # of qpsphere. pdir = RESCR_PATH outpaths = [] for pp in paths: target = pdir / pp.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 remove_binaries(package_dir=False): """Remove all binaries for the current platform Parameters package_dir: bool If True, remove all binaries from the `resou...
paths = [] if package_dir: pdir = RESCR_PATH else: pdir = CACHE_PATH for pp in pdir.iterdir(): if pp.name != "shipped_resources_go_here": paths.append(pp) for pp in paths: pp.unlink()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def elapsed(func): """A decorator for calculating time elapsed when execute function"""
@functools.wraps(func) def wrapper(*args, **kw): start = time.time() print('Running `%s()` ...' % func.__name__) res = func(*args, **kw) end = time.time() print('Function `%s()` running elapsed %.2f s' % (func.__name__, end - start)) return res ...
<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_logger(log_file, name='logger', cmd=True): """define a logger for your program parameters log_file file name of log name name of logger example logger...
import logging logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) # set format formatter = logging.Formatter('%(asctime)s | %(name)s | %(levelname)s | %(message)s', datefmt='%Y-%m-%d %H:%M:%S') # file handler fh = logging.FileHandler(log_file...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def relative_time_to_text(l10n=locales.get(_default), **kwargs): """ Return an aproximate textual representation of the provioded duration of time. Examples: rel...
kwargs = _normalize(**kwargs) cor = _Chain() cor.add(_LessThan1M(l10n, **kwargs)) cor.add(_LessThan1H(l10n, **kwargs)) cor.add(_LessThan23H(l10n, **kwargs)) cor.add(_LessThan6D1H(l10n, **kwargs)) cor.add(_LessThan25D10H(l10n, **kwargs)) cor.add(_LessThan11MM(l10n, **kwargs)) cor.ad...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def size(self): """ size in bytes """
if not self._size: self._size = os.path.getsize(self._path) return self._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 do_heavy_work(self, block): """ Expects Compressor Block like objects """
cipher_key = self.gen_key(32) in_file_path = block.latest_file_info.path dst_file_path = block.processed_data_file_info.path + self.get_extension() self.log.debug("Encrypting file '%s' with key '%s' to file '%s'", in_file_path, cipher_key, dst_file_path) 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 autocommit(f): "A decorator to commit to the storage if autocommit is set to True." @wraps(f) def wrapper(self, *args, **kwargs): result = f(self, *args, **kwargs) if self._meta.commit_ready(): self.commit() return result 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 set(self, key, value): "Set value to the key store." # if key already in data, update indexes if not isinstance(value, dict): raise BadValueError( 'The value {} is incorrect.' ' Values should be strings'.format(value)) _value = deepcopy(val...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def insert(self, value): "Insert value in the keystore. Return the UUID key." key = str(uuid4()) self.set(key, value) return 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 delete(self, key): "Delete a `key` from the keystore." if key in self.data: self.delete_from_index(key) del self.data[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 update(self, key, value): """Update a `key` in the keystore. If the key is non-existent, it's being created """
if not isinstance(value, dict): raise BadValueError( 'The value {} is incorrect.' ' Values should be strings'.format(value)) if key in self.data: v = self.get(key) v.update(value) else: v = value self.set(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 del_key(self, key, key_to_delete): "Delete the `key_to_delete` for the record found with `key`." v = self.get(key) if key_to_delete in v: del v[key_to_delete] self.set(key, v)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def commit(self): "Commit data to the storage." if self._meta.path: with open(self._meta.path, 'wb') as fd: raw = deepcopy(self.raw) # LAZY INDEX PROCESSING # Save indexes only if not lazy lazy_indexes = self.lazy_indexes # Kee...
<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_to_values(self, keys): "Return the items in the keystore with keys in `keys`." return dict((k, v) for k, v in self.data.items() if k in keys)
<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_keys(self, **kwargs): "Return a set of keys filtered according to the given arguments." self._used_index = False keys = set(self.data.keys()) for key_filter, v_filter in kwargs.items(): if key_filter in self.indexes: self._used_index = True ...