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 add_class(self, ioclass): """Add one VNXIOClass instance to policy. .. note: due to the limitation of VNX, need to stop the policy first. """
current_ioclasses = self.ioclasses if ioclass.name in current_ioclasses.name: return current_ioclasses.append(ioclass) self.modify(new_ioclasses=current_ioclasses)
<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_class(self, ioclass): """Remove VNXIOClass instance from policy."""
current_ioclasses = self.ioclasses new_ioclasses = filter(lambda x: x.name != ioclass.name, current_ioclasses) self.modify(new_ioclasses=new_ioclasses)
<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_lun(self, *lun_list): """Replaces the exiting LUNs to lun_list."""
lun_add = self._prepare_luns_add(lun_list) lun_remove = self._prepare_luns_remove(lun_list, False) return self.modify(lun_add=lun_add, lun_remove=lun_remove)
<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_lun(self, add_luns=None, remove_luns=None): """Updates the LUNs in CG, adding the ones in `add_luns` and removing the ones in `remove_luns`"""
if not add_luns and not remove_luns: log.debug("Empty add_luns and remove_luns passed in, " "skip update_lun.") return RESP_OK lun_add = self._prepare_luns_add(add_luns) lun_remove = self._prepare_luns_remove(remove_luns, True) return self.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 clean(inst): """Routine to return FPMU data cleaned to the specified level Parameters inst : (pysat.Instrument) Instrument class object, whose attribute clea...
inst.data.replace(-999., np.nan, inplace=True) # Te inst.data.replace(-9.9999998e+30, np.nan, inplace=True) #Ni 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 _attach_files(self, files_info): """Attaches info returned by instrument list_files routine to Instrument object. """
if not files_info.empty: if (len(files_info.index.unique()) != len(files_info)): estr = 'WARNING! Duplicate datetimes in provided file ' estr = '{:s}information.\nKeeping one of each '.format(estr) estr = '{:s}of the duplicates, dropping the rest.'.f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _store(self): """Store currently loaded filelist for instrument onto filesystem"""
name = self.stored_file_name # check if current file data is different than stored file list # if so, move file list to previous file list, store current to file # if not, do nothing stored_files = self._load() if len(stored_files) != len(self.files): # # 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 _load(self, prev_version=False): """Load stored filelist and return as Pandas Series Parameters prev_version : boolean if True, will load previous version of...
fname = self.stored_file_name if prev_version: fname = os.path.join(self.home_path, 'previous_'+fname) else: fname = os.path.join(self.home_path, fname) if os.path.isfile(fname) and (os.path.getsize(fname) > 0): if self.write_to_disk: ...
<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_data_dir_path(self, inp=None): # import string """Remove the data directory path from filenames"""
# need to add a check in here to make sure data_dir path is actually in # the filename if inp is not None: split_str = os.path.join(self.data_path, '') return inp.apply(lambda x: x.split(split_str)[-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 concat(self, other, strict=False): """Concats two metadata objects together. Parameters other : Meta Meta object to be concatenated strict : bool if True, en...
mdata = self.copy() # checks if strict: for key in other.keys(): if key in mdata: raise RuntimeError('Duplicated keys (variable names) ' + 'across Meta objects in keys().') for key in other.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 pop(self, name): """Remove and return metadata about variable Parameters name : str variable name Returns ------- pandas.Series Series of metadata for variab...
# check if present if name in self: # get case preserved name for variable new_name = self.var_case_name(name) # check if 1D or nD if new_name in self.keys(): output = self[new_name] self.data.drop(new_name, inplace=True, a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transfer_attributes_to_instrument(self, inst, strict_names=False): """Transfer non-standard attributes in Meta to Instrument object. Pysat's load_netCDF and ...
# base Instrument attributes banned = inst._base_attr # get base attribute set, and attributes attached to instance base_attrb = self._base_attr this_attrb = dir(self) # collect these attributes into a dict adict = {} transfer_key = [] for key in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_csv(cls, name=None, col_names=None, sep=None, **kwargs): """Create instrument metadata object from csv. Parameters name : string absolute filename for c...
import pysat req_names = ['name','long_name','units'] if col_names is None: col_names = req_names elif not all([i in col_names for i in req_names]): raise ValueError('col_names must include name, long_name, units.') if sep is None: sep = ',' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nonraw_instance(receiver): """ A signal receiver decorator that fetch the complete instance from db when it's passed as raw """
@wraps(receiver) def wrapper(sender, instance, raw, using, **kwargs): if raw: instance = sender._default_manager.using(using).get(pk=instance.pk) return receiver(sender=sender, raw=raw, instance=instance, using=using, **kwargs) 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 base_definition_pre_delete(sender, instance, **kwargs): """ This is used to pass data required for deletion to the post_delete signal that is no more availab...
# see CASCADE_MARK_ORIGIN's docstring cascade_deletion_origin = popattr( instance._state, '_cascade_deletion_origin', None ) if cascade_deletion_origin == 'model_def': return if (instance.base and issubclass(instance.base, models.Model) and instance.base._meta.abstract):...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def base_definition_post_delete(sender, instance, **kwargs): """ Make sure to delete fields inherited from an abstract model base. """
if hasattr(instance._state, '_deletion'): # Make sure to flatten abstract bases since Django # migrations can't deal with them. model = popattr(instance._state, '_deletion') for field in instance.base._meta.fields: perform_ddl('remove_field', model, field)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def raw_field_definition_proxy_post_save(sender, instance, raw, **kwargs): """ When proxy field definitions are loaded from a fixture they're not passing through...
if raw: model_class = instance.content_type.model_class() opts = model_class._meta if opts.proxy and opts.concrete_model is sender: field_definition_post_save( sender=model_class, instance=instance.type_cast(), raw=raw, **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 field_definition_post_save(sender, instance, created, raw, **kwargs): """ This signal is connected by all FieldDefinition subclasses see comment in FieldDefi...
model_class = instance.model_def.model_class().render_state() field = instance.construct_for_migrate() field.model = model_class if created: if hasattr(instance._state, '_creation_default_value'): field.default = instance._state._creation_default_value delattr(instance._...
<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_cache_deepcopy(obj): """ An helper that correctly deepcopy model cache state """
if isinstance(obj, defaultdict): return deepcopy(obj) elif isinstance(obj, dict): return type(obj)((_app_cache_deepcopy(key), _app_cache_deepcopy(val)) for key, val in obj.items()) elif isinstance(obj, list): return list(_app_cache_deepcopy(val) for val in obj) elif isinstance(o...
<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_cache_restorer(): """ A context manager that restore model cache state as it was before entering context. """
state = _app_cache_deepcopy(apps.__dict__) try: yield state finally: with apps_lock(): apps.__dict__ = state # Rebind the app registry models cache to # individual app config ones. for app_conf in apps.get_app_configs(): app_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 CASCADE_MARK_ORIGIN(collector, field, sub_objs, using): """ Custom on_delete handler which sets _cascade_deletion_origin on the _state of the all relating ob...
CASCADE(collector, field, sub_objs, using) if sub_objs: for obj in sub_objs: obj._state._cascade_deletion_origin = field.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 mutable_model_prepared(signal, sender, definition, existing_model_class, **kwargs): """ Make sure all related model class are created and marked as dependenc...
referenced_models = set() # Collect all model class the obsolete model class was referring to if existing_model_class: for field in existing_model_class._meta.local_fields: if isinstance(field, RelatedField): remote_field_model = get_remote_field_model(field) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _model_class_from_pk(definition_cls, definition_pk): """ Helper used to unpickle MutableModel model class from their definition pk. """
try: return definition_cls.objects.get(pk=definition_pk).model_class() except definition_cls.DoesNotExist: 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 clean(self): """ Make sure the lookup makes sense """
if self.lookup == '?': # Randomly sort return else: lookups = self.lookup.split(LOOKUP_SEP) opts = self.model_def.model_class()._meta valid = True while len(lookups): lookup = lookups.pop(0) try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lorentz_deriv((x, y, z), t0, sigma=10., beta=8./3, rho=28.0): """Compute the time-derivative of a Lorentz system."""
return [sigma * (y - x), x * (rho - z) - y, x * y - beta * z]
<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_series_args(topics, fields): '''Return which topics and which field keys need to be examined for plotting''' keys = {} for field in fields: for topic in topics: if field.startswith(topic): keys[field] = (topic, field[len(topic) + 1:]) return 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 bag_to_dataframe(bag_name, include=None, exclude=None, parse_header=False, seconds=False): ''' Read in a rosbag file and create a pandas data frame that is indexed by the time the message was recorded in the bag. :bag_name: String name for the bag file :include: None, String, or List Topics to...
<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_data_map(msgs_to_read): ''' Create a data map for usage when parsing the bag ''' dmap = {} for topic in msgs_to_read.keys(): base_name = get_key_name(topic) + '__' fields = {} for f in msgs_to_read[topic]: key = (base_name + f).replace('.', '_') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def prune_topics(bag_topics, include, exclude): '''prune the topics. If include is None add all to the set of topics to use if include is a string regex match that string, if it is a list use the list If exclude is None do nothing, if string remove the topics with regex, if it is a 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 get_msg_info(yaml_info, topics, parse_header=True): ''' Get info from all of the messages about what they contain and will be added to the dataframe ''' topic_info = yaml_info['topics'] msgs = {} classes = {} for topic in topics: base_key = get_key_name(topic) msg_pa...
<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_topics(yaml_info): ''' Returns the names of all of the topics in the bag, and prints them to stdout if requested ''' # Pull out the topic info names = [] # Store all of the topics in a dictionary topics = yaml_info['topics'] for topic in topics: names.append(topic['to...
<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_base_fields(msg, prefix='', parse_header=True): '''function to get the full names of every message field in the message''' slots = msg.__slots__ ret_val = [] msg_types = dict() for i in slots: slot_msg = getattr(msg, i) if not parse_header and i == 'header': conti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jsonify_payload(self): """ Dump the payload to JSON """
# Assume already json serialized if isinstance(self.payload, string_types): return self.payload return json.dumps(self.payload, cls=StandardJSONEncoder)
<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): """ Send the webhook method """
payload = self.payload sending_metadata = {'success': False} post_attributes = {'timeout': self.timeout} if self.custom_headers: post_attributes['headers'] = self.custom_headers if not post_attributes.get('headers', None): post_attributes['headers'] = {...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generateIdentityKeyPair(): """ Generate an identity key pair. Clients should only do this once, at install time. @return the generated IdentityKeyPair. """
keyPair = Curve.generateKeyPair() publicKey = IdentityKey(keyPair.getPublicKey()) serialized = '0a21056e8936e8367f768a7bba008ade7cf58407bdc7a6aae293e2c' \ 'b7c06668dcd7d5e12205011524f0c15467100dd603e0d6020f4d293' \ 'edfbcd82129b14a88791ac81365c' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generatePreKeys(start, count): """ Generate a list of PreKeys. Clients should do this at install time, and subsequently any time the list of PreKeys stored o...
results = [] start -= 1 for i in range(0, count): preKeyId = ((start + i) % (Medium.MAX_VALUE - 1)) + 1 results.append(PreKeyRecord(preKeyId, Curve.generateKeyPair())) return 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 validate_valid_transition(enum, from_value, to_value): """ Validate that to_value is a valid choice and that to_value is a valid transition from from_value. ...
validate_available_choice(enum, to_value) if hasattr(enum, '_transitions') and not enum.is_valid_transition(from_value, to_value): message = _(six.text_type('{enum} can not go from "{from_value}" to "{to_value}"')) raise InvalidStatusOperationError(message.format( enum=enum.__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 validate_available_choice(enum, to_value): """ Validate that to_value is defined as a value in enum. """
if to_value is None: return if type(to_value) is not int: try: to_value = int(to_value) except ValueError: message_str = "'{value}' cannot be converted to int" message = _(six.text_type(message_str)) raise InvalidStatusOperationError(mess...
<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(self): """Open the connection wit the device."""
try: self.device.open() except ConnectTimeoutError as cte: raise ConnectionException(cte.message) self.device.timeout = self.timeout self.device._conn._session.transport.set_keepalive(self.keepalive) if hasattr(self.device, "cu"): # make sure ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare_config(self): """Compare candidate config with running."""
diff = self.device.cu.diff() if diff is None: return '' else: return diff.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 get_facts(self): """Return facts of the device."""
output = self.device.facts uptime = self.device.uptime or -1 interfaces = junos_views.junos_iface_table(self.device) interfaces.get() interface_list = interfaces.keys() return { 'vendor': u'Juniper', 'model': py23_compat.text_type(output['model...
<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_ntp_peers(self): """Return the NTP peers configured on the device."""
ntp_table = junos_views.junos_ntp_peers_config_table(self.device) ntp_table.get() ntp_peers = ntp_table.items() if not ntp_peers: return {} return {napalm_base.helpers.ip(peer[0]): {} for peer in ntp_peers}
<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_ntp_servers(self): """Return the NTP servers configured on the device."""
ntp_table = junos_views.junos_ntp_servers_config_table(self.device) ntp_table.get() ntp_servers = ntp_table.items() if not ntp_servers: return {} return {napalm_base.helpers.ip(server[0]): {} for server in ntp_servers}
<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_probes_config(self): """Return the configuration of the RPM probes."""
probes = {} probes_table = junos_views.junos_rpm_probes_config_table(self.device) probes_table.get() probes_table_items = probes_table.items() for probe_test in probes_table_items: test_name = py23_compat.text_type(probe_test[0]) test_details = { ...
<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_probes_results(self): """Return the results of the RPM probes."""
probes_results = {} probes_results_table = junos_views.junos_rpm_probes_results_table(self.device) probes_results_table.get() probes_results_items = probes_results_table.items() for probe_result in probes_results_items: probe_name = py23_compat.text_type(probe_resu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def traceroute(self, destination, source=C.TRACEROUTE_SOURCE, ttl=C.TRACEROUTE_TTL, timeout=C.TRACEROUTE_TIMEOUT, vrf=C.TRACEROUTE_VRF): """Execute traceroute an...
traceroute_result = {} # calling form RPC does not work properly :( # but defined junos_route_instance_table just in case source_str = '' maxttl_str = '' wait_str = '' vrf_str = '' if source: source_str = ' source {source}'.format(source=so...
<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, request, format=None): """ Remove all auth tokens owned by request.user. """
tokens = Token.objects.filter(user=request.user) for token in tokens: token.delete() content = {'success': _('User logged out.')} return Response(content, status=status.HTTP_200_OK)
<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_attrs_to_values(self, response={}): """ Set attributes to dictionary values so can access via dot notation. """
for key in response.keys(): setattr(self, key, response[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 doc(self, groups=None, set_location=True, **properties): """Add flask route to autodoc for automatic documentation Any route decorated with this method will ...
def decorator(f): # Get previous group list (if any) if f in self.func_groups: groupset = self.func_groups[f] else: groupset = set() # Set group[s] if type(groups) is list: groupset.update(groups) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unsaved_files_dialog( self, all_files=False, with_cancel=True, with_discard=True): """Return true if OK to continue with close or quit or whatever"""
for image in self.images: if image.metadata.changed() and (all_files or image.selected): break else: return True dialog = QtWidgets.QMessageBox() dialog.setWindowTitle(self.tr('Photini: unsaved data')) dialog.setText(self.tr('<h3>Some imag...
<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_ISO_8601(cls, date_string, time_string, tz_string): """Sufficiently general ISO 8601 parser. Inputs must be in "basic" format, i.e. no '-' or ':' separa...
# parse tz_string if tz_string: tz_offset = (int(tz_string[1:3]) * 60) + int(tz_string[3:]) if tz_string[0] == '-': tz_offset = -tz_offset else: tz_offset = None if time_string == '000000': # assume no time information ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xpath(self, xpath): """ Finds another node by XPath originating at the current node. """
return [self.get_node_factory().create(node_id) for node_id in self._get_xpath_ids(xpath).split(",") if node_id]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def css(self, css): """ Finds another node by a CSS selector relative to the current node. """
return [self.get_node_factory().create(node_id) for node_id in self._get_css_ids(css).split(",") if node_id]
<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_bool_attr(self, name): """ Returns the value of a boolean HTML attribute like `checked` or `disabled` """
val = self.get_attr(name) return val is not None and val.lower() in ("true", 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 set_attr(self, name, value): """ Sets the value of an attribute. """
self.exec_script("node.setAttribute(%s, %s)" % (repr(name), repr(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 value(self): """ Returns the node's value. """
if self.is_multi_select(): return [opt.value() for opt in self.xpath(".//option") if opt["selected"]] else: return self._invoke("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 set_header(self, key, value): """ Sets a HTTP header for future requests. """
self.conn.issue_command("Header", _normalize_header(key), 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 headers(self): """ Returns a list of the last HTTP response headers. Header keys are normalized to capitalized form, as in `User-Agent`. """
headers = self.conn.issue_command("Headers") res = [] for header in headers.split("\r"): key, value = header.split(": ", 1) for line in value.split("\n"): res.append((_normalize_header(key), line)) 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 eval_script(self, expr): """ Evaluates a piece of Javascript in the context of the current page and returns its value. """
ret = self.conn.issue_command("Evaluate", expr) return json.loads("[%s]" % ret)[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 cookies(self): """ Returns a list of all cookies in cookie string format. """
return [line.strip() for line in self.conn.issue_command("GetCookies").split("\n") if line.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 set_html(self, html, url = None): """ Sets custom HTML in our Webkit session and allows to specify a fake URL. Scripts and CSS is dynamically fetched as if t...
if url: self.conn.issue_command('SetHtml', html, url) else: self.conn.issue_command('SetHtml', html)
<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_proxy(self, host = "localhost", port = 0, user = "", password = ""): """ Sets a custom HTTP proxy to use for future requests. """
self.conn.issue_command("SetProxy", host, port, user, password)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self): """ Returns a new socket connection to this server. """
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("127.0.0.1", self._port)) return sock
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_line(self): """ Consume one line from the stream. """
while True: newline_idx = self.buf.find(b"\n") if newline_idx >= 0: res = self.buf[:newline_idx] self.buf = self.buf[newline_idx + 1:] return res chunk = self.f.recv(4096) if not chunk: raise EndOfStreamError() self.buf += 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 read(self, n): """ Consume `n` characters from the stream. """
while len(self.buf) < n: chunk = self.f.recv(4096) if not chunk: raise EndOfStreamError() self.buf += chunk res, self.buf = self.buf[:n], self.buf[n:] 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 _read_response(self): """ Reads a complete response packet from the server """
result = self.buf.read_line().decode("utf-8") if not result: raise NoResponseError("No response received from server.") msg = self._read_message() if result != "ok": raise InvalidResponseError(msg) return msg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read_message(self): """ Reads a single size-annotated message from the server """
size = int(self.buf.read_line().decode("utf-8")) return self.buf.read(size).decode("utf-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 log_error(self, error, message, detail=None, strip=4): "Add an error message and optional user message to the error list" if message: msg = message + ": " + error else: msg = error tb = traceback.format_stack() if sys.version_info >= (3, 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 equal(self, a, b, message=None): "Check if two values are equal" if a != b: self.log_error("{} != {}".format(str(a), str(b)), message) 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 is_not_none(self, a, message=None): "Check if a value is not None" if a is None: self.log_error("{} is None".format(str(a)), message) 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 enable(self): """Enable the chip."""
# Flip on the power and enable bits. self._write8(TCS34725_ENABLE, TCS34725_ENABLE_PON) time.sleep(0.01) self._write8(TCS34725_ENABLE, (TCS34725_ENABLE_PON | TCS34725_ENABLE_AEN))
<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_interrupt(self, enabled): """Enable or disable interrupts by setting enabled to True or False."""
enable_reg = self._readU8(TCS34725_ENABLE) if enabled: enable_reg |= TCS34725_ENABLE_AIEN else: enable_reg &= ~TCS34725_ENABLE_AIEN self._write8(TCS34725_ENABLE, enable_reg) time.sleep(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 _dict_to_html_attributes(d): """ Converts a dictionary to a string of ``key=\"value\"`` pairs. If ``None`` is provided as the dictionary an empty string is r...
if d is None: return "" return "".join(" {}=\"{}\"".format(key, value) for key, value in iter(d.items()))
<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_of_dicts_to_column_headers(list_of_dicts): """ Detects if all entries in an list of ``dict``'s have identical keys. Returns the keys if all keys are th...
if len(list_of_dicts) < 2 or not all(isinstance(item, dict) for item in list_of_dicts): return None column_headers = list_of_dicts[0].keys() for d in list_of_dicts[1:]: if len(d.keys()) != len(column_headers) or not all(header in d for header in column_headers): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _markup(self, entry): """ Recursively generates HTML for the current entry. Parameters entry : object Object to convert to HTML. Maybe be a single entity or ...
if entry is None: return "" if isinstance(entry, list): list_markup = "<ul>" for item in entry: list_markup += "<li>{:s}</li>".format(self._markup(item)) list_markup += "</ul>" return list_markup if isinstance(entry, di...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _maybe_club(self, list_of_dicts): """ If all keys in a list of dicts are identical, values from each ``dict`` are clubbed, i.e. inserted under a common colum...
column_headers = JsonConverter._list_of_dicts_to_column_headers(list_of_dicts) if column_headers is None: # common headers not found, return normal markup html_output = self._markup(list_of_dicts) else: html_output = self._table_opening_tag html_o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def msg(self, msg=None, ret_r=False): '''code's message''' if msg or ret_r: self._msg = msg return self return self._msg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def detail(self, detail=None, ret_r=False): '''code's detail''' if detail or ret_r: self._detail = detail return self return self._detail
<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, clnt): '''initialize api by YunpianClient''' assert clnt, "clnt is None" self._clnt = clnt self._apikey = clnt.apikey() self._version = clnt.conf(YP_VERSION, defval=VERSION_V2) self._charset = clnt.conf(HTTP_CHARSET, defval=CHARSET_UTF8) self._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 verify_param(self, param, must=[], r=None): '''return Code.ARGUMENT_MISSING if every key in must not found in param''' if APIKEY not in param: param[APIKEY] = self.apikey() r = Result() if r is None else r for p in must: if p not in param: r.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 custom_conf(self, conf): '''custom apikey and http parameters''' if conf: for (key, val) in conf.items(): self.__conf[key] = val return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def api(self, name): '''return special API by package's name''' assert name, 'name is none' if flow.__name__ == name: api = flow.FlowApi() elif sign.__name__ == name: api = sign.SignApi() elif sms.__name__ == name: api = sms.SmsApi() 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 conf(self, key=None, defval=None): '''return YunpianConf if key=None, else return value in YunpianConf''' if key is None: return self._ypconf val = self._ypconf.conf(key) return defval if val is None else 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 post(self, url, data, charset=CHARSET_UTF8, headers={}): '''response json text''' if 'Api-Lang' not in headers: headers['Api-Lang'] = 'python' if 'Content-Type' not in headers: headers['Content-Type'] = "application/x-www-form-urlencoded;charset=" + charset rs...
<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_resolver(app_name=None, pattern_kwargs=None, name=None): ''' Registers the given app_name with DMP and adds convention-based url patterns for it. This function is meant to be called in a project's urls.py. ''' urlconf = URLConf(app_name, pattern_kwargs) resolver = re_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 dmp_paths_for_app(app_name, pattern_kwargs=None, pretty_app_name=None): '''Utility function that creates the default patterns for an app''' dmp = apps.get_app_config('django_mako_plus') # Because these patterns are subpatterns within the app's resolver, # we don't include the /app/ in the pattern --...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dmp_path(regex, kwargs=None, name=None, app_name=None): ''' Creates a DMP-style, convention-based pattern that resolves to various view functions based on the 'dmp_page' value. The following should exist as 1) regex named groups or 2) items in the kwargs dict: dmp_app Should 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 alternate_syntax(local, using, **kwargs): ''' A Mako filter that renders a block of text using a different template engine than Mako. The named template engine must be listed in settings.TEMPLATES. The template context variables are available in the embedded template. Specify kwargs to add add...
<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_view_function(module_name, function_name, fallback_app=None, fallback_template=None, verify_decorator=True): ''' Retrieves a view function from the cache, finding it if the first time. Raises ViewDoesNotExist if not found. This is called by resolver.py. ''' # first check the cache (without ...
<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_view_function(module_name, function_name, fallback_app=None, fallback_template=None, verify_decorator=True): ''' Finds a view function, class-based view, or template view. Raises ViewDoesNotExist if not found. ''' dmp = apps.get_app_config('django_mako_plus') # I'm first calling find_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 iter_related(self): ''' Generator function that iterates this object's related providers, which includes this provider. ''' for tpl in self.provider_run.templates: yield tpl.providers[self.index]
<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_cache_item(self): '''Gets the cached item. Raises AttributeError if it hasn't been set.''' if settings.DEBUG: raise AttributeError('Caching disabled in DEBUG mode') return getattr(self.template, self.options['template_cache_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 flatten(*args): '''Generator that recursively flattens embedded lists, tuples, etc.''' for arg in args: if isinstance(arg, collections.Iterable) and not isinstance(arg, (str, bytes)): yield from flatten(*arg) else: yield arg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def crc32(filename): ''' Calculates the CRC checksum for a file. Using CRC32 because security isn't the issue and don't need perfect noncollisions. We just need to know if a file has changed. On my machine, crc32 was 20 times faster than any hashlib algorithm, including blake and md5 algorithms...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def compile_mako_files(self, app_config): '''Compiles the Mako templates within the apps of this system''' # go through the files in the templates, scripts, and styles directories for subdir_name in self.SEARCH_DIRS: subdir = subdir_name.format( app_path=app_config.pa...
<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_string(self, template_code): ''' Compiles a template from the given string. This is one of the required methods of Django template engines. ''' dmp = apps.get_app_config('django_mako_plus') mako_template = Template(template_code, imports=dmp.template_imports, inp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _register_converter(cls, conv_func, conv_type): '''Triggered by the @converter_function decorator''' cls.converters.append(ConverterFunctionInfo(conv_func, conv_type, len(cls.converters))) cls._sort_converters()
<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_converters(cls, app_ready=False): '''Sorts the converter functions''' # app_ready is True when called from DMP's AppConfig.ready() # we can't sort before then because models aren't ready cls._sorting_enabled = cls._sorting_enabled or app_ready if cls._sorting_enabled: ...
<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_parameters(self, request, *args, **kwargs): ''' Iterates the urlparams and converts them according to the type hints in the current view function. This is the primary function of the class. ''' args = list(args) urlparam_i = 0 parameters = se...
<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_value(self, value, parameter, request): ''' Converts a parameter value in the view function call. value: value from request.dmp.urlparams to convert The value will always be a string, even if empty '' (never None). parameter: an instanc...