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 create(self, password, username, realm=None): """ Creates a storage password. A `StoragePassword` can be identified by <username>, or by <realm>:<username> i...
if not isinstance(username, basestring): raise ValueError("Invalid name: %s" % repr(username)) if realm is None: response = self.post(password=password, name=username) else: response = self.post(password=password, realm=realm, name=username) if 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 create(self, username, password, roles, **params): """Creates a new user. This function makes two roundtrips to the server, plus at most two more if the ``au...
if not isinstance(username, basestring): raise ValueError("Invalid username: %s" % str(username)) username = username.lower() self.post(name=username, password=password, roles=roles, **params) # splunkd doesn't return the user in the POST response body, # so we have ...
<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_attribute(mcs, attribute_name, attribute_value): """ decides whether the given attribute should be excluded from tracing or not """
if attribute_name == '__module__': return True elif hasattr(attribute_value, '_trace_disable'): 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 setup_columns(self): """Creates the treeview stuff"""
tv = self.view['tv_categories'] # sets the model tv.set_model(self.model) # creates the columns cell = gtk.CellRendererText() tvcol = gtk.TreeViewColumn('Name', cell) def cell_data_func(col, cell, mod, it): if mod[it][0]: cell.set_property(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show_curr_model_view(self, model, select): """A currency has been added, or an existing curreny has been selected, and needs to be shown on the right side of...
v = self.view.add_currency_view(select) self.curreny = CurrencyCtrl(model, v) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_modification(self): """Modifications on the right side need to be committed"""
self.__changing_model = True if self.adding_model: self.model.add(self.adding_model) elif self.editing_model and self.editing_iter: # notifies the currencies model path = self.model.get_path(self.editing_iter) self.model.row_changed(path, self.editing_iter) ...
<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_selection_changed(self, sel): """The user changed selection"""
m, self.editing_iter = sel.get_selected() if self.editing_iter: self.editing_model = m[self.editing_iter][0] self.show_curr_model_view(self.editing_model, False) else: self.view.remove_currency_view() return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_estimates(positions, estimates): """ Plots density, and probability estimates. Parameters positions : iterable of float Paragraph positions for which de...
x = list(positions) fig = plt.figure(figsize=(SUBPLOT_WIDTH * len(estimates), FIGURE_HEIGHT)) for i, (title, y) in enumerate(zip(ESTIMATE_TITLES, estimates)): ax = fig.add_subplot(1, len(estimates), i + 1) ax.plot(x, y, linewidth=LINE_WIDTH, c=LINE_COLOR) ax.title.set_text(title) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure(self, options, conf): """ Get filetype option to specify additional filetypes to watch. """
Plugin.configure(self, options, conf) if options.filetype: self.filetypes += options.filetype
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wrap_multipart_params(func): """ A middleware that parses the multipart request body and adds the parsed content to the `multipart_params` attribute. This mi...
def wrapper(request, *args, **kwargs): ctype, pdict = parse_header(request.headers.get('Content-Type', '')) if ctype == "multipart/form-data": if isinstance(pdict['boundary'], str): pdict['boundary'] = pdict['boundary'].encode() params = {} mp ...
<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(self, code): """Core API method for appending to the source code stream. It can take the following as input. *Strings* The processor is called if spec...
# support one-shot push and pop of dictionaries using operators pop_next = self._pop_next if pop_next: self._pop_next = False if isinstance(code, str): # Strings are processed, then indented appropriately for token in self._process(code): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lines(self, code): """Fixes indentation for multiline strings before appending."""
if isinstance(code, str): fix_indentation = self.fix_indentation if fix_indentation: code = fix_indentation(code) return self.append(code) else: return self.append(code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def last_string(self): """The last entry in code_builder, or ``None`` if none so far."""
cb = self.code_builder len_cb = len(cb) if len_cb > 0: return cb[len_cb - 1] else: 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_context(self): """Pops the last set of keyword arguments provided to the processor."""
processor = getattr(self, 'processor', None) if processor is not None: pop_context = getattr(processor, 'pop_context', None) if pop_context is None: pop_context = getattr(processor, 'pop', None) if pop_context is not None: return pop_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 unescape(inp, quote='"'): """ Unescape `quote` in string `inp`. Example usage:: >> unescape('hello \\"') 'hello "' Args: inp (str): String in which `quote` ...
if len(inp) < 2: return inp output = "" unesc = False for act in inp: if act == quote and unesc: output = output[:-1] output += act if act == "\\": unesc = not unesc else: unesc = False return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def escape(inp, quote='"'): """ Escape `quote` in string `inp`. Example usage:: 'hello \\"' 'hello \\\\"' Args: inp (str): String in which `quote` will be escap...
output = "" for c in inp: if c == quote: output += '\\' output += c return output
<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, channel): """Read single ADC Channel"""
checked_channel = self._check_channel_no(channel) self.i2c.write_raw8(checked_channel | self._dac_enabled) reading = self.i2c.read_raw8() reading = self.i2c.read_raw8() return reading / 255.0
<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, channel, state): """Set DAC value and enable output"""
checked_val = self._check_dac_val(channel, state) self._dac_enabled = 0x40 self.i2c.write8(self._dac_enabled, checked_val * 255)
<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_optional_env(key): """ Return the value of an optional environment variable, and use the provided default if it's not set. """
environment_variable_value = os.environ.get(key) if environment_variable_value: return environment_variable_value elif key in CONSTANTS: return CONSTANTS[key] else: raise Exception("The variable {1} is not set".format(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 to_datetime_with_default(value, default_value): """ Converts value into Date or returns default when conversion is not possible. :param value: the value to c...
result = DateTimeConverter.to_nullable_datetime(value) return result if result != None else DateTimeConverter.to_utc_datetime(default_value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """Close the cursor"""
if self.closed or self.connection.closed: return self._cursor.close() self.closed = 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 acquire(self, lock_transactions=None): """ Acquire the connection locks. :param lock_transactions: `bool`, acquire the transaction lock (`self.lock_transacti...
if not self.personal_lock.acquire(timeout=self.lock_timeout): raise LockTimeoutError(self) self.with_count += 1 if lock_transactions is None: lock_transactions = self.lock_transactions if lock_transactions and self.db_state.active_connection is not 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 release(self, lock_transactions=None): """ Release the connection locks. :param lock_transactions: `bool`, release the transaction lock (`self.lock_transacti...
self.personal_lock.release() self.with_count -= 1 if lock_transactions is None: lock_transactions = self.lock_transactions if not lock_transactions: self.db_state.lock.release() return try: # If the connection is closed, an 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 to_type_code(value): """ Gets TypeCode for specific value. :param value: value whose TypeCode is to be resolved. :return: the TypeCode that corresponds to th...
if value == None: return TypeCode.Unknown if not isinstance(value, type): value = type(value) if value is list: return TypeCode.Array elif value is tuple: return TypeCode.Array elif value is set: return TypeCode.Array...
<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_type_with_default(value_type, value, default_value): """ Converts value into an object type specified by Type Code or returns default value when conversio...
result = TypeConverter.to_nullable_type(value_type, value) return result if result != None else default_value
<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_string(type): """ Converts a TypeCode into its string name. :param type: the TypeCode to convert into a string. :return: the name of the TypeCode passed a...
if type == None: return "unknown" elif type == TypeCode.Unknown: return "unknown" elif type == TypeCode.String: return "string" elif type == TypeCode.Integer: return "integer" elif type == TypeCode.Long: return "long" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_netsh_command(netsh_args): """Execute a netsh command and return the output."""
devnull = open(os.devnull, 'w') command_raw = 'netsh interface ipv4 ' + netsh_args return int(subprocess.call(command_raw, stdout=devnull))
<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_array(raw_array): """Parse a WMIC array."""
array_strip_brackets = raw_array.replace('{', '').replace('}', '') array_strip_spaces = array_strip_brackets.replace('"', '').replace(' ', '') return array_strip_spaces.split(',')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def llcs(s1, s2): '''length of the longest common sequence This implementation takes O(len(s1) * len(s2)) time and O(min(len(s1), len(s2))) space. Use only with short strings. >>> llcs('a.b.cd','!a!b!c!!!d!') 4 ''' m, n = len(s1), len(s2) if m < n: # ensure n <= m, to use O(min(n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def lcsr(s1, s2): '''longest common sequence ratio >>> lcsr('ab', 'abcd') 0.5 ''' if s1 == s2: return 1.0 return llcs(s1, s2) / max(1, len(s1), len(s2))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def lcp(s1, s2): '''longest common prefix >>> lcp('abcdx', 'abcdy'), lcp('', 'a'), lcp('x', 'yz') (4, 0, 0) ''' i = 0 for i, (c1, c2) in enumerate(zip(s1, s2)): if c1 != c2: return i return min(len(s1), len(s2))
<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(data, b64_encode=True, uri_encode=True): """Serializes a python dictionary into a Gzip, Base64 encoded string :param data: Python dictionary or lis...
if not isinstance(data, dict): raise RuntimeError("Only dictionaries are supported. The following is not a dictionary:\n %s", data) message = json.dumps(data) if b64_encode: message = jsonuri.io.compress(message).decode('utf-8') if uri_encode: message = urllib.parse.quote_pl...
<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(self, width, len_): """Initializes internal data representation of the BinArray to all-0. The internal data representation is simply tightly-packed bit...
self._width = width self._len = len_ bits = len_ * width self._data = bytearray(BinInt(bits).ceildiv(8))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _locate(self, idx): """Locates an element in the internal data representation. Returns starting byte index, starting bit index in the starting byte, and one ...
start = idx * self._width end = (idx + 1) * self._width sbyte, sbit = divmod(start, 8) ebyte = BinInt(end).ceildiv(8) return sbyte, sbit, ebyte
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def repack(self, to_width, *, msb_first, start=0, start_bit=0, length=None): """Extracts a part of a BinArray's data and converts it to a BinArray of a different...
to_width = operator.index(to_width) if not isinstance(msb_first, bool): raise TypeError('msb_first must be a bool') available = self.repack_data_available( to_width, start=start, start_bit=start_bit) if length is None: length = available e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def repack_data_available(src_width, to_width, *, # noqa: N805 src_length=None, start=None, start_bit=0): """Calculates the maximum number of words that can be r...
start_bit = operator.index(start_bit) if isinstance(src_width, BinArray): self = src_width if src_length is None: if start is None: start = 0 else: start = operator.index(start) if start ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def bucket_to_dataframe(name, buckets, append_name=None): '''A function that turns elasticsearch aggregation buckets into dataframes :param name: The name of the bucket (will be a column in the dataframe) :type name: str :param bucket: a bucket from elasticsearch results :type bucke...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def agg_to_two_dim_dataframe(agg): '''A function that takes an elasticsearch response with aggregation and returns the names of all bucket value pairs :param agg: an aggregation from elasticsearch results :type agg: elasticsearch response.aggregation.agg_name object :returns: pandas data fr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def merge_dataframes(*dfs): '''A helper function for merging two dataframes that have the same indices, duplicate columns are removed :param dfs: a list of dataframes to be merged (note: they must have the same indices) :type dfs: list[pandas.DataFrame] :returns: pandas.DataFrame -- a merge...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode(self): """Decodes the mission files into dictionaries"""
LOGGER.debug('decoding lua tables') if not self.zip_content: self.unzip() LOGGER.debug('reading map resource file') with open(str(self.map_res_file), encoding=ENCODING) as stream: self._map_res, self._map_res_qual = SLTP().decode(stream.read()) 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 unzip(self, overwrite: bool = False): """ Flattens a MIZ file into the temp dir Args: overwrite: allow overwriting exiting files """
if self.zip_content and not overwrite: raise FileExistsError(str(self.temp_dir)) LOGGER.debug('unzipping miz to temp dir') try: with ZipFile(str(self.miz_path)) as zip_file: LOGGER.debug('reading infolist') self.zip_content = [f.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 lis(seq, indices=False): '''longest increasing subsequence >>> lis([1, 2, 5, 3, 4]) [1, 2, 3, 4] ''' if not seq: return [] # prevs[i] is the index of the previous element in the longest subsequence # containing element i prevs = [None] * len(seq) # tails[i] is the pair (...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __fix_bases(base_classes, have_mt): """This function check whether base_classes contains a Model instance. If not, choose the best fitting class for model. F...
fixed = list(base_classes) contains_model = False for b in fixed: if isinstance(fixed, Model): contains_model = True; break pass # adds a model when user is lazy if not contains_model: if have_mt: from gtkmvc3.model_mt import ...
<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(base_classes=(), have_mt=False): """Use this static method to build a model class that possibly derives from other classes. If have_mt is True, then ret...
good_bc = ModelFactory.__fix_bases(base_classes, have_mt) print "Base classes are:", good_bc key = "".join(map(str, good_bc)) if key in ModelFactory.__memoized: return ModelFactory.__memoized[key] cls = new.classobj('', good_bc, {'__module__': '__main__', '__doc__'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _authentication(request_fun): """Decorator to handle autologin and authentication errors. *request_fun* is a function taking no arguments that needs to be ru...
@wraps(request_fun) def wrapper(self, *args, **kwargs): if self.token is _NoAuthenticationToken: # Not yet logged in. if self.autologin and self.username and self.password: # This will throw an uncaught # AuthenticationError if it fails. ...
<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, path_segment, owner=None, app=None, sharing=None, **query): """Performs a GET operation from the REST path segment with the given namespace and que...
path = self.authority + self._abspath(path_segment, owner=owner, app=app, sharing=sharing) logging.debug("GET request to %s (body: %s)", path, repr(query)) response = self.http.get(path, self._auth_headers, **query) 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 post(self, url, headers=None, **kwargs): """Sends a POST request to a URL. :param url: The URL. :type url: ``string`` :param headers: A list of pairs specify...
if headers is None: headers = [] headers.append(("Content-Type", "application/x-www-form-urlencoded")), # We handle GET-style arguments and an unstructured body. This is here # to support the receivers/stream endpoint. if 'body' in kwargs: body = kwargs.pop('body') ...
<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_proxy_model(self, model): """Create a sort filter proxy model for the given model :param model: the model to wrap in a proxy :type model: :class:`QtGu...
proxy = ReftrackSortFilterModel(self) proxy.setSourceModel(model) model.rowsInserted.connect(self.sort_model) return proxy
<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_filter(self, ): """Create a checkbox for every reftrack type so one can filter them :returns: None :rtype: None :raises: None """
types = self.refobjinter.types.keys() for i, t in enumerate(types): cb = QtGui.QCheckBox("%s" % t) cb.setChecked(True) cb.toggled.connect(self.update_filter) self.typecbmap[t] = cb self.typefilter_grid.addWidget(cb, int(i / 4), i % 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 switch_showfilter_icon(self, toggled): """Switch the icon on the showfilter_tb :param toggled: the state of the button :type toggled: :class:`bool` :returns:...
at = QtCore.Qt.DownArrow if toggled else QtCore.Qt.RightArrow self.showfilter_tb.setArrowType(at)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_addnew_win(self, *args, **kwargs): """Open a new window so the use can choose to add new reftracks :returns: None :rtype: None :raises: NotImplementedEr...
if self.reftrackadderwin: self.reftrackadderwin.close() self.reftrackadderwin = ReftrackAdderWin(self.refobjinter, self.root, parent=self) self.reftrackadderwin.destroyed.connect(self.addnewwin_destroyed) self.reftrackadderwin.show()
<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_filter(self, *args, **kwargs): """Update the filter :returns: None :rtype: None :raises: NotImplementedError """
forbidden_statuses = [] if not self.loaded_checkb.isChecked(): forbidden_statuses.append(reftrack.Reftrack.LOADED) if not self.unloaded_checkb.isChecked(): forbidden_statuses.append(reftrack.Reftrack.UNLOADED) if not self.imported_checkb.isChecked(): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_model(self, *args, **kwargs): """Sort the proxy model :returns: None :rtype: None :raises: None """
self.proxy.sort(17) # sort the identifier self.proxy.sort(2) # sort the element self.proxy.sort(1) # sort the elementgrp self.proxy.sort(0)
<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_selected(self, ): """Create a new reftrack with the selected element and type and add it to the root. :returns: None :rtype: None :raises: NotImplemented...
browser = self.shot_browser if self.browser_tabw.currentIndex() == 1 else self.asset_browser selelements = browser.selected_indexes(2) if not selelements: return seltypes = browser.selected_indexes(3) if not seltypes: return elementi = selelements...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_ensemble(ensemble, options): """ Prints out the ensemble composition at each size """
# set output file name size = len(ensemble) filename = '%s_%s_queries.csv' % (options.outname, size) file = os.path.join(os.getcwd(), filename) f = open(file, 'w') out = ', '.join(ensemble) f.write(out) f.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 lookup_blob(hash_value): """ Combines all given arguments to create clean title-tags values. All arguments are divided by a " " seperator and HTML tags are t...
try: blob = BlobStorage.objects.get(sha256=hash_value) except: return "Blob not found" return blob.content
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def comet_view(self, request): """ This is dumb function, it just passes everything it gets into the message stream. Something else in the stream should be respo...
request_id = self.id_for_request(request) if not request_id: request.write(HttpResponse(403).as_bytes()) request.finish() return data = { 'headers': request.headers, 'arguments': request.arguments, 'remote_ip': req...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sshagent_run(cmd): """ Helper function. Runs a command with SSH agent forwarding enabled. Note:: Fabric (and paramiko) can't forward your SSH agent. This hel...
# Handle context manager modifications wrapped_cmd = _prefix_commands(_prefix_env_vars(cmd), 'remote') try: host, port = env.host_string.split(':') return local( u"ssh -p %s -A -o StrictHostKeyChecking=no %s@%s '%s'" % ( port, env.user, host, wrapped_cmd ...
<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_object(obj): """Return a JSON serializable type for ``o``. Args: obj (:py:class:`object`): the object to be serialized. Raises: :py:class:`AttributeError...
LOGGER.debug('as_object(%s)', obj) if isinstance(obj, datetime.date): return as_date(obj) elif hasattr(obj, '__dict__'): # populate dict with visible attributes out = {k: obj.__dict__[k] for k in obj.__dict__ if not k.startswith('_')} # populate dict with property 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 as_date(dat): """Return the RFC3339 UTC string representation of the given date and time. Args: dat (:py:class:`datetime.date`): the object/type to be seria...
LOGGER.debug('as_date(%s)', dat) return strict_rfc3339.timestamp_to_rfc3339_utcoffset( calendar.timegm(dat.timetuple()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chunks(iterable, chunk): """Yield successive n-sized chunks from an iterable."""
for i in range(0, len(iterable), chunk): yield iterable[i:i + chunk]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def integrate(self, function, lower_bound, upper_bound): """ Calculates the integral of the given one dimensional function in the interval from lower_bound to up...
ret = 0.0 n = self.nsteps xStep = (float(upper_bound) - float(lower_bound)) / float(n) self.log_info("xStep" + str(xStep)) x = lower_bound val1 = function(x) self.log_info("val1: " + str(val1)) for i in range(n): x = (i + 1) * xStep + lower_bo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sam_iter(handle, start_line=None, headers=False): """Iterate over SAM file and return SAM entries Args: handle (file): SAM file handle, can be any iterator ...
# Speed tricks: reduces function calls split = str.split strip = str.strip next_line = next if start_line is None: line = next_line(handle) # Read first B6/M8 entry else: line = start_line # Set header to given header # Check if input is text or bytestream if (isin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self): """Return SAM formatted string Returns: str: SAM formatted string containing entire SAM entry """
return '{0}\t{1}\t{2}\t{3}\t{4}\t' \ '{5}\t{6}\t{7}\t{8}\t{9}\t' \ '{10}{11}'.format(self.qname, str(self.flag), self.rname, str(self.pos), str(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 request(self, request_path, data=None, do_authentication=True, is_json=True): """ Core "worker" for making requests and parsing JSON responses. If `is_json` ...
uri = self.api_uri % request_path request = urllib2.Request(uri) # Build up the request if is_json: request.add_header("Content-Type", "application/json") if data is not None: request.add_data(json.dumps(data)) elif data 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 _make_request(self, request): """ Does the magic of actually sending the request and parsing the response """
# TODO: I'm sure all kinds of error checking needs to go here try: response_raw = urllib2.urlopen(request) except urllib2.HTTPError, e: print e.read() raise response_str = response_raw.read() response = json.loads(response_str) 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 add_member(self, address, **kwargs): """ Add a member to a group. All Fiesta membership options can be passed in as keyword arguments. Some valid options inc...
path = 'membership/%s' % self.id kwargs["address"] = address if "group_name" not in kwargs and self.default_name: kwargs["group_name"] = self.default_name response_data = self.api.request(path, kwargs) if 'user_id' in response_data: user_id = response_d...
<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_message(self, subject=None, text=None, markdown=None, message_dict=None): """ Helper function to send a message to a group """
message = FiestaMessage(self.api, self, subject, text, markdown, message_dict) return message.send()
<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_application(self, application_id, **kwargs): """ Add an application to a group. `application_id` is the name of the application to add. Any application o...
path = 'group/%s/application' % self.id data = {'application_id': application_id} if kwargs: data["options"] = kwargs self.api.request(path, 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 send(self, group_id=None, message_dict=None): """ Send this current message to a group. `message_dict` can be a dictionary formatted according to http://docs...
if self.group is not None and self.group.id is not None: group_id = self.group.id path = 'message/%s' % group_id if message_dict is not None: request_data = { 'message': message_dict, } else: subject = self.subject ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_ui(self, ): """Setup the ui :returns: None :rtype: None :raises: None """
labels = self.reftrack.get_option_labels() self.browser = ComboBoxBrowser(len(labels), headers=labels) self.browser_vbox.addWidget(self.browser)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select(self, ): """Store the selected taskfileinfo self.selected and accept the dialog :returns: None :rtype: None :raises: None """
s = self.browser.selected_indexes(self.browser.get_depth()-1) if not s: return i = s[0].internalPointer() if i: tfi = i.internal_data() self.selected = tfi self.accept()
<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_icons(self, ): """Setup the icons of the ui :returns: None :rtype: None :raises: None """
iconbtns = [("menu_border_24x24.png", self.menu_tb), ("duplicate_border_24x24.png", self.duplicate_tb), ("delete_border_24x24.png", self.delete_tb), ("reference_border_24x24.png", self.reference_tb), ("load_border_24x24.png", 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 set_maintext(self, index): """Set the maintext_lb to display text information about the given reftrack :param index: the index :type index: :class:`QtGui.QMo...
dr = QtCore.Qt.DisplayRole text = "" model = index.model() for i in (1, 2, 3, 5, 6): new = model.index(index.row(), i, index.parent()).data(dr) if new is not None: text = " | ".join((text, new)) if text else new self.maintext_lb.setText(t...
<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_identifiertext(self, index): """Set the identifier text on the identifier_lb :param index: the index :type index: :class:`QtGui.QModelIndex` :returns: No...
dr = QtCore.Qt.DisplayRole t = index.model().index(index.row(), 17, index.parent()).data(dr) if t is None: t = -1 else: t = t+1 self.identifier_lb.setText("#%s" % t)
<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_type_icon(self, index): """Set the type icon on type_icon_lb :param index: the index :type index: :class:`QtGui.QModelIndex` :returns: None :rtype: None ...
icon = index.model().index(index.row(), 0, index.parent()).data(QtCore.Qt.DecorationRole) if icon: pix = icon.pixmap(self.type_icon_lb.size()) self.type_icon_lb.setPixmap(pix) else: self.type_icon_lb.setPixmap(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 disable_restricted(self, ): """Disable the restricted buttons :returns: None :rtype: None :raises: None """
todisable = [(self.reftrack.duplicate, self.duplicate_tb), (self.reftrack.delete, self.delete_tb), (self.reftrack.reference, self.reference_tb), (self.reftrack.replace, self.replace_tb),] for action, btn in todisable: res = 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 hide_restricted(self, ): """Hide the restricted buttons :returns: None :rtype: None :raises: None """
tohide = [((self.reftrack.unload, self.unload_tb), (self.reftrack.load, self.load_tb)), ((self.reftrack.import_file, self.importtf_tb), (self.reftrack.import_reference, self.importref_tb))] for (action1, btn1), (action2, btn2) in tohide: ...
<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_top_bar_color(self, index): """Set the color of the upper frame to the background color of the reftrack status :param index: the index :type index: :clas...
dr = QtCore.Qt.ForegroundRole c = index.model().index(index.row(), 8, index.parent()).data(dr) if not c: c = self.upper_fr_default_bg_color self.upper_fr.setStyleSheet('background-color: rgb(%s, %s, %s)' % (c.red(), c.green(), c.blue()))
<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_menu(self, ): """Setup the menu that the menu_tb button uses :returns: None :rtype: None :raises: None """
self.menu = QtGui.QMenu(self) actions = self.reftrack.get_additional_actions() self.actions = [] for a in actions: if a.icon: qaction = QtGui.QAction(a.icon, a.name, self) else: qaction = QtGui.QAction(a.name, self) qac...
<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_taskfileinfo_selection(self, ): """Return a taskfileinfo that the user chose from the available options :returns: the chosen taskfileinfo :rtype: :class:...
sel = OptionSelector(self.reftrack) sel.exec_() return sel.selected
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reference(self, ): """Reference a file :returns: None :rtype: None :raises: None """
tfi = self.get_taskfileinfo_selection() if tfi: self.reftrack.reference(tfi)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_file(self, ): """Import a file :returns: None :rtype: None :raises: NotImplementedError """
tfi = self.get_taskfileinfo_selection() if tfi: self.reftrack.import_file(tfi)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace(self, ): """Replace the current reftrack :returns: None :rtype: None :raises: None """
tfi = self.get_taskfileinfo_selection() if tfi: self.reftrack.replace(tfi)
<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_renditions_if_master_has_changed(sender, instance, **kwargs): '''if master file as changed delete all renditions''' try: obj = sender.objects.get(pk=instance.pk) except sender.DoesNotExist: pass # Object is new, so field hasn't technically changed. else: if not obj.ma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def photo_post_delete_handler(sender, **kwargs): '''delete image when rows is gone from database''' instance = kwargs.get('instance') instance.master.delete(save=False) instance.delete_all_renditions()
<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_rendition_size(self, width=0, height=0): '''returns real rendition URL''' if width == 0 and height == 0: return (self.master_width, self.master_height) target_width = int(width) target_height = int(height) ratio = self.master_width / float(self.master_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 get_rendition_url(self, width=0, height=0): '''get the rendition URL for a specified size if the renditions does not exists it will be created ''' if width == 0 and height == 0: return self.get_master_url() target_width, target_height = self.get_rendition_size(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 delete_all_renditions(self): '''delete all renditions and rendition dict''' if self.renditions: for r in self.renditions.values(): default_storage.delete(r) self.renditions = {}
<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_rendition(self, width, height): '''build a rendition 0 x 0 -> will give master URL only width -> will make a renditions with master's aspect ratio width x height -> will make an image potentialy cropped ''' image = Image.open(self.master) format = 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 execute_actioncollection(obj, actioncollection, confirm=True): """Execute the given actioncollection with the given object :param obj: the object to be proce...
actioncollection.execute(obj) status = actioncollection.status() if status.value == ActionStatus.SUCCESS or not confirm: return status ard = ActionReportDialog(actioncollection) confirmed = ard.exec_() if confirmed: msg = "User confirmed to continue although the status was: %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 release(self): """Create a release 1. Perform Sanity checks on work file. 2. Copy work file to releasefile location. 3. Perform cleanup actions on releasefil...
log.info("Releasing: %s", self._workfile.get_fullpath()) ac = self.build_actions() ac.execute(self) s = ac.status().value if not s == ActionStatus.SUCCESS: ard = ActionReportDialog(ac) ard.exec_() pass return s == ActionStatus.SUCCESS
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_actions(self): """Create an ActionCollection that will perform sanity checks, copy the file, create a database entry and perform cleanup actions and in...
checkau = ActionUnit("Sanity Checks", "Check the workfile. If the file is not conform, ask the user to continue.", self.sanity_check) copyau = ActionUnit("Copy File", "Copy the workfile to the releasefile location.", ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sanity_check(self, release): """Perform sanity checks on the workfile of the given release This is inteded to be used in a action unit. :param release: the r...
log.info("Performing sanity checks.") return execute_actioncollection(release._workfile, actioncollection=release._checks, confirm=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 copy(self, release): """Copy the workfile of the given release to the releasefile location This is inteded to be used in a action unit. :param release: the r...
workfp = release._workfile.get_fullpath() releasefp = release._releasefile.get_fullpath() copy_file(release._workfile, release._releasefile) return ActionStatus(ActionStatus.SUCCESS, msg="Copied %s to %s location." % (workfp, ...
<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_db_entry(self, release): """Create a db entry for releasefile of the given release Set _releasedbentry and _commentdbentry of the given release file T...
log.info("Create database entry with comment: %s", release.comment) tfi = release._releasefile.get_obj() tf, note = tfi.create_db_entry(release.comment) release._releasedbentry = tf release._commentdbentry = note return ActionStatus(ActionStatus.SUCCESS, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cleanup(self, release): """Perform cleanup actions on the releasefile of the given release This is inteded to be used in a action unit. :param release: the r...
log.info("Performing cleanup.") return execute_actioncollection(release._releasefile, actioncollection=release._cleanup, confirm=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 delete_releasefile(self, release): """Delete the releasefile of the given release This is inteded to be used in a action unit. :param release: the release wi...
fp = release._releasefile.get_fullpath() log.info("Deleting release file %s", fp) delete_file(release._releasefile) return ActionStatus(ActionStatus.SUCCESS, msg="Deleted %s" % fp)
<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_db_entry(self, release): """Delete the db entries for releasefile and comment of the given release :param release: the release with the releasefile an...
log.info("Delete database entry for file.") release._releasedbentry.delete() log.info("Delete database entry for comment.") release._commentdbentry.delete() return ActionStatus(ActionStatus.SUCCESS, msg="Deleted database entries for releasefile and co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def socket_reader(connection: socket, buffer_size: int = 1024): """ read data from adb socket """
while connection is not None: try: buffer = connection.recv(buffer_size) # no output if not len(buffer): raise ConnectionAbortedError except ConnectionAbortedError: # socket closed print('connection aborted') co...