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 _get_site_amplification_term(self, C, vs30): """ Returns the site amplification term for the case in which Vs30 is used directly """
return C["gamma"] * np.log10(vs30 / self.CONSTS["Vref"])
<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_site_amplification_term(self, C, vs30): """ Returns the site amplification given Eurocode 8 site classification """
f_s = np.zeros_like(vs30) # Site class B idx = np.logical_and(vs30 < 800.0, vs30 >= 360.0) f_s[idx] = C["eB"] # Site Class C idx = np.logical_and(vs30 < 360.0, vs30 >= 180.0) f_s[idx] = C["eC"] # Site Class D idx = vs30 < 180.0 f_s[idx] = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_mean(self, C, rup, dists, sites): """ Returns the mean value of ground motion - noting that in this case the style-of-faulting term is neglected """
return (self._get_magnitude_scaling_term(C, rup.mag) + self._get_distance_scaling_term(C, dists.rjb, rup.mag) + self._get_site_amplification_term(C, sites.vs30))
<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_loss_tables(dstore): """ Compute the total losses by rupture and losses by rlzi. """
oq = dstore['oqparam'] L = len(oq.loss_dt().names) R = dstore['csm_info'].get_num_rlzs() serials = dstore['ruptures']['serial'] idx_by_ser = dict(zip(serials, range(len(serials)))) tbl = numpy.zeros((len(serials), L), F32) lbr = numpy.zeros((R, L), F32) # losses by rlz for rec in dstor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def html(header_rows): """ Convert a list of tuples describing a table into a HTML string """
name = 'table%d' % next(tablecounter) return HtmlTable([map(str, row) for row in header_rows], name).render()
<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_tabs(tag_ids, tag_status, tag_contents): """ Return a HTML string containing all the tabs we want to display """
templ = ''' <div id="tabs"> <ul> %s </ul> %s </div>''' lis = [] contents = [] for i, (tag_id, status, tag_content) in enumerate( zip(tag_ids, tag_status, tag_contents), 1): mark = '.' if status == 'complete' else '!' lis.append('<li><a href="#tabs-%d">%s%s</a></li>' % (i, ta...
<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_report(isodate='today'): """ Build a HTML report with the computations performed at the given isodate. Return the name of the report, which is saved in ...
if isodate == 'today': isodate = date.today() else: isodate = date(*time.strptime(isodate, '%Y-%m-%d')[:3]) isodate1 = isodate + timedelta(1) # +1 day tag_ids = [] tag_status = [] tag_contents = [] # the fetcher returns an header which is stripped with [1:] jobs = dbc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scenario_risk(riskinputs, riskmodel, param, monitor): """ Core function for a scenario computation. :param riskinput: a of :class:`openquake.risklib.riskinpu...
E = param['E'] L = len(riskmodel.loss_types) result = dict(agg=numpy.zeros((E, L), F32), avg=[], all_losses=AccumDict(accum={})) for ri in riskinputs: for out in riskmodel.gen_outputs(ri, monitor, param['epspath']): r = out.rlzi weight = param['weights'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _check_depth_limits(input_dict): '''Returns the default upper and lower depth values if not in dictionary :param input_dict: Dictionary corresponding to the kwargs dictionary of calling function :returns: 'upper_depth': Upper seismogenic depth (float) 'lower_depth': Lower seism...
<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_decimal_from_datetime(time): ''' As the decimal time function requires inputs in the form of numpy arrays need to convert each value in the datetime object to a single numpy array ''' # Get decimal seconds from seconds + microseconds temp_seconds = np.float(time.second) + (np.floa...
<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_catalogue(self, valid_id): ''' Method to post-process the catalogue based on the selection options :param numpy.ndarray valid_id: Boolean vector indicating whether each event is selected (True) or not (False) :returns: Catalogue of selecte...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def within_polygon(self, polygon, distance=None, **kwargs): ''' Select earthquakes within polygon :param polygon: Centre point as instance of nhlib.geo.polygon.Polygon class :param float distance: Buffer distance (km) (can take negative values) :returns...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def circular_distance_from_point(self, point, distance, **kwargs): ''' Select earthquakes within a distance from a Point :param point: Centre point as instance of nhlib.geo.point.Point class :param float distance: Distance (km) :returns: Ins...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def cartesian_square_centred_on_point(self, point, distance, **kwargs): ''' Select earthquakes from within a square centered on a point :param point: Centre point as instance of nhlib.geo.point.Point class :param distance: Distance (km) :returns: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def within_joyner_boore_distance(self, surface, distance, **kwargs): ''' Select events within a Joyner-Boore distance of a fault :param surface: Fault surface as instance of nhlib.geo.surface.base.SimpleFaultSurface or as instance of nhlib.geo.surface.Comple...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def within_rupture_distance(self, surface, distance, **kwargs): ''' Select events within a rupture distance from a fault surface :param surface: Fault surface as instance of nhlib.geo.surface.base.BaseSurface :param float distance: Rupture distance (km) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def within_time_period(self, start_time=None, end_time=None): ''' Select earthquakes occurring within a given time period :param start_time: Earliest time (as datetime.datetime object) :param end_time: Latest time (as datetime.datetime object) :returns:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def within_depth_range(self, lower_depth=None, upper_depth=None): ''' Selects events within a specified depth range :param float lower_depth: Lower depth for consideration :param float upper_depth: Upper depth for consideration :returns: Ins...
<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_cluster_set(self, vcl): """ For a given catalogue and list of cluster IDs this function splits the catalogue into a dictionary containing an individua...
num_clust = np.max(vcl) cluster_set = [] for clid in range(0, num_clust + 1): idx = np.where(vcl == clid)[0] cluster_cat = deepcopy(self.catalogue) cluster_cat.select_catalogue_events(idx) cluster_set.append((clid, cluster_cat)) return dic...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def within_bounding_box(self, limits): """ Selects the earthquakes within a bounding box. :parameter limits: A list or a numpy array with four elements in the fo...
is_valid = np.logical_and( self.catalogue.data['longitude'] >= limits[0], np.logical_and(self.catalogue.data['longitude'] <= limits[2], np.logical_and( self.catalogue.data['latitude'] >= limits[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 get_calc_ids(datadir=None): """ Extract the available calculation IDs from the datadir, in order. """
datadir = datadir or get_datadir() if not os.path.exists(datadir): return [] calc_ids = set() for f in os.listdir(datadir): mo = re.match(CALC_REGEX, f) if mo: calc_ids.add(int(mo.group(2))) return sorted(calc_ids)
<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_last_calc_id(datadir=None): """ Extract the latest calculation ID from the given directory. If none is found, return 0. """
datadir = datadir or get_datadir() calcs = get_calc_ids(datadir) if not calcs: return 0 return calcs[-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 open(self, mode): """ Open the underlying .hdf5 file and the parent, if any """
if self.hdf5 == (): # not already open kw = dict(mode=mode, libver='latest') if mode == 'r': kw['swmr'] = True try: self.hdf5 = hdf5.File(self.filename, **kw) except OSError as exc: raise OSError('%s in %s' % (exc,...
<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_dset(self, key, dtype, shape=(None,), compression=None, fillvalue=0, attrs=None): """ Create a one-dimensional HDF5 dataset. :param key: name of the d...
return hdf5.create( self.hdf5, key, dtype, shape, compression, fillvalue, attrs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extend(self, key, array, **attrs): """ Extend the dataset associated to the given key; create it if needed :param key: name of the dataset :param array: arra...
try: dset = self.hdf5[key] except KeyError: dset = hdf5.create(self.hdf5, key, array.dtype, shape=(None,) + array.shape[1:]) hdf5.extend(dset, array) for k, v in attrs.items(): dset.attrs[k] = v return dset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, key, kw): """ Update the object associated to `key` with the `kw` dictionary; works for LiteralAttrs objects and automatically flushes. """
if key not in self: obj = hdf5.LiteralAttrs() else: obj = self[key] vars(obj).update(kw) self[key] = obj self.flush()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export_path(self, relname, export_dir=None): """ Return the path of the exported file by adding the export_dir in front, the calculation ID at the end. :para...
# removing inner slashed to avoid creating intermediate directories name, ext = relname.replace('/', '-').rsplit('.', 1) newname = '%s_%s.%s' % (name, self.calc_id, ext) if export_dir is None: export_dir = self.export_dir return os.path.join(export_dir, newname)
<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_fname(self, prefix, postfix, fmt, export_dir=None): """ Build a file name from a realization, by using prefix and extension. :param prefix: the prefix ...
if hasattr(postfix, 'sm_lt_path'): # is a realization fname = '%s-rlz-%03d.%s' % (prefix, postfix.ordinal, fmt) else: fname = prefix + ('-%s' % postfix if postfix else '') + '.' + fmt return self.export_path(fname, export_dir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flush(self): """Flush the underlying hdf5 file"""
if self.parent != (): self.parent.flush() if self.hdf5: # is open self.hdf5.flush()
<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 underlying hdf5 file"""
if self.parent != (): self.parent.flush() self.parent.close() if self.hdf5: # is open self.hdf5.flush() self.hdf5.close() self.hdf5 = ()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getsize(self, key=None): """ Return the size in byte of the output associated to the given key. If no key is given, returns the total size of all files. """
if key is None: return os.path.getsize(self.filename) return hdf5.ByteCounter.get_nbytes( h5py.File.__getitem__(self.hdf5, 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 maybe_encode(value): """ If value is a sequence of strings, encode it """
if isinstance(value, (list, tuple)) and isinstance(value[0], str): return encode(value) return 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 extend(dset, array, **attrs): """ Extend an extensible dataset with an array of a compatible dtype. :param dset: an h5py dataset :param array: an array of le...
length = len(dset) if len(array) == 0: return length newlength = length + len(array) if array.dtype.name == 'object': # vlen array shape = (newlength,) + preshape(array[0]) else: shape = (newlength,) + array.shape[1:] dset.resize(shape) dset[length:newlength] = arra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extend3(filename, key, array, **attrs): """ Extend an HDF5 file dataset with the given array """
with h5py.File(filename) as h5: try: dset = h5[key] except KeyError: if array.dtype.name == 'object': # vlen array shape = (None,) + preshape(array[0]) else: shape = (None,) + array.shape[1:] dset = create(h5, key, arr...
<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_nbytes(dset): """ If the dataset has an attribute 'nbytes', return it. Otherwise get the size of the underlying array. Returns None if the dataset is act...
if 'nbytes' in dset.attrs: # look if the dataset has an attribute nbytes return dset.attrs['nbytes'] elif hasattr(dset, 'dtype'): # else extract nbytes from the underlying array return dset.size * numpy.zeros(1, dset.dtype).nbytes
<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_array(values): """ Decode the values which are bytestrings. """
out = [] for val in values: try: out.append(val.decode('utf8')) except AttributeError: out.append(val) return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def temporary(cls): """ Returns a temporary hdf5 file, open for writing. The temporary name is stored in the .path attribute. It is the user responsability to re...
fh, path = tempfile.mkstemp(suffix='.hdf5') os.close(fh) self = cls(path, 'w') self.path = path 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 save_vlen(self, key, data): """ Save a sequence of variable-length arrays :param key: name of the dataset :param data: data to store as a list of arrays """
shape = (None,) + data[0].shape[:-1] try: dset = self[key] except KeyError: vdt = h5py.special_dtype(vlen=data[0].dtype) dset = create(self, key, vdt, shape, fillvalue=None) nbytes = dset.attrs.get('nbytes', 0) totlen = dset.attrs.get('totlen'...
<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_nbytes(self, key, nbytes=None): """ Set the `nbytes` attribute on the HDF5 object identified by `key`. """
obj = super().__getitem__(key) if nbytes is not None: # size set from outside obj.attrs['nbytes'] = nbytes else: # recursively determine the size of the datagroup obj.attrs['nbytes'] = nbytes = ByteCounter.get_nbytes(obj) return nbytes
<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_delta(self, stds, dists): """ Computes the additional delta to be used for the computation of the upp and low models """
delta = np.maximum((0.1-0.001*dists.repi), np.zeros_like(dists.repi)) return delta
<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_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ Returns only the mean values. See documentation for method `GroundShakingIntensityMode...
# distances distsl = copy.copy(dists) distsl.rjb, distsl.rrup = \ utils.get_equivalent_distances_east(rup.mag, dists.repi) # # Pezeshk et al. 2011 - Rrup mean1, stds1 = super().get_mean_and_stddevs(sites, rup, distsl, imt, ...
<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_checked(self, state): """ Sets the Widget checked state. :param state: New check state. :type state: bool :return: Method success. :rtype: bool """
if not self.__checkable: return False if state: self.__checked = True self.setPixmap(self.__active_pixmap) else: self.__checked = False self.setPixmap(self.__default_pixmap) self.toggled.emit(state) 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 set_menu(self, menu): """ Sets the Widget menu. :param menu: Menu. :type menu: QMenu :return: Method success. :rtype: bool """
self.__menu = menu if not self.parent(): return False parent = [parent for parent in umbra.ui.common.parents_walker(self)].pop() for action in self.__menu.actions(): not action.shortcut().isEmpty() and parent.addAction(action) 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 get(self, path, default=None): """ Returns given path value. :param path: Path name. :type path: unicode :param default: Default value if path is not found. ...
try: return self.__getitem__(path) except KeyError as error: return default
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __watch_file_system(self): """ Watches the file system for paths that have been changed or invalidated on disk. """
for path, data in self.__paths.items(): stored_modified_time, is_file = data try: if not foundations.common.path_exists(path): LOGGER.warning( "!> {0} | '{1}' path has been invalidated and will be unregistered!".format( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_path(self, path, modified_time=None): """ Registers given path. :param path: Path name. :type path: unicode :param modified_time: Custom modified ti...
if not foundations.common.path_exists(path): raise foundations.exceptions.PathExistsError("{0} | '{1}' path doesn't exists!".format( self.__class__.__name__, path)) if path in self: raise umbra.exceptions.PathRegistrationError("{0} | '{1}' path is already regis...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unregister_path(self, path): """ Unregisters given path. :param path: Path name. :type path: unicode :return: Method success. :rtype: bool """
if not path in self: raise umbra.exceptions.PathExistsError("{0} | '{1}' path isn't registered!".format( self.__class__.__name__, path)) del (self.__paths[path]) 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 get_path_modified_time(path): """ Returns given path modification time. :param path: Path. :type path: unicode :return: Modification time. :rtype: int """
return float(foundations.common.get_first_item(str(os.path.getmtime(path)).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 _post_login_page(self): """Login to Janrain."""
# Prepare post data data = { "form": "signInForm", "client_id": JANRAIN_CLIENT_ID, "redirect_uri": "https://www.fido.ca/pages/#/", "response_type": "token", "locale": "en-US", "userID": self.username, "currentPassword":...
<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_token(self): """Get token from JanRain."""
# HTTP request try: raw_res = yield from self._session.get(TOKEN_URL, headers=self._headers, timeout=self._timeout) except OSError: raise PyFidoError("Can not get token"...
<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_account_number(self, token, uuid): """Get fido account number."""
# Data data = {"accessToken": token, "uuid": uuid} # Http request try: raw_res = yield from self._session.post(ACCOUNT_URL, data=data, headers=self._header...
<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_balance(self, account_number): """Get current balance from Fido."""
# Prepare data data = {"ctn": self.username, "language": "en-US", "accountNumber": account_number} # Http request try: raw_res = yield from self._session.post(BALANCE_URL, data=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 _get_fido_dollar(self, account_number, number): """Get current Fido dollar balance."""
# Prepare data data = json.dumps({"fidoDollarBalanceFormList": [{"phoneNumber": number, "accountNumber": account_number}]}) # Prepare headers headers_json = self._headers.copy() headers_json["Content-Type"] = "application/j...
<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_usage(self, account_number, number): """Get Fido usage. Get the following data - talk - text - data Roaming data is not supported yet """
# Prepare data data = {"ctn": number, "language": "en-US", "accountNumber": account_number} # Http request try: raw_res = yield from self._session.post(USAGE_URL, data=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 fetch_data(self): """Fetch the latest data from Fido."""
# Get http session yield from self._get_httpsession() # Post login page yield from self._post_login_page() # Get token token_uuid = yield from self._get_token() # Get account number account_number = yield from self._get_account_number(*token_uuid) ...
<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( command, abort=True, capture=False, verbose=False, echo=False, stream=None, ): """Run a command locally. Arguments: command: a command to execute. a...
stream = stream or sys.stdout if echo: out = stream out.write(u'$ %s' % command) # Capture stdout and stderr in the same stream command = u'%s 2>&1' % command if verbose: out = stream err = stream else: out = subprocess.PIPE err = subprocess.PI...
<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_message(base): """ Given a MailBase, this will construct a MIME part that is canonicalized for use with the Python email API. """
ctype, ctparams = base.get_content_type() if not ctype: if base.parts: ctype = 'multipart/mixed' else: ctype = 'text/plain' maintype, subtype = ctype.split('/') is_text = maintype == 'text' is_multipart = maintype == 'multipart' if base.parts and not i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_message(self): """ Returns raw email.Message instance. Validates message first. """
self.validate() bodies = [(self.body, 'text/plain'), (self.html, 'text/html')] for idx, (val, content_type) in enumerate(bodies): if val is None: bodies[idx] = None elif isinstance(val, Attachment): bodies[idx] = val.to_mailbase...
<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_bad_headers(self): """ Checks for bad headers i.e. newlines in subject, sender or recipients. """
headers = [self.subject, self.sender] headers += list(self.send_to) headers += dict(self.extra_headers).values() for val in headers: for c in '\r\n': if c in val: 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 validate(self): """ Checks if message is valid and raises appropriate exception. """
if not (self.recipients or self.cc or self.bcc): raise InvalidMessage("No recipients have been added") if not self.body and not self.html: raise InvalidMessage("No body has been set") if not self.sender: raise InvalidMessage("No sender address has been set...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_settings(cls, settings, prefix='mail.'): """Create a new instance of 'DebugMailer' from settings dict. :param settings: a settings dict-like :param pref...
settings = settings or {} top_level_directory = settings.get(prefix+'top_level_directory') if top_level_directory is None: raise ValueError("DebugMailer: must specify " "'%stop_level_directory'" % prefix) return cls(top_level_directory)
<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, message, fail_silently=False): """Save message to a file for debugging """
seeds = '1234567890qwertyuiopasdfghjklzxcvbnm' file_part1 = datetime.now().strftime('%Y%m%d%H%M%S') file_part2 = ''.join(sample(seeds, 4)) filename = join(self.tld, '%s_%s.msg' % (file_part1, file_part2)) with open(filename, 'w') as fd: fd.write(str(message.to_messag...
<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_settings(cls, settings, prefix='mail.'): """Create a new instance of 'Mailer' from settings dict. :param settings: a settings dict-like :param prefix: p...
settings = settings or {} kwarg_names = [prefix + k for k in ( 'host', 'port', 'username', 'password', 'tls', 'ssl', 'keyfile', 'certfile', 'queue_path', 'debug', 'default_sender')] size = len(prefix) kwargs = dict(...
<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_immediately(self, message, fail_silently=False): """Send a message immediately, outside the transaction manager. If there is a connection error to the m...
try: return self.smtp_mailer.send(*self._message_args(message)) except smtplib.socket.error: if not fail_silently: raise
<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_to_queue(self, message): """Add a message to a maildir queue. In order to handle this, the setting 'mail.queue_path' must be provided and must point to ...
if not self.queue_delivery: raise RuntimeError("No queue_path provided") return self.queue_delivery.send(*self._message_args(message))
<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_seq(obj): """ Check if an object is a sequence. """
return (not is_str(obj) and not is_dict(obj) and (hasattr(obj, "__getitem__") or hasattr(obj, "__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 update(dst, src): """ Recursively update values in dst from src. Unlike the builtin dict.update() function, this method will decend into nested dicts, updati...
for k, v in src.items(): if isinstance(v, Mapping): r = update(dst.get(k, {}), v) dst[k] = r else: dst[k] = src[k] return dst
<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_values(src): """ Recursively get values in dict. Unlike the builtin dict.values() function, this method will descend into nested dicts, returning all ne...
for v in src.values(): if isinstance(v, dict): for v in dict_values(v): yield v else: yield v
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_path_package(thepath): """ Takes a file system path and returns the module object of the python package the said path belongs to. If the said path can n...
pname = find_path_package_name(thepath) if not pname: return None fromlist = b'' if six.PY2 else '' return __import__(pname, globals(), locals(), [fromlist])
<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_path_package_name(thepath): """ Takes a file system path and returns the name of the python package the said path belongs to. If the said path can not b...
module_found = False last_module_found = None continue_ = True while continue_: module_found = is_path_python_module(thepath) next_path = path.dirname(thepath) if next_path == thepath: continue_ = False if module_found: init_names = ['__init__%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 is_path_python_module(thepath): """ Given a path, find out of the path is a python module or is inside a python module. """
thepath = path.normpath(thepath) if path.isfile(thepath): base, ext = path.splitext(thepath) if ext in _py_suffixes: return True return False if path.isdir(thepath): for suffix in _py_suffixes: if path.isfile(path.join(thepath, '__init__%s' % suffix...
<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_files(root, pattern): """Find all files matching the glob pattern recursively :param root: string :param pattern: string :return: list of file paths rel...
results = [] for base, dirs, files in os.walk(root): matched = fnmatch.filter(files, pattern) results.extend(os.path.join(base, f) for f in matched) 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 find_directories(root, pattern): """Find all directories matching the glob pattern recursively :param root: string :param pattern: string :return: list of di...
results = [] for base, dirs, files in os.walk(root): matched = fnmatch.filter(dirs, pattern) results.extend(os.path.join(base, d) for d in matched) 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 posargs_limiter(func, *args): """ takes a function a positional arguments and sends only the number of positional arguments the function is expecting """
posargs = inspect.getargspec(func)[0] length = len(posargs) if inspect.ismethod(func): length -= 1 if length == 0: return func() return func(*args[0:length])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compose(*functions): """Function composition on a series of functions. Remember that function composition runs right-to-left: `f . g . h = f(g(h(x)))`. As a ...
return functools.reduce(lambda f, g: lambda x: f(g(x)), functions, identity)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def first_where(pred, iterable, default=None): """Returns the first element in an iterable that meets the given predicate. :param default: is the default value t...
return next(six.moves.filter(pred, iterable), default)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def partition_iter(pred, iterable): """Partitions an iterable with a predicate into two iterables, one with elements satisfying the predicate and one with elemen...
left, right = itertools.tee(iterable, 2) return ( (x for x in left if pred(x)), (y for y in right if not pred(y)) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def partition_list(pred, iterable): """Partitions an iterable with a predicate into two lists, one with elements satisfying the predicate and one with elements t...
left, right = partition_iter(pred, iterable) return list(left), list(right)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def split_every(n, iterable): """Returns a generator that spits an iteratable into n-sized chunks. The last chunk may have less than n elements. See http://stack...
items = iter(iterable) return itertools.takewhile(bool, (list(itertools.islice(items, n)) for _ in itertools.count()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unique(iterable, key=identity): """Yields all the unique values in an iterable maintaining order"""
seen = set() for item in iterable: item_key = key(item) if item_key not in seen: seen.add(item_key) yield item
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iteritems(self): """ Sort and then iterate the dictionary """
sorted_data = sorted(self.data.iteritems(), self.cmp, self.key, self.reverse) for k,v in sorted_data: yield k,v
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _adapt_param(self, key, val): """ Adapt the value if an adapter is defined. """
if key in self.param_adapters: try: return self.param_adapters[key](val) except (AdaptError, AdaptErrors, TypeError, ValueError) as e: if hasattr(e, 'errors'): errors = e.errors else: errors = [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 input(self, *args, **kwargs): """ Adapt the input and check for errors. Returns a tuple of adapted (args, kwargs) or raises AnticipateErrors """
errors = [] if args and self.arg_names: args = list(args) # Replace args inline that have adapters for i, (key, val) in enumerate(izip(self.arg_names, args)): try: args[i] = self._adapt_param(key, val) except Antic...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def output(self, result): """ Adapts the result of a function based on the returns definition. """
if self.returns: errors = None try: return self._adapt_result(result) except AdaptErrors as e: errors = e.errors except AdaptError as e: errors = [e] raise AnticipateErrors( message='Ret...
<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, value): """Passes the value to FileField and resizes the image at the path the parent returns if needed. """
path = super(Image, self).clean(value) if path and self.size: self.resize_image(join(self.base_path, path)) return 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 calculate_dimensions(image_size, desired_size): """Return the Tuple with the arguments to pass to Image.crop. If the image is smaller than than the desired_s...
current_x, current_y = image_size target_x, target_y = desired_size if current_x < target_x and current_y < target_y: return None if current_x > target_x: new_x0 = floor(current_x / 2) new_x = new_x0 - ceil(target_x / 2) new_width = tar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def options(self, *args, **kwargs): """Default OPTIONS response If the 'cors' option is True, will respond with an empty response and set the 'Access-Control-All...
if getattr(options, 'cors', False): self.set_header('Access-Control-Allow-Headers', 'Content-Type, Authorization, ' 'Accept, X-Requested-With') self.set_header('Access-Control-Allow-Methods', 'OPTIONS, 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 write_error(self, status_code, **kwargs): """Override `write_error` in order to output JSON errors :param status_code: the response's status code, e.g. 500 "...
http_error = _get_http_error(kwargs) if http_error: self.finish(self._error_template(status_code, http_error.errors, http_error.source)) else: source = kwargs.get('source', getattr(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _error_template(cls, status_code, errors, source=None): """Construct JSON error response :param status_code: the http status code :param errors: string or li...
# this handles unhandled exceptions if isinstance(errors, basestring): errors_out = {'errors': [{'message': errors}]} elif isinstance(errors, (list, tuple)): errors_out = {'errors': [{'message': e} for e in errors]} else: errors_out = errors 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 get_json_body(self, required=None, validators=None): """Get JSON from the request body :param required: optionally provide a list of keys that should be in t...
content_type = self.request.headers.get('Content-Type', 'application/json') if 'application/json' not in content_type.split(';'): raise HTTPError(415, 'Content-Type should be application/json') if not self.request.body: err...
<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_token(self, token, requested_access): """ Check the token bearer is permitted to access the resource :param token: Access token :param requested_acces...
client = API(options.url_auth, auth_username=options.service_id, auth_password=options.client_secret, ssl_options=ssl_server_options()) headers = {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'applicatio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare(self): """If OAuth verification is required, validate provided token :raise: HTTPError if token does not have access """
requested_access = self.endpoint_access(self.request.method) use_oauth = getattr(options, 'use_oauth', None) if use_oauth and requested_access is not self.UNAUTHENTICATED_ACCESS: token = self.request.headers.get('Authorization', '').split(' ')[-1] if token: ...
<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_fast(xmlfile, element_name, attrnames, warn=False, optional=False): """ Parses the given attrnames from all elements with element_name @Note: The eleme...
prefixedAttrnames = [_prefix_keyword(a, warn) for a in attrnames] if optional: pattern = ''.join(['<%s' % element_name] + ['(\\s+%s="(?P<%s>[^"]*?)")?' % a for a in zip(attrnames, prefixedAttrnames)]) else: pattern = '.*'.join(['<%s' % element_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 tracing(pattern=None, out=None): """Print executed lines to stdout."""
_trace = partial(trace_line, pattern) if out is None: out = sys.stdout with redirect_stdout(out): sys.settrace(_trace) try: yield finally: sys.settrace(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 override_params(opening_char='{', closing_char='}', separator_char='|'): """ Override some character settings @type opening_char: str @param opening_char: Op...
global char_separator, char_opening, char_closing char_separator = separator_char char_opening = opening_char char_closing = closing_char
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unique(text): """ Return an unique text @type text: str @param text: Text written used spin syntax. @return: An unique text # Generate an unique sentence 'Th...
# check if the text is correct correct, error = _is_correct(text) if not correct: raise Exception(error) s = [] _all_unique_texts(text, s) return s[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 _all_unique_texts(text, final): """ Compute all the possible unique texts @type text: str @param text: Text written used spin syntax @type final: list @param...
if not char_opening in text: if not text in final: final.append(text) return stack = [] indexes = [] for i, c in enumerate(text): if c == char_closing: if stack[-1] == char_opening: start_index = indexes.pop() substring = ...
<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_correct(text): """ Check if the specified text has a correct spin syntax @type text: str @param text: Text written used spin syntax @rtype: tuple @return...
error = '' stack = [] for i, c in enumerate(text): if c == char_opening: stack.append(c) elif c == char_closing: if stack.count == 0: error = 'Syntax incorrect. Found "}" before "{"' break last_char = stack.pop() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_FunctionBody(self, node): """Visitor for `FunctionBody` AST node."""
for child in node.children: return_value = self.visit(child) if isinstance(child, ReturnStatement): return return_value if isinstance(child, (IfStatement, WhileStatement)): if return_value is not None: return return_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 visit_WhileStatement(self, node): """Visitor for `WhileStatement` AST node."""
while self.visit(node.condition): result = self.visit(node.compound) if result is not None: return result